kmemleak.c 42 KB

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