kmemleak.c 47 KB

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