kmemleak.c 41 KB

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