kmemleak.c 50 KB

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