kmemleak.c 42 KB

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