kmemleak.c 46 KB

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