kmemleak.c 43 KB

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