kmemleak.c 48 KB

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