kmemleak.c 40 KB

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