kmemleak.c 55 KB

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