kmemleak.c 41 KB

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