kmemleak.c 41 KB

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