kmemleak.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. /*
  2. * mm/kmemleak.c
  3. *
  4. * Copyright (C) 2008 ARM Limited
  5. * Written by Catalin Marinas <catalin.marinas@arm.com>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2 as
  9. * published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. *
  20. *
  21. * For more information on the algorithm and kmemleak usage, please see
  22. * Documentation/kmemleak.txt.
  23. *
  24. * Notes on locking
  25. * ----------------
  26. *
  27. * The following locks and mutexes are used by kmemleak:
  28. *
  29. * - kmemleak_lock (rwlock): protects the object_list modifications and
  30. * accesses to the object_tree_root. The object_list is the main list
  31. * holding the metadata (struct kmemleak_object) for the allocated memory
  32. * blocks. The object_tree_root is a priority search tree used to look-up
  33. * metadata based on a pointer to the corresponding memory block. The
  34. * kmemleak_object structures are added to the object_list and
  35. * object_tree_root in the create_object() function called from the
  36. * kmemleak_alloc() callback and removed in delete_object() called from the
  37. * kmemleak_free() callback
  38. * - kmemleak_object.lock (spinlock): protects a kmemleak_object. Accesses to
  39. * the metadata (e.g. count) are protected by this lock. Note that some
  40. * members of this structure may be protected by other means (atomic or
  41. * kmemleak_lock). This lock is also held when scanning the corresponding
  42. * memory block to avoid the kernel freeing it via the kmemleak_free()
  43. * callback. This is less heavyweight than holding a global lock like
  44. * kmemleak_lock during scanning
  45. * - scan_mutex (mutex): ensures that only one thread may scan the memory for
  46. * unreferenced objects at a time. The gray_list contains the objects which
  47. * are already referenced or marked as false positives and need to be
  48. * scanned. This list is only modified during a scanning episode when the
  49. * scan_mutex is held. At the end of a scan, the gray_list is always empty.
  50. * Note that the kmemleak_object.use_count is incremented when an object is
  51. * added to the gray_list and therefore cannot be freed. This mutex also
  52. * prevents multiple users of the "kmemleak" debugfs file together with
  53. * modifications to the memory scanning parameters including the scan_thread
  54. * pointer
  55. *
  56. * The kmemleak_object structures have a use_count incremented or decremented
  57. * using the get_object()/put_object() functions. When the use_count becomes
  58. * 0, this count can no longer be incremented and put_object() schedules the
  59. * kmemleak_object freeing via an RCU callback. All calls to the get_object()
  60. * function must be protected by rcu_read_lock() to avoid accessing a freed
  61. * structure.
  62. */
  63. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  64. #include <linux/init.h>
  65. #include <linux/kernel.h>
  66. #include <linux/list.h>
  67. #include <linux/sched.h>
  68. #include <linux/jiffies.h>
  69. #include <linux/delay.h>
  70. #include <linux/module.h>
  71. #include <linux/kthread.h>
  72. #include <linux/prio_tree.h>
  73. #include <linux/gfp.h>
  74. #include <linux/fs.h>
  75. #include <linux/debugfs.h>
  76. #include <linux/seq_file.h>
  77. #include <linux/cpumask.h>
  78. #include <linux/spinlock.h>
  79. #include <linux/mutex.h>
  80. #include <linux/rcupdate.h>
  81. #include <linux/stacktrace.h>
  82. #include <linux/cache.h>
  83. #include <linux/percpu.h>
  84. #include <linux/hardirq.h>
  85. #include <linux/mmzone.h>
  86. #include <linux/slab.h>
  87. #include <linux/thread_info.h>
  88. #include <linux/err.h>
  89. #include <linux/uaccess.h>
  90. #include <linux/string.h>
  91. #include <linux/nodemask.h>
  92. #include <linux/mm.h>
  93. #include <asm/sections.h>
  94. #include <asm/processor.h>
  95. #include <asm/atomic.h>
  96. #include <linux/kmemleak.h>
  97. /*
  98. * Kmemleak configuration and common defines.
  99. */
  100. #define MAX_TRACE 16 /* stack trace length */
  101. #define MSECS_MIN_AGE 5000 /* minimum object age for reporting */
  102. #define SECS_FIRST_SCAN 60 /* delay before the first scan */
  103. #define SECS_SCAN_WAIT 600 /* subsequent auto scanning delay */
  104. #define GRAY_LIST_PASSES 25 /* maximum number of gray list scans */
  105. #define MAX_SCAN_SIZE 4096 /* maximum size of a scanned block */
  106. #define BYTES_PER_POINTER sizeof(void *)
  107. /* GFP bitmask for kmemleak internal allocations */
  108. #define GFP_KMEMLEAK_MASK (GFP_KERNEL | GFP_ATOMIC)
  109. /* scanning area inside a memory block */
  110. struct kmemleak_scan_area {
  111. struct hlist_node node;
  112. unsigned long offset;
  113. size_t length;
  114. };
  115. /*
  116. * Structure holding the metadata for each allocated memory block.
  117. * Modifications to such objects should be made while holding the
  118. * object->lock. Insertions or deletions from object_list, gray_list or
  119. * tree_node are already protected by the corresponding locks or mutex (see
  120. * the notes on locking above). These objects are reference-counted
  121. * (use_count) and freed using the RCU mechanism.
  122. */
  123. struct kmemleak_object {
  124. spinlock_t lock;
  125. unsigned long flags; /* object status flags */
  126. struct list_head object_list;
  127. struct list_head gray_list;
  128. struct prio_tree_node tree_node;
  129. struct rcu_head rcu; /* object_list lockless traversal */
  130. /* object usage count; object freed when use_count == 0 */
  131. atomic_t use_count;
  132. unsigned long pointer;
  133. size_t size;
  134. /* minimum number of a pointers found before it is considered leak */
  135. int min_count;
  136. /* the total number of pointers found pointing to this object */
  137. int count;
  138. /* memory ranges to be scanned inside an object (empty for all) */
  139. struct hlist_head area_list;
  140. unsigned long trace[MAX_TRACE];
  141. unsigned int trace_len;
  142. unsigned long jiffies; /* creation timestamp */
  143. pid_t pid; /* pid of the current task */
  144. char comm[TASK_COMM_LEN]; /* executable name */
  145. };
  146. /* flag representing the memory block allocation status */
  147. #define OBJECT_ALLOCATED (1 << 0)
  148. /* flag set after the first reporting of an unreference object */
  149. #define OBJECT_REPORTED (1 << 1)
  150. /* flag set to not scan the object */
  151. #define OBJECT_NO_SCAN (1 << 2)
  152. /* flag set on newly allocated objects */
  153. #define OBJECT_NEW (1 << 3)
  154. /* the list of all allocated objects */
  155. static LIST_HEAD(object_list);
  156. /* the list of gray-colored objects (see color_gray comment below) */
  157. static LIST_HEAD(gray_list);
  158. /* prio search tree for object boundaries */
  159. static struct prio_tree_root object_tree_root;
  160. /* rw_lock protecting the access to object_list and prio_tree_root */
  161. static DEFINE_RWLOCK(kmemleak_lock);
  162. /* allocation caches for kmemleak internal data */
  163. static struct kmem_cache *object_cache;
  164. static struct kmem_cache *scan_area_cache;
  165. /* set if tracing memory operations is enabled */
  166. static atomic_t kmemleak_enabled = ATOMIC_INIT(0);
  167. /* set in the late_initcall if there were no errors */
  168. static atomic_t kmemleak_initialized = ATOMIC_INIT(0);
  169. /* enables or disables early logging of the memory operations */
  170. static atomic_t kmemleak_early_log = ATOMIC_INIT(1);
  171. /* set if a fata kmemleak error has occurred */
  172. static atomic_t kmemleak_error = ATOMIC_INIT(0);
  173. /* minimum and maximum address that may be valid pointers */
  174. static unsigned long min_addr = ULONG_MAX;
  175. static unsigned long max_addr;
  176. static struct task_struct *scan_thread;
  177. /* used to avoid reporting of recently allocated objects */
  178. static unsigned long jiffies_min_age;
  179. static unsigned long jiffies_last_scan;
  180. /* delay between automatic memory scannings */
  181. static signed long jiffies_scan_wait;
  182. /* enables or disables the task stacks scanning */
  183. static int kmemleak_stack_scan = 1;
  184. /* protects the memory scanning, parameters and debug/kmemleak file access */
  185. static DEFINE_MUTEX(scan_mutex);
  186. /*
  187. * Early object allocation/freeing logging. Kmemleak is initialized after the
  188. * kernel allocator. However, both the kernel allocator and kmemleak may
  189. * allocate memory blocks which need to be tracked. Kmemleak defines an
  190. * arbitrary buffer to hold the allocation/freeing information before it is
  191. * fully initialized.
  192. */
  193. /* kmemleak operation type for early logging */
  194. enum {
  195. KMEMLEAK_ALLOC,
  196. KMEMLEAK_FREE,
  197. KMEMLEAK_FREE_PART,
  198. KMEMLEAK_NOT_LEAK,
  199. KMEMLEAK_IGNORE,
  200. KMEMLEAK_SCAN_AREA,
  201. KMEMLEAK_NO_SCAN
  202. };
  203. /*
  204. * Structure holding the information passed to kmemleak callbacks during the
  205. * early logging.
  206. */
  207. struct early_log {
  208. int op_type; /* kmemleak operation type */
  209. const void *ptr; /* allocated/freed memory block */
  210. size_t size; /* memory block size */
  211. int min_count; /* minimum reference count */
  212. unsigned long offset; /* scan area offset */
  213. size_t length; /* scan area length */
  214. unsigned long trace[MAX_TRACE]; /* stack trace */
  215. unsigned int trace_len; /* stack trace length */
  216. };
  217. /* early logging buffer and current position */
  218. static struct early_log
  219. early_log[CONFIG_DEBUG_KMEMLEAK_EARLY_LOG_SIZE] __initdata;
  220. static int crt_early_log __initdata;
  221. static void kmemleak_disable(void);
  222. /*
  223. * Print a warning and dump the stack trace.
  224. */
  225. #define kmemleak_warn(x...) do { \
  226. pr_warning(x); \
  227. dump_stack(); \
  228. } while (0)
  229. /*
  230. * Macro invoked when a serious kmemleak condition occured and cannot be
  231. * recovered from. Kmemleak will be disabled and further allocation/freeing
  232. * tracing no longer available.
  233. */
  234. #define kmemleak_stop(x...) do { \
  235. kmemleak_warn(x); \
  236. kmemleak_disable(); \
  237. } while (0)
  238. /*
  239. * Object colors, encoded with count and min_count:
  240. * - white - orphan object, not enough references to it (count < min_count)
  241. * - gray - not orphan, not marked as false positive (min_count == 0) or
  242. * sufficient references to it (count >= min_count)
  243. * - black - ignore, it doesn't contain references (e.g. text section)
  244. * (min_count == -1). No function defined for this color.
  245. * Newly created objects don't have any color assigned (object->count == -1)
  246. * before the next memory scan when they become white.
  247. */
  248. static int color_white(const struct kmemleak_object *object)
  249. {
  250. return object->count != -1 && object->count < object->min_count;
  251. }
  252. static int color_gray(const struct kmemleak_object *object)
  253. {
  254. return object->min_count != -1 && object->count >= object->min_count;
  255. }
  256. static int color_black(const struct kmemleak_object *object)
  257. {
  258. return object->min_count == -1;
  259. }
  260. /*
  261. * Objects are considered unreferenced only if their color is white, they have
  262. * not be deleted and have a minimum age to avoid false positives caused by
  263. * pointers temporarily stored in CPU registers.
  264. */
  265. static int unreferenced_object(struct kmemleak_object *object)
  266. {
  267. return (object->flags & OBJECT_ALLOCATED) && color_white(object) &&
  268. time_before_eq(object->jiffies + jiffies_min_age,
  269. jiffies_last_scan);
  270. }
  271. /*
  272. * Printing of the unreferenced objects information to the seq file. The
  273. * print_unreferenced function must be called with the object->lock held.
  274. */
  275. static void print_unreferenced(struct seq_file *seq,
  276. struct kmemleak_object *object)
  277. {
  278. int i;
  279. seq_printf(seq, "unreferenced object 0x%08lx (size %zu):\n",
  280. object->pointer, object->size);
  281. seq_printf(seq, " comm \"%s\", pid %d, jiffies %lu\n",
  282. object->comm, object->pid, object->jiffies);
  283. seq_printf(seq, " backtrace:\n");
  284. for (i = 0; i < object->trace_len; i++) {
  285. void *ptr = (void *)object->trace[i];
  286. seq_printf(seq, " [<%p>] %pS\n", ptr, ptr);
  287. }
  288. }
  289. /*
  290. * Print the kmemleak_object information. This function is used mainly for
  291. * debugging special cases when kmemleak operations. It must be called with
  292. * the object->lock held.
  293. */
  294. static void dump_object_info(struct kmemleak_object *object)
  295. {
  296. struct stack_trace trace;
  297. trace.nr_entries = object->trace_len;
  298. trace.entries = object->trace;
  299. pr_notice("Object 0x%08lx (size %zu):\n",
  300. object->tree_node.start, object->size);
  301. pr_notice(" comm \"%s\", pid %d, jiffies %lu\n",
  302. object->comm, object->pid, object->jiffies);
  303. pr_notice(" min_count = %d\n", object->min_count);
  304. pr_notice(" count = %d\n", object->count);
  305. pr_notice(" flags = 0x%lx\n", object->flags);
  306. pr_notice(" backtrace:\n");
  307. print_stack_trace(&trace, 4);
  308. }
  309. /*
  310. * Look-up a memory block metadata (kmemleak_object) in the priority search
  311. * tree based on a pointer value. If alias is 0, only values pointing to the
  312. * beginning of the memory block are allowed. The kmemleak_lock must be held
  313. * when calling this function.
  314. */
  315. static struct kmemleak_object *lookup_object(unsigned long ptr, int alias)
  316. {
  317. struct prio_tree_node *node;
  318. struct prio_tree_iter iter;
  319. struct kmemleak_object *object;
  320. prio_tree_iter_init(&iter, &object_tree_root, ptr, ptr);
  321. node = prio_tree_next(&iter);
  322. if (node) {
  323. object = prio_tree_entry(node, struct kmemleak_object,
  324. tree_node);
  325. if (!alias && object->pointer != ptr) {
  326. kmemleak_warn("Found object by alias");
  327. object = NULL;
  328. }
  329. } else
  330. object = NULL;
  331. return object;
  332. }
  333. /*
  334. * Increment the object use_count. Return 1 if successful or 0 otherwise. Note
  335. * that once an object's use_count reached 0, the RCU freeing was already
  336. * registered and the object should no longer be used. This function must be
  337. * called under the protection of rcu_read_lock().
  338. */
  339. static int get_object(struct kmemleak_object *object)
  340. {
  341. return atomic_inc_not_zero(&object->use_count);
  342. }
  343. /*
  344. * RCU callback to free a kmemleak_object.
  345. */
  346. static void free_object_rcu(struct rcu_head *rcu)
  347. {
  348. struct hlist_node *elem, *tmp;
  349. struct kmemleak_scan_area *area;
  350. struct kmemleak_object *object =
  351. container_of(rcu, struct kmemleak_object, rcu);
  352. /*
  353. * Once use_count is 0 (guaranteed by put_object), there is no other
  354. * code accessing this object, hence no need for locking.
  355. */
  356. hlist_for_each_entry_safe(area, elem, tmp, &object->area_list, node) {
  357. hlist_del(elem);
  358. kmem_cache_free(scan_area_cache, area);
  359. }
  360. kmem_cache_free(object_cache, object);
  361. }
  362. /*
  363. * Decrement the object use_count. Once the count is 0, free the object using
  364. * an RCU callback. Since put_object() may be called via the kmemleak_free() ->
  365. * delete_object() path, the delayed RCU freeing ensures that there is no
  366. * recursive call to the kernel allocator. Lock-less RCU object_list traversal
  367. * is also possible.
  368. */
  369. static void put_object(struct kmemleak_object *object)
  370. {
  371. if (!atomic_dec_and_test(&object->use_count))
  372. return;
  373. /* should only get here after delete_object was called */
  374. WARN_ON(object->flags & OBJECT_ALLOCATED);
  375. call_rcu(&object->rcu, free_object_rcu);
  376. }
  377. /*
  378. * Look up an object in the prio search tree and increase its use_count.
  379. */
  380. static struct kmemleak_object *find_and_get_object(unsigned long ptr, int alias)
  381. {
  382. unsigned long flags;
  383. struct kmemleak_object *object = NULL;
  384. rcu_read_lock();
  385. read_lock_irqsave(&kmemleak_lock, flags);
  386. if (ptr >= min_addr && ptr < max_addr)
  387. object = lookup_object(ptr, alias);
  388. read_unlock_irqrestore(&kmemleak_lock, flags);
  389. /* check whether the object is still available */
  390. if (object && !get_object(object))
  391. object = NULL;
  392. rcu_read_unlock();
  393. return object;
  394. }
  395. /*
  396. * Save stack trace to the given array of MAX_TRACE size.
  397. */
  398. static int __save_stack_trace(unsigned long *trace)
  399. {
  400. struct stack_trace stack_trace;
  401. stack_trace.max_entries = MAX_TRACE;
  402. stack_trace.nr_entries = 0;
  403. stack_trace.entries = trace;
  404. stack_trace.skip = 2;
  405. save_stack_trace(&stack_trace);
  406. return stack_trace.nr_entries;
  407. }
  408. /*
  409. * Create the metadata (struct kmemleak_object) corresponding to an allocated
  410. * memory block and add it to the object_list and object_tree_root.
  411. */
  412. static struct kmemleak_object *create_object(unsigned long ptr, size_t size,
  413. int min_count, gfp_t gfp)
  414. {
  415. unsigned long flags;
  416. struct kmemleak_object *object;
  417. struct prio_tree_node *node;
  418. object = kmem_cache_alloc(object_cache, gfp & GFP_KMEMLEAK_MASK);
  419. if (!object) {
  420. kmemleak_stop("Cannot allocate a kmemleak_object structure\n");
  421. return NULL;
  422. }
  423. INIT_LIST_HEAD(&object->object_list);
  424. INIT_LIST_HEAD(&object->gray_list);
  425. INIT_HLIST_HEAD(&object->area_list);
  426. spin_lock_init(&object->lock);
  427. atomic_set(&object->use_count, 1);
  428. object->flags = OBJECT_ALLOCATED | OBJECT_NEW;
  429. object->pointer = ptr;
  430. object->size = size;
  431. object->min_count = min_count;
  432. object->count = -1; /* no color initially */
  433. object->jiffies = jiffies;
  434. /* task information */
  435. if (in_irq()) {
  436. object->pid = 0;
  437. strncpy(object->comm, "hardirq", sizeof(object->comm));
  438. } else if (in_softirq()) {
  439. object->pid = 0;
  440. strncpy(object->comm, "softirq", sizeof(object->comm));
  441. } else {
  442. object->pid = current->pid;
  443. /*
  444. * There is a small chance of a race with set_task_comm(),
  445. * however using get_task_comm() here may cause locking
  446. * dependency issues with current->alloc_lock. In the worst
  447. * case, the command line is not correct.
  448. */
  449. strncpy(object->comm, current->comm, sizeof(object->comm));
  450. }
  451. /* kernel backtrace */
  452. object->trace_len = __save_stack_trace(object->trace);
  453. INIT_PRIO_TREE_NODE(&object->tree_node);
  454. object->tree_node.start = ptr;
  455. object->tree_node.last = ptr + size - 1;
  456. write_lock_irqsave(&kmemleak_lock, flags);
  457. min_addr = min(min_addr, ptr);
  458. max_addr = max(max_addr, ptr + size);
  459. node = prio_tree_insert(&object_tree_root, &object->tree_node);
  460. /*
  461. * The code calling the kernel does not yet have the pointer to the
  462. * memory block to be able to free it. However, we still hold the
  463. * kmemleak_lock here in case parts of the kernel started freeing
  464. * random memory blocks.
  465. */
  466. if (node != &object->tree_node) {
  467. unsigned long flags;
  468. kmemleak_stop("Cannot insert 0x%lx into the object search tree "
  469. "(already existing)\n", ptr);
  470. object = lookup_object(ptr, 1);
  471. spin_lock_irqsave(&object->lock, flags);
  472. dump_object_info(object);
  473. spin_unlock_irqrestore(&object->lock, flags);
  474. goto out;
  475. }
  476. list_add_tail_rcu(&object->object_list, &object_list);
  477. out:
  478. write_unlock_irqrestore(&kmemleak_lock, flags);
  479. return object;
  480. }
  481. /*
  482. * Remove the metadata (struct kmemleak_object) for a memory block from the
  483. * object_list and object_tree_root and decrement its use_count.
  484. */
  485. static void __delete_object(struct kmemleak_object *object)
  486. {
  487. unsigned long flags;
  488. write_lock_irqsave(&kmemleak_lock, flags);
  489. prio_tree_remove(&object_tree_root, &object->tree_node);
  490. list_del_rcu(&object->object_list);
  491. write_unlock_irqrestore(&kmemleak_lock, flags);
  492. WARN_ON(!(object->flags & OBJECT_ALLOCATED));
  493. WARN_ON(atomic_read(&object->use_count) < 2);
  494. /*
  495. * Locking here also ensures that the corresponding memory block
  496. * cannot be freed when it is being scanned.
  497. */
  498. spin_lock_irqsave(&object->lock, flags);
  499. object->flags &= ~OBJECT_ALLOCATED;
  500. spin_unlock_irqrestore(&object->lock, flags);
  501. put_object(object);
  502. }
  503. /*
  504. * Look up the metadata (struct kmemleak_object) corresponding to ptr and
  505. * delete it.
  506. */
  507. static void delete_object_full(unsigned long ptr)
  508. {
  509. struct kmemleak_object *object;
  510. object = find_and_get_object(ptr, 0);
  511. if (!object) {
  512. #ifdef DEBUG
  513. kmemleak_warn("Freeing unknown object at 0x%08lx\n",
  514. ptr);
  515. #endif
  516. return;
  517. }
  518. __delete_object(object);
  519. put_object(object);
  520. }
  521. /*
  522. * Look up the metadata (struct kmemleak_object) corresponding to ptr and
  523. * delete it. If the memory block is partially freed, the function may create
  524. * additional metadata for the remaining parts of the block.
  525. */
  526. static void delete_object_part(unsigned long ptr, size_t size)
  527. {
  528. struct kmemleak_object *object;
  529. unsigned long start, end;
  530. object = find_and_get_object(ptr, 1);
  531. if (!object) {
  532. #ifdef DEBUG
  533. kmemleak_warn("Partially freeing unknown object at 0x%08lx "
  534. "(size %zu)\n", ptr, size);
  535. #endif
  536. return;
  537. }
  538. __delete_object(object);
  539. /*
  540. * Create one or two objects that may result from the memory block
  541. * split. Note that partial freeing is only done by free_bootmem() and
  542. * this happens before kmemleak_init() is called. The path below is
  543. * only executed during early log recording in kmemleak_init(), so
  544. * GFP_KERNEL is enough.
  545. */
  546. start = object->pointer;
  547. end = object->pointer + object->size;
  548. if (ptr > start)
  549. create_object(start, ptr - start, object->min_count,
  550. GFP_KERNEL);
  551. if (ptr + size < end)
  552. create_object(ptr + size, end - ptr - size, object->min_count,
  553. GFP_KERNEL);
  554. put_object(object);
  555. }
  556. /*
  557. * Make a object permanently as gray-colored so that it can no longer be
  558. * reported as a leak. This is used in general to mark a false positive.
  559. */
  560. static void make_gray_object(unsigned long ptr)
  561. {
  562. unsigned long flags;
  563. struct kmemleak_object *object;
  564. object = find_and_get_object(ptr, 0);
  565. if (!object) {
  566. kmemleak_warn("Graying unknown object at 0x%08lx\n", ptr);
  567. return;
  568. }
  569. spin_lock_irqsave(&object->lock, flags);
  570. object->min_count = 0;
  571. spin_unlock_irqrestore(&object->lock, flags);
  572. put_object(object);
  573. }
  574. /*
  575. * Mark the object as black-colored so that it is ignored from scans and
  576. * reporting.
  577. */
  578. static void make_black_object(unsigned long ptr)
  579. {
  580. unsigned long flags;
  581. struct kmemleak_object *object;
  582. object = find_and_get_object(ptr, 0);
  583. if (!object) {
  584. kmemleak_warn("Blacking unknown object at 0x%08lx\n", ptr);
  585. return;
  586. }
  587. spin_lock_irqsave(&object->lock, flags);
  588. object->min_count = -1;
  589. object->flags |= OBJECT_NO_SCAN;
  590. spin_unlock_irqrestore(&object->lock, flags);
  591. put_object(object);
  592. }
  593. /*
  594. * Add a scanning area to the object. If at least one such area is added,
  595. * kmemleak will only scan these ranges rather than the whole memory block.
  596. */
  597. static void add_scan_area(unsigned long ptr, unsigned long offset,
  598. size_t length, gfp_t gfp)
  599. {
  600. unsigned long flags;
  601. struct kmemleak_object *object;
  602. struct kmemleak_scan_area *area;
  603. object = find_and_get_object(ptr, 0);
  604. if (!object) {
  605. kmemleak_warn("Adding scan area to unknown object at 0x%08lx\n",
  606. ptr);
  607. return;
  608. }
  609. area = kmem_cache_alloc(scan_area_cache, gfp & GFP_KMEMLEAK_MASK);
  610. if (!area) {
  611. kmemleak_warn("Cannot allocate a scan area\n");
  612. goto out;
  613. }
  614. spin_lock_irqsave(&object->lock, flags);
  615. if (offset + length > object->size) {
  616. kmemleak_warn("Scan area larger than object 0x%08lx\n", ptr);
  617. dump_object_info(object);
  618. kmem_cache_free(scan_area_cache, area);
  619. goto out_unlock;
  620. }
  621. INIT_HLIST_NODE(&area->node);
  622. area->offset = offset;
  623. area->length = length;
  624. hlist_add_head(&area->node, &object->area_list);
  625. out_unlock:
  626. spin_unlock_irqrestore(&object->lock, flags);
  627. out:
  628. put_object(object);
  629. }
  630. /*
  631. * Set the OBJECT_NO_SCAN flag for the object corresponding to the give
  632. * pointer. Such object will not be scanned by kmemleak but references to it
  633. * are searched.
  634. */
  635. static void object_no_scan(unsigned long ptr)
  636. {
  637. unsigned long flags;
  638. struct kmemleak_object *object;
  639. object = find_and_get_object(ptr, 0);
  640. if (!object) {
  641. kmemleak_warn("Not scanning unknown object at 0x%08lx\n", ptr);
  642. return;
  643. }
  644. spin_lock_irqsave(&object->lock, flags);
  645. object->flags |= OBJECT_NO_SCAN;
  646. spin_unlock_irqrestore(&object->lock, flags);
  647. put_object(object);
  648. }
  649. /*
  650. * Log an early kmemleak_* call to the early_log buffer. These calls will be
  651. * processed later once kmemleak is fully initialized.
  652. */
  653. static void __init log_early(int op_type, const void *ptr, size_t size,
  654. int min_count, unsigned long offset, size_t length)
  655. {
  656. unsigned long flags;
  657. struct early_log *log;
  658. if (crt_early_log >= ARRAY_SIZE(early_log)) {
  659. pr_warning("Early log buffer exceeded\n");
  660. kmemleak_disable();
  661. return;
  662. }
  663. /*
  664. * There is no need for locking since the kernel is still in UP mode
  665. * at this stage. Disabling the IRQs is enough.
  666. */
  667. local_irq_save(flags);
  668. log = &early_log[crt_early_log];
  669. log->op_type = op_type;
  670. log->ptr = ptr;
  671. log->size = size;
  672. log->min_count = min_count;
  673. log->offset = offset;
  674. log->length = length;
  675. if (op_type == KMEMLEAK_ALLOC)
  676. log->trace_len = __save_stack_trace(log->trace);
  677. crt_early_log++;
  678. local_irq_restore(flags);
  679. }
  680. /*
  681. * Log an early allocated block and populate the stack trace.
  682. */
  683. static void early_alloc(struct early_log *log)
  684. {
  685. struct kmemleak_object *object;
  686. unsigned long flags;
  687. int i;
  688. if (!atomic_read(&kmemleak_enabled) || !log->ptr || IS_ERR(log->ptr))
  689. return;
  690. /*
  691. * RCU locking needed to ensure object is not freed via put_object().
  692. */
  693. rcu_read_lock();
  694. object = create_object((unsigned long)log->ptr, log->size,
  695. log->min_count, GFP_KERNEL);
  696. spin_lock_irqsave(&object->lock, flags);
  697. for (i = 0; i < log->trace_len; i++)
  698. object->trace[i] = log->trace[i];
  699. object->trace_len = log->trace_len;
  700. spin_unlock_irqrestore(&object->lock, flags);
  701. rcu_read_unlock();
  702. }
  703. /*
  704. * Memory allocation function callback. This function is called from the
  705. * kernel allocators when a new block is allocated (kmem_cache_alloc, kmalloc,
  706. * vmalloc etc.).
  707. */
  708. void __ref kmemleak_alloc(const void *ptr, size_t size, int min_count,
  709. gfp_t gfp)
  710. {
  711. pr_debug("%s(0x%p, %zu, %d)\n", __func__, ptr, size, min_count);
  712. if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  713. create_object((unsigned long)ptr, size, min_count, gfp);
  714. else if (atomic_read(&kmemleak_early_log))
  715. log_early(KMEMLEAK_ALLOC, ptr, size, min_count, 0, 0);
  716. }
  717. EXPORT_SYMBOL_GPL(kmemleak_alloc);
  718. /*
  719. * Memory freeing function callback. This function is called from the kernel
  720. * allocators when a block is freed (kmem_cache_free, kfree, vfree etc.).
  721. */
  722. void __ref kmemleak_free(const void *ptr)
  723. {
  724. pr_debug("%s(0x%p)\n", __func__, ptr);
  725. if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  726. delete_object_full((unsigned long)ptr);
  727. else if (atomic_read(&kmemleak_early_log))
  728. log_early(KMEMLEAK_FREE, ptr, 0, 0, 0, 0);
  729. }
  730. EXPORT_SYMBOL_GPL(kmemleak_free);
  731. /*
  732. * Partial memory freeing function callback. This function is usually called
  733. * from bootmem allocator when (part of) a memory block is freed.
  734. */
  735. void __ref kmemleak_free_part(const void *ptr, size_t size)
  736. {
  737. pr_debug("%s(0x%p)\n", __func__, ptr);
  738. if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  739. delete_object_part((unsigned long)ptr, size);
  740. else if (atomic_read(&kmemleak_early_log))
  741. log_early(KMEMLEAK_FREE_PART, ptr, size, 0, 0, 0);
  742. }
  743. EXPORT_SYMBOL_GPL(kmemleak_free_part);
  744. /*
  745. * Mark an already allocated memory block as a false positive. This will cause
  746. * the block to no longer be reported as leak and always be scanned.
  747. */
  748. void __ref kmemleak_not_leak(const void *ptr)
  749. {
  750. pr_debug("%s(0x%p)\n", __func__, ptr);
  751. if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  752. make_gray_object((unsigned long)ptr);
  753. else if (atomic_read(&kmemleak_early_log))
  754. log_early(KMEMLEAK_NOT_LEAK, ptr, 0, 0, 0, 0);
  755. }
  756. EXPORT_SYMBOL(kmemleak_not_leak);
  757. /*
  758. * Ignore a memory block. This is usually done when it is known that the
  759. * corresponding block is not a leak and does not contain any references to
  760. * other allocated memory blocks.
  761. */
  762. void __ref kmemleak_ignore(const void *ptr)
  763. {
  764. pr_debug("%s(0x%p)\n", __func__, ptr);
  765. if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  766. make_black_object((unsigned long)ptr);
  767. else if (atomic_read(&kmemleak_early_log))
  768. log_early(KMEMLEAK_IGNORE, ptr, 0, 0, 0, 0);
  769. }
  770. EXPORT_SYMBOL(kmemleak_ignore);
  771. /*
  772. * Limit the range to be scanned in an allocated memory block.
  773. */
  774. void __ref kmemleak_scan_area(const void *ptr, unsigned long offset,
  775. size_t length, gfp_t gfp)
  776. {
  777. pr_debug("%s(0x%p)\n", __func__, ptr);
  778. if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  779. add_scan_area((unsigned long)ptr, offset, length, gfp);
  780. else if (atomic_read(&kmemleak_early_log))
  781. log_early(KMEMLEAK_SCAN_AREA, ptr, 0, 0, offset, length);
  782. }
  783. EXPORT_SYMBOL(kmemleak_scan_area);
  784. /*
  785. * Inform kmemleak not to scan the given memory block.
  786. */
  787. void __ref kmemleak_no_scan(const void *ptr)
  788. {
  789. pr_debug("%s(0x%p)\n", __func__, ptr);
  790. if (atomic_read(&kmemleak_enabled) && ptr && !IS_ERR(ptr))
  791. object_no_scan((unsigned long)ptr);
  792. else if (atomic_read(&kmemleak_early_log))
  793. log_early(KMEMLEAK_NO_SCAN, ptr, 0, 0, 0, 0);
  794. }
  795. EXPORT_SYMBOL(kmemleak_no_scan);
  796. /*
  797. * Memory scanning is a long process and it needs to be interruptable. This
  798. * function checks whether such interrupt condition occured.
  799. */
  800. static int scan_should_stop(void)
  801. {
  802. if (!atomic_read(&kmemleak_enabled))
  803. return 1;
  804. /*
  805. * This function may be called from either process or kthread context,
  806. * hence the need to check for both stop conditions.
  807. */
  808. if (current->mm)
  809. return signal_pending(current);
  810. else
  811. return kthread_should_stop();
  812. return 0;
  813. }
  814. /*
  815. * Scan a memory block (exclusive range) for valid pointers and add those
  816. * found to the gray list.
  817. */
  818. static void scan_block(void *_start, void *_end,
  819. struct kmemleak_object *scanned, int allow_resched)
  820. {
  821. unsigned long *ptr;
  822. unsigned long *start = PTR_ALIGN(_start, BYTES_PER_POINTER);
  823. unsigned long *end = _end - (BYTES_PER_POINTER - 1);
  824. for (ptr = start; ptr < end; ptr++) {
  825. unsigned long flags;
  826. unsigned long pointer = *ptr;
  827. struct kmemleak_object *object;
  828. if (allow_resched)
  829. cond_resched();
  830. if (scan_should_stop())
  831. break;
  832. object = find_and_get_object(pointer, 1);
  833. if (!object)
  834. continue;
  835. if (object == scanned) {
  836. /* self referenced, ignore */
  837. put_object(object);
  838. continue;
  839. }
  840. /*
  841. * Avoid the lockdep recursive warning on object->lock being
  842. * previously acquired in scan_object(). These locks are
  843. * enclosed by scan_mutex.
  844. */
  845. spin_lock_irqsave_nested(&object->lock, flags,
  846. SINGLE_DEPTH_NESTING);
  847. if (!color_white(object)) {
  848. /* non-orphan, ignored or new */
  849. spin_unlock_irqrestore(&object->lock, flags);
  850. put_object(object);
  851. continue;
  852. }
  853. /*
  854. * Increase the object's reference count (number of pointers
  855. * to the memory block). If this count reaches the required
  856. * minimum, the object's color will become gray and it will be
  857. * added to the gray_list.
  858. */
  859. object->count++;
  860. if (color_gray(object))
  861. list_add_tail(&object->gray_list, &gray_list);
  862. else
  863. put_object(object);
  864. spin_unlock_irqrestore(&object->lock, flags);
  865. }
  866. }
  867. /*
  868. * Scan a memory block corresponding to a kmemleak_object. A condition is
  869. * that object->use_count >= 1.
  870. */
  871. static void scan_object(struct kmemleak_object *object)
  872. {
  873. struct kmemleak_scan_area *area;
  874. struct hlist_node *elem;
  875. unsigned long flags;
  876. /*
  877. * Once the object->lock is aquired, the corresponding memory block
  878. * cannot be freed (the same lock is aquired in delete_object).
  879. */
  880. spin_lock_irqsave(&object->lock, flags);
  881. if (object->flags & OBJECT_NO_SCAN)
  882. goto out;
  883. if (!(object->flags & OBJECT_ALLOCATED))
  884. /* already freed object */
  885. goto out;
  886. if (hlist_empty(&object->area_list)) {
  887. void *start = (void *)object->pointer;
  888. void *end = (void *)(object->pointer + object->size);
  889. while (start < end && (object->flags & OBJECT_ALLOCATED) &&
  890. !(object->flags & OBJECT_NO_SCAN)) {
  891. scan_block(start, min(start + MAX_SCAN_SIZE, end),
  892. object, 0);
  893. start += MAX_SCAN_SIZE;
  894. spin_unlock_irqrestore(&object->lock, flags);
  895. cond_resched();
  896. spin_lock_irqsave(&object->lock, flags);
  897. }
  898. } else
  899. hlist_for_each_entry(area, elem, &object->area_list, node)
  900. scan_block((void *)(object->pointer + area->offset),
  901. (void *)(object->pointer + area->offset
  902. + area->length), object, 0);
  903. out:
  904. spin_unlock_irqrestore(&object->lock, flags);
  905. }
  906. /*
  907. * Scan data sections and all the referenced memory blocks allocated via the
  908. * kernel's standard allocators. This function must be called with the
  909. * scan_mutex held.
  910. */
  911. static void kmemleak_scan(void)
  912. {
  913. unsigned long flags;
  914. struct kmemleak_object *object, *tmp;
  915. struct task_struct *task;
  916. int i;
  917. int new_leaks = 0;
  918. int gray_list_pass = 0;
  919. jiffies_last_scan = jiffies;
  920. /* prepare the kmemleak_object's */
  921. rcu_read_lock();
  922. list_for_each_entry_rcu(object, &object_list, object_list) {
  923. spin_lock_irqsave(&object->lock, flags);
  924. #ifdef DEBUG
  925. /*
  926. * With a few exceptions there should be a maximum of
  927. * 1 reference to any object at this point.
  928. */
  929. if (atomic_read(&object->use_count) > 1) {
  930. pr_debug("object->use_count = %d\n",
  931. atomic_read(&object->use_count));
  932. dump_object_info(object);
  933. }
  934. #endif
  935. /* reset the reference count (whiten the object) */
  936. object->count = 0;
  937. object->flags &= ~OBJECT_NEW;
  938. if (color_gray(object) && get_object(object))
  939. list_add_tail(&object->gray_list, &gray_list);
  940. spin_unlock_irqrestore(&object->lock, flags);
  941. }
  942. rcu_read_unlock();
  943. /* data/bss scanning */
  944. scan_block(_sdata, _edata, NULL, 1);
  945. scan_block(__bss_start, __bss_stop, NULL, 1);
  946. #ifdef CONFIG_SMP
  947. /* per-cpu sections scanning */
  948. for_each_possible_cpu(i)
  949. scan_block(__per_cpu_start + per_cpu_offset(i),
  950. __per_cpu_end + per_cpu_offset(i), NULL, 1);
  951. #endif
  952. /*
  953. * Struct page scanning for each node. The code below is not yet safe
  954. * with MEMORY_HOTPLUG.
  955. */
  956. for_each_online_node(i) {
  957. pg_data_t *pgdat = NODE_DATA(i);
  958. unsigned long start_pfn = pgdat->node_start_pfn;
  959. unsigned long end_pfn = start_pfn + pgdat->node_spanned_pages;
  960. unsigned long pfn;
  961. for (pfn = start_pfn; pfn < end_pfn; pfn++) {
  962. struct page *page;
  963. if (!pfn_valid(pfn))
  964. continue;
  965. page = pfn_to_page(pfn);
  966. /* only scan if page is in use */
  967. if (page_count(page) == 0)
  968. continue;
  969. scan_block(page, page + 1, NULL, 1);
  970. }
  971. }
  972. /*
  973. * Scanning the task stacks may introduce false negatives and it is
  974. * not enabled by default.
  975. */
  976. if (kmemleak_stack_scan) {
  977. read_lock(&tasklist_lock);
  978. for_each_process(task)
  979. scan_block(task_stack_page(task),
  980. task_stack_page(task) + THREAD_SIZE,
  981. NULL, 0);
  982. read_unlock(&tasklist_lock);
  983. }
  984. /*
  985. * Scan the objects already referenced from the sections scanned
  986. * above. More objects will be referenced and, if there are no memory
  987. * leaks, all the objects will be scanned. The list traversal is safe
  988. * for both tail additions and removals from inside the loop. The
  989. * kmemleak objects cannot be freed from outside the loop because their
  990. * use_count was increased.
  991. */
  992. repeat:
  993. object = list_entry(gray_list.next, typeof(*object), gray_list);
  994. while (&object->gray_list != &gray_list) {
  995. cond_resched();
  996. /* may add new objects to the list */
  997. if (!scan_should_stop())
  998. scan_object(object);
  999. tmp = list_entry(object->gray_list.next, typeof(*object),
  1000. gray_list);
  1001. /* remove the object from the list and release it */
  1002. list_del(&object->gray_list);
  1003. put_object(object);
  1004. object = tmp;
  1005. }
  1006. if (scan_should_stop() || ++gray_list_pass >= GRAY_LIST_PASSES)
  1007. goto scan_end;
  1008. /*
  1009. * Check for new objects allocated during this scanning and add them
  1010. * to the gray list.
  1011. */
  1012. rcu_read_lock();
  1013. list_for_each_entry_rcu(object, &object_list, object_list) {
  1014. spin_lock_irqsave(&object->lock, flags);
  1015. if ((object->flags & OBJECT_NEW) && !color_black(object) &&
  1016. get_object(object)) {
  1017. object->flags &= ~OBJECT_NEW;
  1018. list_add_tail(&object->gray_list, &gray_list);
  1019. }
  1020. spin_unlock_irqrestore(&object->lock, flags);
  1021. }
  1022. rcu_read_unlock();
  1023. if (!list_empty(&gray_list))
  1024. goto repeat;
  1025. scan_end:
  1026. WARN_ON(!list_empty(&gray_list));
  1027. /*
  1028. * If scanning was stopped or new objects were being allocated at a
  1029. * higher rate than gray list scanning, do not report any new
  1030. * unreferenced objects.
  1031. */
  1032. if (scan_should_stop() || gray_list_pass >= GRAY_LIST_PASSES)
  1033. return;
  1034. /*
  1035. * Scanning result reporting.
  1036. */
  1037. rcu_read_lock();
  1038. list_for_each_entry_rcu(object, &object_list, object_list) {
  1039. spin_lock_irqsave(&object->lock, flags);
  1040. if (unreferenced_object(object) &&
  1041. !(object->flags & OBJECT_REPORTED)) {
  1042. object->flags |= OBJECT_REPORTED;
  1043. new_leaks++;
  1044. }
  1045. spin_unlock_irqrestore(&object->lock, flags);
  1046. }
  1047. rcu_read_unlock();
  1048. if (new_leaks)
  1049. pr_info("%d new suspected memory leaks (see "
  1050. "/sys/kernel/debug/kmemleak)\n", new_leaks);
  1051. }
  1052. /*
  1053. * Thread function performing automatic memory scanning. Unreferenced objects
  1054. * at the end of a memory scan are reported but only the first time.
  1055. */
  1056. static int kmemleak_scan_thread(void *arg)
  1057. {
  1058. static int first_run = 1;
  1059. pr_info("Automatic memory scanning thread started\n");
  1060. set_user_nice(current, 10);
  1061. /*
  1062. * Wait before the first scan to allow the system to fully initialize.
  1063. */
  1064. if (first_run) {
  1065. first_run = 0;
  1066. ssleep(SECS_FIRST_SCAN);
  1067. }
  1068. while (!kthread_should_stop()) {
  1069. signed long timeout = jiffies_scan_wait;
  1070. mutex_lock(&scan_mutex);
  1071. kmemleak_scan();
  1072. mutex_unlock(&scan_mutex);
  1073. /* wait before the next scan */
  1074. while (timeout && !kthread_should_stop())
  1075. timeout = schedule_timeout_interruptible(timeout);
  1076. }
  1077. pr_info("Automatic memory scanning thread ended\n");
  1078. return 0;
  1079. }
  1080. /*
  1081. * Start the automatic memory scanning thread. This function must be called
  1082. * with the scan_mutex held.
  1083. */
  1084. void start_scan_thread(void)
  1085. {
  1086. if (scan_thread)
  1087. return;
  1088. scan_thread = kthread_run(kmemleak_scan_thread, NULL, "kmemleak");
  1089. if (IS_ERR(scan_thread)) {
  1090. pr_warning("Failed to create the scan thread\n");
  1091. scan_thread = NULL;
  1092. }
  1093. }
  1094. /*
  1095. * Stop the automatic memory scanning thread. This function must be called
  1096. * with the scan_mutex held.
  1097. */
  1098. void stop_scan_thread(void)
  1099. {
  1100. if (scan_thread) {
  1101. kthread_stop(scan_thread);
  1102. scan_thread = NULL;
  1103. }
  1104. }
  1105. /*
  1106. * Iterate over the object_list and return the first valid object at or after
  1107. * the required position with its use_count incremented. The function triggers
  1108. * a memory scanning when the pos argument points to the first position.
  1109. */
  1110. static void *kmemleak_seq_start(struct seq_file *seq, loff_t *pos)
  1111. {
  1112. struct kmemleak_object *object;
  1113. loff_t n = *pos;
  1114. int err;
  1115. err = mutex_lock_interruptible(&scan_mutex);
  1116. if (err < 0)
  1117. return ERR_PTR(err);
  1118. rcu_read_lock();
  1119. list_for_each_entry_rcu(object, &object_list, object_list) {
  1120. if (n-- > 0)
  1121. continue;
  1122. if (get_object(object))
  1123. goto out;
  1124. }
  1125. object = NULL;
  1126. out:
  1127. return object;
  1128. }
  1129. /*
  1130. * Return the next object in the object_list. The function decrements the
  1131. * use_count of the previous object and increases that of the next one.
  1132. */
  1133. static void *kmemleak_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  1134. {
  1135. struct kmemleak_object *prev_obj = v;
  1136. struct kmemleak_object *next_obj = NULL;
  1137. struct list_head *n = &prev_obj->object_list;
  1138. ++(*pos);
  1139. list_for_each_continue_rcu(n, &object_list) {
  1140. next_obj = list_entry(n, struct kmemleak_object, object_list);
  1141. if (get_object(next_obj))
  1142. break;
  1143. }
  1144. put_object(prev_obj);
  1145. return next_obj;
  1146. }
  1147. /*
  1148. * Decrement the use_count of the last object required, if any.
  1149. */
  1150. static void kmemleak_seq_stop(struct seq_file *seq, void *v)
  1151. {
  1152. if (!IS_ERR(v)) {
  1153. /*
  1154. * kmemleak_seq_start may return ERR_PTR if the scan_mutex
  1155. * waiting was interrupted, so only release it if !IS_ERR.
  1156. */
  1157. rcu_read_unlock();
  1158. mutex_unlock(&scan_mutex);
  1159. if (v)
  1160. put_object(v);
  1161. }
  1162. }
  1163. /*
  1164. * Print the information for an unreferenced object to the seq file.
  1165. */
  1166. static int kmemleak_seq_show(struct seq_file *seq, void *v)
  1167. {
  1168. struct kmemleak_object *object = v;
  1169. unsigned long flags;
  1170. spin_lock_irqsave(&object->lock, flags);
  1171. if ((object->flags & OBJECT_REPORTED) && unreferenced_object(object))
  1172. print_unreferenced(seq, object);
  1173. spin_unlock_irqrestore(&object->lock, flags);
  1174. return 0;
  1175. }
  1176. static const struct seq_operations kmemleak_seq_ops = {
  1177. .start = kmemleak_seq_start,
  1178. .next = kmemleak_seq_next,
  1179. .stop = kmemleak_seq_stop,
  1180. .show = kmemleak_seq_show,
  1181. };
  1182. static int kmemleak_open(struct inode *inode, struct file *file)
  1183. {
  1184. if (!atomic_read(&kmemleak_enabled))
  1185. return -EBUSY;
  1186. return seq_open(file, &kmemleak_seq_ops);
  1187. }
  1188. static int kmemleak_release(struct inode *inode, struct file *file)
  1189. {
  1190. return seq_release(inode, file);
  1191. }
  1192. static int dump_str_object_info(const char *str)
  1193. {
  1194. unsigned long flags;
  1195. struct kmemleak_object *object;
  1196. unsigned long addr;
  1197. addr= simple_strtoul(str, NULL, 0);
  1198. object = find_and_get_object(addr, 0);
  1199. if (!object) {
  1200. pr_info("Unknown object at 0x%08lx\n", addr);
  1201. return -EINVAL;
  1202. }
  1203. spin_lock_irqsave(&object->lock, flags);
  1204. dump_object_info(object);
  1205. spin_unlock_irqrestore(&object->lock, flags);
  1206. put_object(object);
  1207. return 0;
  1208. }
  1209. /*
  1210. * File write operation to configure kmemleak at run-time. The following
  1211. * commands can be written to the /sys/kernel/debug/kmemleak file:
  1212. * off - disable kmemleak (irreversible)
  1213. * stack=on - enable the task stacks scanning
  1214. * stack=off - disable the tasks stacks scanning
  1215. * scan=on - start the automatic memory scanning thread
  1216. * scan=off - stop the automatic memory scanning thread
  1217. * scan=... - set the automatic memory scanning period in seconds (0 to
  1218. * disable it)
  1219. * scan - trigger a memory scan
  1220. * dump=... - dump information about the object found at the given address
  1221. */
  1222. static ssize_t kmemleak_write(struct file *file, const char __user *user_buf,
  1223. size_t size, loff_t *ppos)
  1224. {
  1225. char buf[64];
  1226. int buf_size;
  1227. int ret;
  1228. buf_size = min(size, (sizeof(buf) - 1));
  1229. if (strncpy_from_user(buf, user_buf, buf_size) < 0)
  1230. return -EFAULT;
  1231. buf[buf_size] = 0;
  1232. ret = mutex_lock_interruptible(&scan_mutex);
  1233. if (ret < 0)
  1234. return ret;
  1235. if (strncmp(buf, "off", 3) == 0)
  1236. kmemleak_disable();
  1237. else if (strncmp(buf, "stack=on", 8) == 0)
  1238. kmemleak_stack_scan = 1;
  1239. else if (strncmp(buf, "stack=off", 9) == 0)
  1240. kmemleak_stack_scan = 0;
  1241. else if (strncmp(buf, "scan=on", 7) == 0)
  1242. start_scan_thread();
  1243. else if (strncmp(buf, "scan=off", 8) == 0)
  1244. stop_scan_thread();
  1245. else if (strncmp(buf, "scan=", 5) == 0) {
  1246. unsigned long secs;
  1247. ret = strict_strtoul(buf + 5, 0, &secs);
  1248. if (ret < 0)
  1249. goto out;
  1250. stop_scan_thread();
  1251. if (secs) {
  1252. jiffies_scan_wait = msecs_to_jiffies(secs * 1000);
  1253. start_scan_thread();
  1254. }
  1255. } else if (strncmp(buf, "scan", 4) == 0)
  1256. kmemleak_scan();
  1257. else if (strncmp(buf, "dump=", 5) == 0)
  1258. ret = dump_str_object_info(buf + 5);
  1259. else
  1260. ret = -EINVAL;
  1261. out:
  1262. mutex_unlock(&scan_mutex);
  1263. if (ret < 0)
  1264. return ret;
  1265. /* ignore the rest of the buffer, only one command at a time */
  1266. *ppos += size;
  1267. return size;
  1268. }
  1269. static const struct file_operations kmemleak_fops = {
  1270. .owner = THIS_MODULE,
  1271. .open = kmemleak_open,
  1272. .read = seq_read,
  1273. .write = kmemleak_write,
  1274. .llseek = seq_lseek,
  1275. .release = kmemleak_release,
  1276. };
  1277. /*
  1278. * Perform the freeing of the kmemleak internal objects after waiting for any
  1279. * current memory scan to complete.
  1280. */
  1281. static int kmemleak_cleanup_thread(void *arg)
  1282. {
  1283. struct kmemleak_object *object;
  1284. mutex_lock(&scan_mutex);
  1285. stop_scan_thread();
  1286. rcu_read_lock();
  1287. list_for_each_entry_rcu(object, &object_list, object_list)
  1288. delete_object_full(object->pointer);
  1289. rcu_read_unlock();
  1290. mutex_unlock(&scan_mutex);
  1291. return 0;
  1292. }
  1293. /*
  1294. * Start the clean-up thread.
  1295. */
  1296. static void kmemleak_cleanup(void)
  1297. {
  1298. struct task_struct *cleanup_thread;
  1299. cleanup_thread = kthread_run(kmemleak_cleanup_thread, NULL,
  1300. "kmemleak-clean");
  1301. if (IS_ERR(cleanup_thread))
  1302. pr_warning("Failed to create the clean-up thread\n");
  1303. }
  1304. /*
  1305. * Disable kmemleak. No memory allocation/freeing will be traced once this
  1306. * function is called. Disabling kmemleak is an irreversible operation.
  1307. */
  1308. static void kmemleak_disable(void)
  1309. {
  1310. /* atomically check whether it was already invoked */
  1311. if (atomic_cmpxchg(&kmemleak_error, 0, 1))
  1312. return;
  1313. /* stop any memory operation tracing */
  1314. atomic_set(&kmemleak_early_log, 0);
  1315. atomic_set(&kmemleak_enabled, 0);
  1316. /* check whether it is too early for a kernel thread */
  1317. if (atomic_read(&kmemleak_initialized))
  1318. kmemleak_cleanup();
  1319. pr_info("Kernel memory leak detector disabled\n");
  1320. }
  1321. /*
  1322. * Allow boot-time kmemleak disabling (enabled by default).
  1323. */
  1324. static int kmemleak_boot_config(char *str)
  1325. {
  1326. if (!str)
  1327. return -EINVAL;
  1328. if (strcmp(str, "off") == 0)
  1329. kmemleak_disable();
  1330. else if (strcmp(str, "on") != 0)
  1331. return -EINVAL;
  1332. return 0;
  1333. }
  1334. early_param("kmemleak", kmemleak_boot_config);
  1335. /*
  1336. * Kmemleak initialization.
  1337. */
  1338. void __init kmemleak_init(void)
  1339. {
  1340. int i;
  1341. unsigned long flags;
  1342. jiffies_min_age = msecs_to_jiffies(MSECS_MIN_AGE);
  1343. jiffies_scan_wait = msecs_to_jiffies(SECS_SCAN_WAIT * 1000);
  1344. object_cache = KMEM_CACHE(kmemleak_object, SLAB_NOLEAKTRACE);
  1345. scan_area_cache = KMEM_CACHE(kmemleak_scan_area, SLAB_NOLEAKTRACE);
  1346. INIT_PRIO_TREE_ROOT(&object_tree_root);
  1347. /* the kernel is still in UP mode, so disabling the IRQs is enough */
  1348. local_irq_save(flags);
  1349. if (!atomic_read(&kmemleak_error)) {
  1350. atomic_set(&kmemleak_enabled, 1);
  1351. atomic_set(&kmemleak_early_log, 0);
  1352. }
  1353. local_irq_restore(flags);
  1354. /*
  1355. * This is the point where tracking allocations is safe. Automatic
  1356. * scanning is started during the late initcall. Add the early logged
  1357. * callbacks to the kmemleak infrastructure.
  1358. */
  1359. for (i = 0; i < crt_early_log; i++) {
  1360. struct early_log *log = &early_log[i];
  1361. switch (log->op_type) {
  1362. case KMEMLEAK_ALLOC:
  1363. early_alloc(log);
  1364. break;
  1365. case KMEMLEAK_FREE:
  1366. kmemleak_free(log->ptr);
  1367. break;
  1368. case KMEMLEAK_FREE_PART:
  1369. kmemleak_free_part(log->ptr, log->size);
  1370. break;
  1371. case KMEMLEAK_NOT_LEAK:
  1372. kmemleak_not_leak(log->ptr);
  1373. break;
  1374. case KMEMLEAK_IGNORE:
  1375. kmemleak_ignore(log->ptr);
  1376. break;
  1377. case KMEMLEAK_SCAN_AREA:
  1378. kmemleak_scan_area(log->ptr, log->offset, log->length,
  1379. GFP_KERNEL);
  1380. break;
  1381. case KMEMLEAK_NO_SCAN:
  1382. kmemleak_no_scan(log->ptr);
  1383. break;
  1384. default:
  1385. WARN_ON(1);
  1386. }
  1387. }
  1388. }
  1389. /*
  1390. * Late initialization function.
  1391. */
  1392. static int __init kmemleak_late_init(void)
  1393. {
  1394. struct dentry *dentry;
  1395. atomic_set(&kmemleak_initialized, 1);
  1396. if (atomic_read(&kmemleak_error)) {
  1397. /*
  1398. * Some error occured and kmemleak was disabled. There is a
  1399. * small chance that kmemleak_disable() was called immediately
  1400. * after setting kmemleak_initialized and we may end up with
  1401. * two clean-up threads but serialized by scan_mutex.
  1402. */
  1403. kmemleak_cleanup();
  1404. return -ENOMEM;
  1405. }
  1406. dentry = debugfs_create_file("kmemleak", S_IRUGO, NULL, NULL,
  1407. &kmemleak_fops);
  1408. if (!dentry)
  1409. pr_warning("Failed to create the debugfs kmemleak file\n");
  1410. mutex_lock(&scan_mutex);
  1411. start_scan_thread();
  1412. mutex_unlock(&scan_mutex);
  1413. pr_info("Kernel memory leak detector initialized\n");
  1414. return 0;
  1415. }
  1416. late_initcall(kmemleak_late_init);