kmemleak.c 44 KB

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