kmemleak.c 47 KB

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