kmemleak.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * mm/kmemleak.c
  4. *
  5. * Copyright (C) 2008 ARM Limited
  6. * Written by Catalin Marinas <catalin.marinas@arm.com>
  7. *
  8. * For more information on the algorithm and kmemleak usage, please see
  9. * Documentation/dev-tools/kmemleak.rst.
  10. *
  11. * Notes on locking
  12. * ----------------
  13. *
  14. * The following locks and mutexes are used by kmemleak:
  15. *
  16. * - kmemleak_lock (raw_spinlock_t): protects the object_list as well as
  17. * del_state modifications and accesses to the object trees
  18. * (object_tree_root, object_phys_tree_root, object_percpu_tree_root). The
  19. * object_list is the main list holding the metadata (struct
  20. * kmemleak_object) for the allocated memory blocks. The object trees are
  21. * red black trees used to look-up metadata based on a pointer to the
  22. * corresponding memory block. The kmemleak_object structures are added to
  23. * the object_list and the object tree root in the create_object() function
  24. * called from the kmemleak_alloc{,_phys,_percpu}() callback and removed in
  25. * delete_object() called from the kmemleak_free{,_phys,_percpu}() callback
  26. * - kmemleak_object.lock (raw_spinlock_t): protects a kmemleak_object.
  27. * Accesses to the metadata (e.g. count) are protected by this lock. Note
  28. * that some members of this structure may be protected by other means
  29. * (atomic or kmemleak_lock). This lock is also held when scanning the
  30. * corresponding memory block to avoid the kernel freeing it via the
  31. * kmemleak_free() callback. This is less heavyweight than holding a global
  32. * lock like kmemleak_lock during scanning.
  33. * - scan_mutex (mutex): ensures that only one thread may scan the memory for
  34. * unreferenced objects at a time. The gray_list contains the objects which
  35. * are already referenced or marked as false positives and need to be
  36. * scanned. This list is only modified during a scanning episode when the
  37. * scan_mutex is held. At the end of a scan, the gray_list is always empty.
  38. * Note that the kmemleak_object.use_count is incremented when an object is
  39. * added to the gray_list and therefore cannot be freed. This mutex also
  40. * prevents multiple users of the "kmemleak" debugfs file together with
  41. * modifications to the memory scanning parameters including the scan_thread
  42. * pointer
  43. *
  44. * Locks and mutexes are acquired/nested in the following order:
  45. *
  46. * scan_mutex [-> object->lock] -> kmemleak_lock -> other_object->lock (SINGLE_DEPTH_NESTING)
  47. *
  48. * No kmemleak_lock and object->lock nesting is allowed outside scan_mutex
  49. * regions.
  50. *
  51. * The kmemleak_object structures have a use_count incremented or decremented
  52. * using the get_object()/put_object() functions. When the use_count becomes
  53. * 0, this count can no longer be incremented and put_object() schedules the
  54. * kmemleak_object freeing via an RCU callback. All calls to the get_object()
  55. * function must be protected by rcu_read_lock() to avoid accessing a freed
  56. * structure.
  57. */
  58. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  59. #include <linux/init.h>
  60. #include <linux/kernel.h>
  61. #include <linux/list.h>
  62. #include <linux/sched/signal.h>
  63. #include <linux/sched/task.h>
  64. #include <linux/sched/task_stack.h>
  65. #include <linux/jiffies.h>
  66. #include <linux/delay.h>
  67. #include <linux/export.h>
  68. #include <linux/kthread.h>
  69. #include <linux/rbtree.h>
  70. #include <linux/fs.h>
  71. #include <linux/debugfs.h>
  72. #include <linux/seq_file.h>
  73. #include <linux/cpumask.h>
  74. #include <linux/spinlock.h>
  75. #include <linux/module.h>
  76. #include <linux/mutex.h>
  77. #include <linux/rcupdate.h>
  78. #include <linux/stacktrace.h>
  79. #include <linux/stackdepot.h>
  80. #include <linux/cache.h>
  81. #include <linux/percpu.h>
  82. #include <linux/memblock.h>
  83. #include <linux/pfn.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 <linux/atomic.h>
  97. #include <linux/kasan.h>
  98. #include <linux/kfence.h>
  99. #include <linux/kmemleak.h>
  100. #include <linux/memory_hotplug.h>
  101. /*
  102. * Kmemleak configuration and common defines.
  103. */
  104. #define MAX_TRACE 16 /* stack trace length */
  105. #define MSECS_MIN_AGE 5000 /* minimum object age for reporting */
  106. #define SECS_FIRST_SCAN 60 /* delay before the first scan */
  107. #define SECS_SCAN_WAIT 600 /* subsequent auto scanning delay */
  108. #define MAX_SCAN_SIZE 4096 /* maximum size of a scanned block */
  109. #define BYTES_PER_POINTER sizeof(void *)
  110. /* scanning area inside a memory block */
  111. struct kmemleak_scan_area {
  112. struct hlist_node node;
  113. unsigned long start;
  114. size_t size;
  115. };
  116. #define KMEMLEAK_GREY 0
  117. #define KMEMLEAK_BLACK -1
  118. /*
  119. * Structure holding the metadata for each allocated memory block.
  120. * Modifications to such objects should be made while holding the
  121. * object->lock. Insertions or deletions from object_list, gray_list or
  122. * rb_node are already protected by the corresponding locks or mutex (see
  123. * the notes on locking above). These objects are reference-counted
  124. * (use_count) and freed using the RCU mechanism.
  125. */
  126. struct kmemleak_object {
  127. raw_spinlock_t lock;
  128. unsigned int flags; /* object status flags */
  129. struct list_head object_list;
  130. struct list_head gray_list;
  131. struct rb_node rb_node;
  132. struct rcu_head rcu; /* object_list lockless traversal */
  133. /* object usage count; object freed when use_count == 0 */
  134. atomic_t use_count;
  135. unsigned int del_state; /* deletion state */
  136. unsigned long pointer;
  137. size_t size;
  138. /* pass surplus references to this pointer */
  139. unsigned long excess_ref;
  140. /* minimum number of a pointers found before it is considered leak */
  141. int min_count;
  142. /* the total number of pointers found pointing to this object */
  143. int count;
  144. /* checksum for detecting modified objects */
  145. u32 checksum;
  146. depot_stack_handle_t trace_handle;
  147. /* memory ranges to be scanned inside an object (empty for all) */
  148. struct hlist_head area_list;
  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. /* flag set to fully scan the object when scan_area allocation failed */
  160. #define OBJECT_FULL_SCAN (1 << 3)
  161. /* flag set for object allocated with physical address */
  162. #define OBJECT_PHYS (1 << 4)
  163. /* flag set for per-CPU pointers */
  164. #define OBJECT_PERCPU (1 << 5)
  165. /* set when __remove_object() called */
  166. #define DELSTATE_REMOVED (1 << 0)
  167. /* set to temporarily prevent deletion from object_list */
  168. #define DELSTATE_NO_DELETE (1 << 1)
  169. #define HEX_PREFIX " "
  170. /* number of bytes to print per line; must be 16 or 32 */
  171. #define HEX_ROW_SIZE 16
  172. /* number of bytes to print at a time (1, 2, 4, 8) */
  173. #define HEX_GROUP_SIZE 1
  174. /* include ASCII after the hex output */
  175. #define HEX_ASCII 1
  176. /* max number of lines to be printed */
  177. #define HEX_MAX_LINES 2
  178. /* the list of all allocated objects */
  179. static LIST_HEAD(object_list);
  180. /* the list of gray-colored objects (see color_gray comment below) */
  181. static LIST_HEAD(gray_list);
  182. /* memory pool allocation */
  183. static struct kmemleak_object mem_pool[CONFIG_DEBUG_KMEMLEAK_MEM_POOL_SIZE];
  184. static int mem_pool_free_count = ARRAY_SIZE(mem_pool);
  185. static LIST_HEAD(mem_pool_free_list);
  186. /* search tree for object boundaries */
  187. static struct rb_root object_tree_root = RB_ROOT;
  188. /* search tree for object (with OBJECT_PHYS flag) boundaries */
  189. static struct rb_root object_phys_tree_root = RB_ROOT;
  190. /* search tree for object (with OBJECT_PERCPU flag) boundaries */
  191. static struct rb_root object_percpu_tree_root = RB_ROOT;
  192. /* protecting the access to object_list, object_tree_root (or object_phys_tree_root) */
  193. static DEFINE_RAW_SPINLOCK(kmemleak_lock);
  194. /* allocation caches for kmemleak internal data */
  195. static struct kmem_cache *object_cache;
  196. static struct kmem_cache *scan_area_cache;
  197. /* set if tracing memory operations is enabled */
  198. static int kmemleak_enabled = 1;
  199. /* same as above but only for the kmemleak_free() callback */
  200. static int kmemleak_free_enabled = 1;
  201. /* set in the late_initcall if there were no errors */
  202. static int kmemleak_late_initialized;
  203. /* set if a kmemleak warning was issued */
  204. static int kmemleak_warning;
  205. /* set if a fatal kmemleak error has occurred */
  206. static int kmemleak_error;
  207. /* minimum and maximum address that may be valid pointers */
  208. static unsigned long min_addr = ULONG_MAX;
  209. static unsigned long max_addr;
  210. /* minimum and maximum address that may be valid per-CPU pointers */
  211. static unsigned long min_percpu_addr = ULONG_MAX;
  212. static unsigned long max_percpu_addr;
  213. static struct task_struct *scan_thread;
  214. /* used to avoid reporting of recently allocated objects */
  215. static unsigned long jiffies_min_age;
  216. static unsigned long jiffies_last_scan;
  217. /* delay between automatic memory scannings */
  218. static unsigned long jiffies_scan_wait;
  219. /* enables or disables the task stacks scanning */
  220. static int kmemleak_stack_scan = 1;
  221. /* protects the memory scanning, parameters and debug/kmemleak file access */
  222. static DEFINE_MUTEX(scan_mutex);
  223. /* setting kmemleak=on, will set this var, skipping the disable */
  224. static int kmemleak_skip_disable;
  225. /* If there are leaks that can be reported */
  226. static bool kmemleak_found_leaks;
  227. static bool kmemleak_verbose;
  228. module_param_named(verbose, kmemleak_verbose, bool, 0600);
  229. static void kmemleak_disable(void);
  230. /*
  231. * Print a warning and dump the stack trace.
  232. */
  233. #define kmemleak_warn(x...) do { \
  234. pr_warn(x); \
  235. dump_stack(); \
  236. kmemleak_warning = 1; \
  237. } while (0)
  238. /*
  239. * Macro invoked when a serious kmemleak condition occurred and cannot be
  240. * recovered from. Kmemleak will be disabled and further allocation/freeing
  241. * tracing no longer available.
  242. */
  243. #define kmemleak_stop(x...) do { \
  244. kmemleak_warn(x); \
  245. kmemleak_disable(); \
  246. } while (0)
  247. #define warn_or_seq_printf(seq, fmt, ...) do { \
  248. if (seq) \
  249. seq_printf(seq, fmt, ##__VA_ARGS__); \
  250. else \
  251. pr_warn(fmt, ##__VA_ARGS__); \
  252. } while (0)
  253. static void warn_or_seq_hex_dump(struct seq_file *seq, int prefix_type,
  254. int rowsize, int groupsize, const void *buf,
  255. size_t len, bool ascii)
  256. {
  257. if (seq)
  258. seq_hex_dump(seq, HEX_PREFIX, prefix_type, rowsize, groupsize,
  259. buf, len, ascii);
  260. else
  261. print_hex_dump(KERN_WARNING, pr_fmt(HEX_PREFIX), prefix_type,
  262. rowsize, groupsize, buf, len, ascii);
  263. }
  264. /*
  265. * Printing of the objects hex dump to the seq file. The number of lines to be
  266. * printed is limited to HEX_MAX_LINES to prevent seq file spamming. The
  267. * actual number of printed bytes depends on HEX_ROW_SIZE. It must be called
  268. * with the object->lock held.
  269. */
  270. static void hex_dump_object(struct seq_file *seq,
  271. struct kmemleak_object *object)
  272. {
  273. const u8 *ptr = (const u8 *)object->pointer;
  274. size_t len;
  275. if (WARN_ON_ONCE(object->flags & OBJECT_PHYS))
  276. return;
  277. if (object->flags & OBJECT_PERCPU)
  278. ptr = (const u8 *)this_cpu_ptr((void __percpu *)object->pointer);
  279. /* limit the number of lines to HEX_MAX_LINES */
  280. len = min_t(size_t, object->size, HEX_MAX_LINES * HEX_ROW_SIZE);
  281. if (object->flags & OBJECT_PERCPU)
  282. warn_or_seq_printf(seq, " hex dump (first %zu bytes on cpu %d):\n",
  283. len, raw_smp_processor_id());
  284. else
  285. warn_or_seq_printf(seq, " hex dump (first %zu bytes):\n", len);
  286. kasan_disable_current();
  287. warn_or_seq_hex_dump(seq, DUMP_PREFIX_NONE, HEX_ROW_SIZE,
  288. HEX_GROUP_SIZE, kasan_reset_tag((void *)ptr), len, HEX_ASCII);
  289. kasan_enable_current();
  290. }
  291. /*
  292. * Object colors, encoded with count and min_count:
  293. * - white - orphan object, not enough references to it (count < min_count)
  294. * - gray - not orphan, not marked as false positive (min_count == 0) or
  295. * sufficient references to it (count >= min_count)
  296. * - black - ignore, it doesn't contain references (e.g. text section)
  297. * (min_count == -1). No function defined for this color.
  298. * Newly created objects don't have any color assigned (object->count == -1)
  299. * before the next memory scan when they become white.
  300. */
  301. static bool color_white(const struct kmemleak_object *object)
  302. {
  303. return object->count != KMEMLEAK_BLACK &&
  304. object->count < object->min_count;
  305. }
  306. static bool color_gray(const struct kmemleak_object *object)
  307. {
  308. return object->min_count != KMEMLEAK_BLACK &&
  309. object->count >= object->min_count;
  310. }
  311. /*
  312. * Objects are considered unreferenced only if their color is white, they have
  313. * not be deleted and have a minimum age to avoid false positives caused by
  314. * pointers temporarily stored in CPU registers.
  315. */
  316. static bool unreferenced_object(struct kmemleak_object *object)
  317. {
  318. return (color_white(object) && object->flags & OBJECT_ALLOCATED) &&
  319. time_before_eq(object->jiffies + jiffies_min_age,
  320. jiffies_last_scan);
  321. }
  322. /*
  323. * Printing of the unreferenced objects information to the seq file. The
  324. * print_unreferenced function must be called with the object->lock held.
  325. */
  326. static void print_unreferenced(struct seq_file *seq,
  327. struct kmemleak_object *object)
  328. {
  329. int i;
  330. unsigned long *entries;
  331. unsigned int nr_entries;
  332. nr_entries = stack_depot_fetch(object->trace_handle, &entries);
  333. warn_or_seq_printf(seq, "unreferenced object 0x%08lx (size %zu):\n",
  334. object->pointer, object->size);
  335. warn_or_seq_printf(seq, " comm \"%s\", pid %d, jiffies %lu\n",
  336. object->comm, object->pid, object->jiffies);
  337. hex_dump_object(seq, object);
  338. warn_or_seq_printf(seq, " backtrace (crc %x):\n", object->checksum);
  339. for (i = 0; i < nr_entries; i++) {
  340. void *ptr = (void *)entries[i];
  341. warn_or_seq_printf(seq, " %pS\n", ptr);
  342. }
  343. }
  344. /*
  345. * Print the kmemleak_object information. This function is used mainly for
  346. * debugging special cases when kmemleak operations. It must be called with
  347. * the object->lock held.
  348. */
  349. static void dump_object_info(struct kmemleak_object *object)
  350. {
  351. pr_notice("Object 0x%08lx (size %zu):\n",
  352. object->pointer, object->size);
  353. pr_notice(" comm \"%s\", pid %d, jiffies %lu\n",
  354. object->comm, object->pid, object->jiffies);
  355. pr_notice(" min_count = %d\n", object->min_count);
  356. pr_notice(" count = %d\n", object->count);
  357. pr_notice(" flags = 0x%x\n", object->flags);
  358. pr_notice(" checksum = %u\n", object->checksum);
  359. pr_notice(" backtrace:\n");
  360. if (object->trace_handle)
  361. stack_depot_print(object->trace_handle);
  362. }
  363. static struct rb_root *object_tree(unsigned long objflags)
  364. {
  365. if (objflags & OBJECT_PHYS)
  366. return &object_phys_tree_root;
  367. if (objflags & OBJECT_PERCPU)
  368. return &object_percpu_tree_root;
  369. return &object_tree_root;
  370. }
  371. /*
  372. * Look-up a memory block metadata (kmemleak_object) in the object search
  373. * tree based on a pointer value. If alias is 0, only values pointing to the
  374. * beginning of the memory block are allowed. The kmemleak_lock must be held
  375. * when calling this function.
  376. */
  377. static struct kmemleak_object *__lookup_object(unsigned long ptr, int alias,
  378. unsigned int objflags)
  379. {
  380. struct rb_node *rb = object_tree(objflags)->rb_node;
  381. unsigned long untagged_ptr = (unsigned long)kasan_reset_tag((void *)ptr);
  382. while (rb) {
  383. struct kmemleak_object *object;
  384. unsigned long untagged_objp;
  385. object = rb_entry(rb, struct kmemleak_object, rb_node);
  386. untagged_objp = (unsigned long)kasan_reset_tag((void *)object->pointer);
  387. if (untagged_ptr < untagged_objp)
  388. rb = object->rb_node.rb_left;
  389. else if (untagged_objp + object->size <= untagged_ptr)
  390. rb = object->rb_node.rb_right;
  391. else if (untagged_objp == untagged_ptr || alias)
  392. return object;
  393. else {
  394. kmemleak_warn("Found object by alias at 0x%08lx\n",
  395. ptr);
  396. dump_object_info(object);
  397. break;
  398. }
  399. }
  400. return NULL;
  401. }
  402. /* Look-up a kmemleak object which allocated with virtual address. */
  403. static struct kmemleak_object *lookup_object(unsigned long ptr, int alias)
  404. {
  405. return __lookup_object(ptr, alias, 0);
  406. }
  407. /*
  408. * Increment the object use_count. Return 1 if successful or 0 otherwise. Note
  409. * that once an object's use_count reached 0, the RCU freeing was already
  410. * registered and the object should no longer be used. This function must be
  411. * called under the protection of rcu_read_lock().
  412. */
  413. static int get_object(struct kmemleak_object *object)
  414. {
  415. return atomic_inc_not_zero(&object->use_count);
  416. }
  417. /*
  418. * Memory pool allocation and freeing. kmemleak_lock must not be held.
  419. */
  420. static struct kmemleak_object *mem_pool_alloc(gfp_t gfp)
  421. {
  422. unsigned long flags;
  423. struct kmemleak_object *object;
  424. /* try the slab allocator first */
  425. if (object_cache) {
  426. object = kmem_cache_alloc_noprof(object_cache,
  427. gfp_nested_mask(gfp));
  428. if (object)
  429. return object;
  430. }
  431. /* slab allocation failed, try the memory pool */
  432. raw_spin_lock_irqsave(&kmemleak_lock, flags);
  433. object = list_first_entry_or_null(&mem_pool_free_list,
  434. typeof(*object), object_list);
  435. if (object)
  436. list_del(&object->object_list);
  437. else if (mem_pool_free_count)
  438. object = &mem_pool[--mem_pool_free_count];
  439. else
  440. pr_warn_once("Memory pool empty, consider increasing CONFIG_DEBUG_KMEMLEAK_MEM_POOL_SIZE\n");
  441. raw_spin_unlock_irqrestore(&kmemleak_lock, flags);
  442. return object;
  443. }
  444. /*
  445. * Return the object to either the slab allocator or the memory pool.
  446. */
  447. static void mem_pool_free(struct kmemleak_object *object)
  448. {
  449. unsigned long flags;
  450. if (object < mem_pool || object >= mem_pool + ARRAY_SIZE(mem_pool)) {
  451. kmem_cache_free(object_cache, object);
  452. return;
  453. }
  454. /* add the object to the memory pool free list */
  455. raw_spin_lock_irqsave(&kmemleak_lock, flags);
  456. list_add(&object->object_list, &mem_pool_free_list);
  457. raw_spin_unlock_irqrestore(&kmemleak_lock, flags);
  458. }
  459. /*
  460. * RCU callback to free a kmemleak_object.
  461. */
  462. static void free_object_rcu(struct rcu_head *rcu)
  463. {
  464. struct hlist_node *tmp;
  465. struct kmemleak_scan_area *area;
  466. struct kmemleak_object *object =
  467. container_of(rcu, struct kmemleak_object, rcu);
  468. /*
  469. * Once use_count is 0 (guaranteed by put_object), there is no other
  470. * code accessing this object, hence no need for locking.
  471. */
  472. hlist_for_each_entry_safe(area, tmp, &object->area_list, node) {
  473. hlist_del(&area->node);
  474. kmem_cache_free(scan_area_cache, area);
  475. }
  476. mem_pool_free(object);
  477. }
  478. /*
  479. * Decrement the object use_count. Once the count is 0, free the object using
  480. * an RCU callback. Since put_object() may be called via the kmemleak_free() ->
  481. * delete_object() path, the delayed RCU freeing ensures that there is no
  482. * recursive call to the kernel allocator. Lock-less RCU object_list traversal
  483. * is also possible.
  484. */
  485. static void put_object(struct kmemleak_object *object)
  486. {
  487. if (!atomic_dec_and_test(&object->use_count))
  488. return;
  489. /* should only get here after delete_object was called */
  490. WARN_ON(object->flags & OBJECT_ALLOCATED);
  491. /*
  492. * It may be too early for the RCU callbacks, however, there is no
  493. * concurrent object_list traversal when !object_cache and all objects
  494. * came from the memory pool. Free the object directly.
  495. */
  496. if (object_cache)
  497. call_rcu(&object->rcu, free_object_rcu);
  498. else
  499. free_object_rcu(&object->rcu);
  500. }
  501. /*
  502. * Look up an object in the object search tree and increase its use_count.
  503. */
  504. static struct kmemleak_object *__find_and_get_object(unsigned long ptr, int alias,
  505. unsigned int objflags)
  506. {
  507. unsigned long flags;
  508. struct kmemleak_object *object;
  509. rcu_read_lock();
  510. raw_spin_lock_irqsave(&kmemleak_lock, flags);
  511. object = __lookup_object(ptr, alias, objflags);
  512. raw_spin_unlock_irqrestore(&kmemleak_lock, flags);
  513. /* check whether the object is still available */
  514. if (object && !get_object(object))
  515. object = NULL;
  516. rcu_read_unlock();
  517. return object;
  518. }
  519. /* Look up and get an object which allocated with virtual address. */
  520. static struct kmemleak_object *find_and_get_object(unsigned long ptr, int alias)
  521. {
  522. return __find_and_get_object(ptr, alias, 0);
  523. }
  524. /*
  525. * Remove an object from its object tree and object_list. Must be called with
  526. * the kmemleak_lock held _if_ kmemleak is still enabled.
  527. */
  528. static void __remove_object(struct kmemleak_object *object)
  529. {
  530. rb_erase(&object->rb_node, object_tree(object->flags));
  531. if (!(object->del_state & DELSTATE_NO_DELETE))
  532. list_del_rcu(&object->object_list);
  533. object->del_state |= DELSTATE_REMOVED;
  534. }
  535. static struct kmemleak_object *__find_and_remove_object(unsigned long ptr,
  536. int alias,
  537. unsigned int objflags)
  538. {
  539. struct kmemleak_object *object;
  540. object = __lookup_object(ptr, alias, objflags);
  541. if (object)
  542. __remove_object(object);
  543. return object;
  544. }
  545. /*
  546. * Look up an object in the object search tree and remove it from both object
  547. * tree root and object_list. The returned object's use_count should be at
  548. * least 1, as initially set by create_object().
  549. */
  550. static struct kmemleak_object *find_and_remove_object(unsigned long ptr, int alias,
  551. unsigned int objflags)
  552. {
  553. unsigned long flags;
  554. struct kmemleak_object *object;
  555. raw_spin_lock_irqsave(&kmemleak_lock, flags);
  556. object = __find_and_remove_object(ptr, alias, objflags);
  557. raw_spin_unlock_irqrestore(&kmemleak_lock, flags);
  558. return object;
  559. }
  560. static noinline depot_stack_handle_t set_track_prepare(void)
  561. {
  562. depot_stack_handle_t trace_handle;
  563. unsigned long entries[MAX_TRACE];
  564. unsigned int nr_entries;
  565. /*
  566. * Use object_cache to determine whether kmemleak_init() has
  567. * been invoked. stack_depot_early_init() is called before
  568. * kmemleak_init() in mm_core_init().
  569. */
  570. if (!object_cache)
  571. return 0;
  572. nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3);
  573. trace_handle = stack_depot_save(entries, nr_entries, GFP_NOWAIT);
  574. return trace_handle;
  575. }
  576. static struct kmemleak_object *__alloc_object(gfp_t gfp)
  577. {
  578. struct kmemleak_object *object;
  579. object = mem_pool_alloc(gfp);
  580. if (!object) {
  581. pr_warn("Cannot allocate a kmemleak_object structure\n");
  582. kmemleak_disable();
  583. return NULL;
  584. }
  585. INIT_LIST_HEAD(&object->object_list);
  586. INIT_LIST_HEAD(&object->gray_list);
  587. INIT_HLIST_HEAD(&object->area_list);
  588. raw_spin_lock_init(&object->lock);
  589. atomic_set(&object->use_count, 1);
  590. object->excess_ref = 0;
  591. object->count = 0; /* white color initially */
  592. object->checksum = 0;
  593. object->del_state = 0;
  594. /* task information */
  595. if (in_hardirq()) {
  596. object->pid = 0;
  597. strscpy(object->comm, "hardirq");
  598. } else if (in_serving_softirq()) {
  599. object->pid = 0;
  600. strscpy(object->comm, "softirq");
  601. } else {
  602. object->pid = current->pid;
  603. /*
  604. * There is a small chance of a race with set_task_comm(),
  605. * however using get_task_comm() here may cause locking
  606. * dependency issues with current->alloc_lock. In the worst
  607. * case, the command line is not correct.
  608. */
  609. strscpy(object->comm, current->comm);
  610. }
  611. /* kernel backtrace */
  612. object->trace_handle = set_track_prepare();
  613. return object;
  614. }
  615. static int __link_object(struct kmemleak_object *object, unsigned long ptr,
  616. size_t size, int min_count, unsigned int objflags)
  617. {
  618. struct kmemleak_object *parent;
  619. struct rb_node **link, *rb_parent;
  620. unsigned long untagged_ptr;
  621. unsigned long untagged_objp;
  622. object->flags = OBJECT_ALLOCATED | objflags;
  623. object->pointer = ptr;
  624. object->size = kfence_ksize((void *)ptr) ?: size;
  625. object->min_count = min_count;
  626. object->jiffies = jiffies;
  627. untagged_ptr = (unsigned long)kasan_reset_tag((void *)ptr);
  628. /*
  629. * Only update min_addr and max_addr with object storing virtual
  630. * address. And update min_percpu_addr max_percpu_addr for per-CPU
  631. * objects.
  632. */
  633. if (objflags & OBJECT_PERCPU) {
  634. min_percpu_addr = min(min_percpu_addr, untagged_ptr);
  635. max_percpu_addr = max(max_percpu_addr, untagged_ptr + size);
  636. } else if (!(objflags & OBJECT_PHYS)) {
  637. min_addr = min(min_addr, untagged_ptr);
  638. max_addr = max(max_addr, untagged_ptr + size);
  639. }
  640. link = &object_tree(objflags)->rb_node;
  641. rb_parent = NULL;
  642. while (*link) {
  643. rb_parent = *link;
  644. parent = rb_entry(rb_parent, struct kmemleak_object, rb_node);
  645. untagged_objp = (unsigned long)kasan_reset_tag((void *)parent->pointer);
  646. if (untagged_ptr + size <= untagged_objp)
  647. link = &parent->rb_node.rb_left;
  648. else if (untagged_objp + parent->size <= untagged_ptr)
  649. link = &parent->rb_node.rb_right;
  650. else {
  651. kmemleak_stop("Cannot insert 0x%lx into the object search tree (overlaps existing)\n",
  652. ptr);
  653. /*
  654. * No need for parent->lock here since "parent" cannot
  655. * be freed while the kmemleak_lock is held.
  656. */
  657. dump_object_info(parent);
  658. return -EEXIST;
  659. }
  660. }
  661. rb_link_node(&object->rb_node, rb_parent, link);
  662. rb_insert_color(&object->rb_node, object_tree(objflags));
  663. list_add_tail_rcu(&object->object_list, &object_list);
  664. return 0;
  665. }
  666. /*
  667. * Create the metadata (struct kmemleak_object) corresponding to an allocated
  668. * memory block and add it to the object_list and object tree.
  669. */
  670. static void __create_object(unsigned long ptr, size_t size,
  671. int min_count, gfp_t gfp, unsigned int objflags)
  672. {
  673. struct kmemleak_object *object;
  674. unsigned long flags;
  675. int ret;
  676. object = __alloc_object(gfp);
  677. if (!object)
  678. return;
  679. raw_spin_lock_irqsave(&kmemleak_lock, flags);
  680. ret = __link_object(object, ptr, size, min_count, objflags);
  681. raw_spin_unlock_irqrestore(&kmemleak_lock, flags);
  682. if (ret)
  683. mem_pool_free(object);
  684. }
  685. /* Create kmemleak object which allocated with virtual address. */
  686. static void create_object(unsigned long ptr, size_t size,
  687. int min_count, gfp_t gfp)
  688. {
  689. __create_object(ptr, size, min_count, gfp, 0);
  690. }
  691. /* Create kmemleak object which allocated with physical address. */
  692. static void create_object_phys(unsigned long ptr, size_t size,
  693. int min_count, gfp_t gfp)
  694. {
  695. __create_object(ptr, size, min_count, gfp, OBJECT_PHYS);
  696. }
  697. /* Create kmemleak object corresponding to a per-CPU allocation. */
  698. static void create_object_percpu(unsigned long ptr, size_t size,
  699. int min_count, gfp_t gfp)
  700. {
  701. __create_object(ptr, size, min_count, gfp, OBJECT_PERCPU);
  702. }
  703. /*
  704. * Mark the object as not allocated and schedule RCU freeing via put_object().
  705. */
  706. static void __delete_object(struct kmemleak_object *object)
  707. {
  708. unsigned long flags;
  709. WARN_ON(!(object->flags & OBJECT_ALLOCATED));
  710. WARN_ON(atomic_read(&object->use_count) < 1);
  711. /*
  712. * Locking here also ensures that the corresponding memory block
  713. * cannot be freed when it is being scanned.
  714. */
  715. raw_spin_lock_irqsave(&object->lock, flags);
  716. object->flags &= ~OBJECT_ALLOCATED;
  717. raw_spin_unlock_irqrestore(&object->lock, flags);
  718. put_object(object);
  719. }
  720. /*
  721. * Look up the metadata (struct kmemleak_object) corresponding to ptr and
  722. * delete it.
  723. */
  724. static void delete_object_full(unsigned long ptr, unsigned int objflags)
  725. {
  726. struct kmemleak_object *object;
  727. object = find_and_remove_object(ptr, 0, objflags);
  728. if (!object) {
  729. #ifdef DEBUG
  730. kmemleak_warn("Freeing unknown object at 0x%08lx\n",
  731. ptr);
  732. #endif
  733. return;
  734. }
  735. __delete_object(object);
  736. }
  737. /*
  738. * Look up the metadata (struct kmemleak_object) corresponding to ptr and
  739. * delete it. If the memory block is partially freed, the function may create
  740. * additional metadata for the remaining parts of the block.
  741. */
  742. static void delete_object_part(unsigned long ptr, size_t size,
  743. unsigned int objflags)
  744. {
  745. struct kmemleak_object *object, *object_l, *object_r;
  746. unsigned long start, end, flags;
  747. object_l = __alloc_object(GFP_KERNEL);
  748. if (!object_l)
  749. return;
  750. object_r = __alloc_object(GFP_KERNEL);
  751. if (!object_r)
  752. goto out;
  753. raw_spin_lock_irqsave(&kmemleak_lock, flags);
  754. object = __find_and_remove_object(ptr, 1, objflags);
  755. if (!object) {
  756. #ifdef DEBUG
  757. kmemleak_warn("Partially freeing unknown object at 0x%08lx (size %zu)\n",
  758. ptr, size);
  759. #endif
  760. goto unlock;
  761. }
  762. /*
  763. * Create one or two objects that may result from the memory block
  764. * split. Note that partial freeing is only done by free_bootmem() and
  765. * this happens before kmemleak_init() is called.
  766. */
  767. start = object->pointer;
  768. end = object->pointer + object->size;
  769. if ((ptr > start) &&
  770. !__link_object(object_l, start, ptr - start,
  771. object->min_count, objflags))
  772. object_l = NULL;
  773. if ((ptr + size < end) &&
  774. !__link_object(object_r, ptr + size, end - ptr - size,
  775. object->min_count, objflags))
  776. object_r = NULL;
  777. unlock:
  778. raw_spin_unlock_irqrestore(&kmemleak_lock, flags);
  779. if (object)
  780. __delete_object(object);
  781. out:
  782. if (object_l)
  783. mem_pool_free(object_l);
  784. if (object_r)
  785. mem_pool_free(object_r);
  786. }
  787. static void __paint_it(struct kmemleak_object *object, int color)
  788. {
  789. object->min_count = color;
  790. if (color == KMEMLEAK_BLACK)
  791. object->flags |= OBJECT_NO_SCAN;
  792. }
  793. static void paint_it(struct kmemleak_object *object, int color)
  794. {
  795. unsigned long flags;
  796. raw_spin_lock_irqsave(&object->lock, flags);
  797. __paint_it(object, color);
  798. raw_spin_unlock_irqrestore(&object->lock, flags);
  799. }
  800. static void paint_ptr(unsigned long ptr, int color, unsigned int objflags)
  801. {
  802. struct kmemleak_object *object;
  803. object = __find_and_get_object(ptr, 0, objflags);
  804. if (!object) {
  805. kmemleak_warn("Trying to color unknown object at 0x%08lx as %s\n",
  806. ptr,
  807. (color == KMEMLEAK_GREY) ? "Grey" :
  808. (color == KMEMLEAK_BLACK) ? "Black" : "Unknown");
  809. return;
  810. }
  811. paint_it(object, color);
  812. put_object(object);
  813. }
  814. /*
  815. * Mark an object permanently as gray-colored so that it can no longer be
  816. * reported as a leak. This is used in general to mark a false positive.
  817. */
  818. static void make_gray_object(unsigned long ptr)
  819. {
  820. paint_ptr(ptr, KMEMLEAK_GREY, 0);
  821. }
  822. /*
  823. * Mark the object as black-colored so that it is ignored from scans and
  824. * reporting.
  825. */
  826. static void make_black_object(unsigned long ptr, unsigned int objflags)
  827. {
  828. paint_ptr(ptr, KMEMLEAK_BLACK, objflags);
  829. }
  830. /*
  831. * Add a scanning area to the object. If at least one such area is added,
  832. * kmemleak will only scan these ranges rather than the whole memory block.
  833. */
  834. static void add_scan_area(unsigned long ptr, size_t size, gfp_t gfp)
  835. {
  836. unsigned long flags;
  837. struct kmemleak_object *object;
  838. struct kmemleak_scan_area *area = NULL;
  839. unsigned long untagged_ptr;
  840. unsigned long untagged_objp;
  841. object = find_and_get_object(ptr, 1);
  842. if (!object) {
  843. kmemleak_warn("Adding scan area to unknown object at 0x%08lx\n",
  844. ptr);
  845. return;
  846. }
  847. untagged_ptr = (unsigned long)kasan_reset_tag((void *)ptr);
  848. untagged_objp = (unsigned long)kasan_reset_tag((void *)object->pointer);
  849. if (scan_area_cache)
  850. area = kmem_cache_alloc_noprof(scan_area_cache,
  851. gfp_nested_mask(gfp));
  852. raw_spin_lock_irqsave(&object->lock, flags);
  853. if (!area) {
  854. pr_warn_once("Cannot allocate a scan area, scanning the full object\n");
  855. /* mark the object for full scan to avoid false positives */
  856. object->flags |= OBJECT_FULL_SCAN;
  857. goto out_unlock;
  858. }
  859. if (size == SIZE_MAX) {
  860. size = untagged_objp + object->size - untagged_ptr;
  861. } else if (untagged_ptr + size > untagged_objp + object->size) {
  862. kmemleak_warn("Scan area larger than object 0x%08lx\n", ptr);
  863. dump_object_info(object);
  864. kmem_cache_free(scan_area_cache, area);
  865. goto out_unlock;
  866. }
  867. INIT_HLIST_NODE(&area->node);
  868. area->start = ptr;
  869. area->size = size;
  870. hlist_add_head(&area->node, &object->area_list);
  871. out_unlock:
  872. raw_spin_unlock_irqrestore(&object->lock, flags);
  873. put_object(object);
  874. }
  875. /*
  876. * Any surplus references (object already gray) to 'ptr' are passed to
  877. * 'excess_ref'. This is used in the vmalloc() case where a pointer to
  878. * vm_struct may be used as an alternative reference to the vmalloc'ed object
  879. * (see free_thread_stack()).
  880. */
  881. static void object_set_excess_ref(unsigned long ptr, unsigned long excess_ref)
  882. {
  883. unsigned long flags;
  884. struct kmemleak_object *object;
  885. object = find_and_get_object(ptr, 0);
  886. if (!object) {
  887. kmemleak_warn("Setting excess_ref on unknown object at 0x%08lx\n",
  888. ptr);
  889. return;
  890. }
  891. raw_spin_lock_irqsave(&object->lock, flags);
  892. object->excess_ref = excess_ref;
  893. raw_spin_unlock_irqrestore(&object->lock, flags);
  894. put_object(object);
  895. }
  896. /*
  897. * Set the OBJECT_NO_SCAN flag for the object corresponding to the give
  898. * pointer. Such object will not be scanned by kmemleak but references to it
  899. * are searched.
  900. */
  901. static void object_no_scan(unsigned long ptr)
  902. {
  903. unsigned long flags;
  904. struct kmemleak_object *object;
  905. object = find_and_get_object(ptr, 0);
  906. if (!object) {
  907. kmemleak_warn("Not scanning unknown object at 0x%08lx\n", ptr);
  908. return;
  909. }
  910. raw_spin_lock_irqsave(&object->lock, flags);
  911. object->flags |= OBJECT_NO_SCAN;
  912. raw_spin_unlock_irqrestore(&object->lock, flags);
  913. put_object(object);
  914. }
  915. /**
  916. * kmemleak_alloc - register a newly allocated object
  917. * @ptr: pointer to beginning of the object
  918. * @size: size of the object
  919. * @min_count: minimum number of references to this object. If during memory
  920. * scanning a number of references less than @min_count is found,
  921. * the object is reported as a memory leak. If @min_count is 0,
  922. * the object is never reported as a leak. If @min_count is -1,
  923. * the object is ignored (not scanned and not reported as a leak)
  924. * @gfp: kmalloc() flags used for kmemleak internal memory allocations
  925. *
  926. * This function is called from the kernel allocators when a new object
  927. * (memory block) is allocated (kmem_cache_alloc, kmalloc etc.).
  928. */
  929. void __ref kmemleak_alloc(const void *ptr, size_t size, int min_count,
  930. gfp_t gfp)
  931. {
  932. pr_debug("%s(0x%px, %zu, %d)\n", __func__, ptr, size, min_count);
  933. if (kmemleak_enabled && ptr && !IS_ERR(ptr))
  934. create_object((unsigned long)ptr, size, min_count, gfp);
  935. }
  936. EXPORT_SYMBOL_GPL(kmemleak_alloc);
  937. /**
  938. * kmemleak_alloc_percpu - register a newly allocated __percpu object
  939. * @ptr: __percpu pointer to beginning of the object
  940. * @size: size of the object
  941. * @gfp: flags used for kmemleak internal memory allocations
  942. *
  943. * This function is called from the kernel percpu allocator when a new object
  944. * (memory block) is allocated (alloc_percpu).
  945. */
  946. void __ref kmemleak_alloc_percpu(const void __percpu *ptr, size_t size,
  947. gfp_t gfp)
  948. {
  949. pr_debug("%s(0x%px, %zu)\n", __func__, ptr, size);
  950. if (kmemleak_enabled && ptr && !IS_ERR_PCPU(ptr))
  951. create_object_percpu((__force unsigned long)ptr, size, 1, gfp);
  952. }
  953. EXPORT_SYMBOL_GPL(kmemleak_alloc_percpu);
  954. /**
  955. * kmemleak_vmalloc - register a newly vmalloc'ed object
  956. * @area: pointer to vm_struct
  957. * @size: size of the object
  958. * @gfp: __vmalloc() flags used for kmemleak internal memory allocations
  959. *
  960. * This function is called from the vmalloc() kernel allocator when a new
  961. * object (memory block) is allocated.
  962. */
  963. void __ref kmemleak_vmalloc(const struct vm_struct *area, size_t size, gfp_t gfp)
  964. {
  965. pr_debug("%s(0x%px, %zu)\n", __func__, area, size);
  966. /*
  967. * A min_count = 2 is needed because vm_struct contains a reference to
  968. * the virtual address of the vmalloc'ed block.
  969. */
  970. if (kmemleak_enabled) {
  971. create_object((unsigned long)area->addr, size, 2, gfp);
  972. object_set_excess_ref((unsigned long)area,
  973. (unsigned long)area->addr);
  974. }
  975. }
  976. EXPORT_SYMBOL_GPL(kmemleak_vmalloc);
  977. /**
  978. * kmemleak_free - unregister a previously registered object
  979. * @ptr: pointer to beginning of the object
  980. *
  981. * This function is called from the kernel allocators when an object (memory
  982. * block) is freed (kmem_cache_free, kfree, vfree etc.).
  983. */
  984. void __ref kmemleak_free(const void *ptr)
  985. {
  986. pr_debug("%s(0x%px)\n", __func__, ptr);
  987. if (kmemleak_free_enabled && ptr && !IS_ERR(ptr))
  988. delete_object_full((unsigned long)ptr, 0);
  989. }
  990. EXPORT_SYMBOL_GPL(kmemleak_free);
  991. /**
  992. * kmemleak_free_part - partially unregister a previously registered object
  993. * @ptr: pointer to the beginning or inside the object. This also
  994. * represents the start of the range to be freed
  995. * @size: size to be unregistered
  996. *
  997. * This function is called when only a part of a memory block is freed
  998. * (usually from the bootmem allocator).
  999. */
  1000. void __ref kmemleak_free_part(const void *ptr, size_t size)
  1001. {
  1002. pr_debug("%s(0x%px)\n", __func__, ptr);
  1003. if (kmemleak_enabled && ptr && !IS_ERR(ptr))
  1004. delete_object_part((unsigned long)ptr, size, 0);
  1005. }
  1006. EXPORT_SYMBOL_GPL(kmemleak_free_part);
  1007. /**
  1008. * kmemleak_free_percpu - unregister a previously registered __percpu object
  1009. * @ptr: __percpu pointer to beginning of the object
  1010. *
  1011. * This function is called from the kernel percpu allocator when an object
  1012. * (memory block) is freed (free_percpu).
  1013. */
  1014. void __ref kmemleak_free_percpu(const void __percpu *ptr)
  1015. {
  1016. pr_debug("%s(0x%px)\n", __func__, ptr);
  1017. if (kmemleak_free_enabled && ptr && !IS_ERR_PCPU(ptr))
  1018. delete_object_full((__force unsigned long)ptr, OBJECT_PERCPU);
  1019. }
  1020. EXPORT_SYMBOL_GPL(kmemleak_free_percpu);
  1021. /**
  1022. * kmemleak_update_trace - update object allocation stack trace
  1023. * @ptr: pointer to beginning of the object
  1024. *
  1025. * Override the object allocation stack trace for cases where the actual
  1026. * allocation place is not always useful.
  1027. */
  1028. void __ref kmemleak_update_trace(const void *ptr)
  1029. {
  1030. struct kmemleak_object *object;
  1031. depot_stack_handle_t trace_handle;
  1032. unsigned long flags;
  1033. pr_debug("%s(0x%px)\n", __func__, ptr);
  1034. if (!kmemleak_enabled || IS_ERR_OR_NULL(ptr))
  1035. return;
  1036. object = find_and_get_object((unsigned long)ptr, 1);
  1037. if (!object) {
  1038. #ifdef DEBUG
  1039. kmemleak_warn("Updating stack trace for unknown object at %p\n",
  1040. ptr);
  1041. #endif
  1042. return;
  1043. }
  1044. trace_handle = set_track_prepare();
  1045. raw_spin_lock_irqsave(&object->lock, flags);
  1046. object->trace_handle = trace_handle;
  1047. raw_spin_unlock_irqrestore(&object->lock, flags);
  1048. put_object(object);
  1049. }
  1050. EXPORT_SYMBOL(kmemleak_update_trace);
  1051. /**
  1052. * kmemleak_not_leak - mark an allocated object as false positive
  1053. * @ptr: pointer to beginning of the object
  1054. *
  1055. * Calling this function on an object will cause the memory block to no longer
  1056. * be reported as leak and always be scanned.
  1057. */
  1058. void __ref kmemleak_not_leak(const void *ptr)
  1059. {
  1060. pr_debug("%s(0x%px)\n", __func__, ptr);
  1061. if (kmemleak_enabled && ptr && !IS_ERR(ptr))
  1062. make_gray_object((unsigned long)ptr);
  1063. }
  1064. EXPORT_SYMBOL(kmemleak_not_leak);
  1065. /**
  1066. * kmemleak_ignore - ignore an allocated object
  1067. * @ptr: pointer to beginning of the object
  1068. *
  1069. * Calling this function on an object will cause the memory block to be
  1070. * ignored (not scanned and not reported as a leak). This is usually done when
  1071. * it is known that the corresponding block is not a leak and does not contain
  1072. * any references to other allocated memory blocks.
  1073. */
  1074. void __ref kmemleak_ignore(const void *ptr)
  1075. {
  1076. pr_debug("%s(0x%px)\n", __func__, ptr);
  1077. if (kmemleak_enabled && ptr && !IS_ERR(ptr))
  1078. make_black_object((unsigned long)ptr, 0);
  1079. }
  1080. EXPORT_SYMBOL(kmemleak_ignore);
  1081. /**
  1082. * kmemleak_scan_area - limit the range to be scanned in an allocated object
  1083. * @ptr: pointer to beginning or inside the object. This also
  1084. * represents the start of the scan area
  1085. * @size: size of the scan area
  1086. * @gfp: kmalloc() flags used for kmemleak internal memory allocations
  1087. *
  1088. * This function is used when it is known that only certain parts of an object
  1089. * contain references to other objects. Kmemleak will only scan these areas
  1090. * reducing the number false negatives.
  1091. */
  1092. void __ref kmemleak_scan_area(const void *ptr, size_t size, gfp_t gfp)
  1093. {
  1094. pr_debug("%s(0x%px)\n", __func__, ptr);
  1095. if (kmemleak_enabled && ptr && size && !IS_ERR(ptr))
  1096. add_scan_area((unsigned long)ptr, size, gfp);
  1097. }
  1098. EXPORT_SYMBOL(kmemleak_scan_area);
  1099. /**
  1100. * kmemleak_no_scan - do not scan an allocated object
  1101. * @ptr: pointer to beginning of the object
  1102. *
  1103. * This function notifies kmemleak not to scan the given memory block. Useful
  1104. * in situations where it is known that the given object does not contain any
  1105. * references to other objects. Kmemleak will not scan such objects reducing
  1106. * the number of false negatives.
  1107. */
  1108. void __ref kmemleak_no_scan(const void *ptr)
  1109. {
  1110. pr_debug("%s(0x%px)\n", __func__, ptr);
  1111. if (kmemleak_enabled && ptr && !IS_ERR(ptr))
  1112. object_no_scan((unsigned long)ptr);
  1113. }
  1114. EXPORT_SYMBOL(kmemleak_no_scan);
  1115. /**
  1116. * kmemleak_alloc_phys - similar to kmemleak_alloc but taking a physical
  1117. * address argument
  1118. * @phys: physical address of the object
  1119. * @size: size of the object
  1120. * @gfp: kmalloc() flags used for kmemleak internal memory allocations
  1121. */
  1122. void __ref kmemleak_alloc_phys(phys_addr_t phys, size_t size, gfp_t gfp)
  1123. {
  1124. pr_debug("%s(0x%px, %zu)\n", __func__, &phys, size);
  1125. if (kmemleak_enabled)
  1126. /*
  1127. * Create object with OBJECT_PHYS flag and
  1128. * assume min_count 0.
  1129. */
  1130. create_object_phys((unsigned long)phys, size, 0, gfp);
  1131. }
  1132. EXPORT_SYMBOL(kmemleak_alloc_phys);
  1133. /**
  1134. * kmemleak_free_part_phys - similar to kmemleak_free_part but taking a
  1135. * physical address argument
  1136. * @phys: physical address if the beginning or inside an object. This
  1137. * also represents the start of the range to be freed
  1138. * @size: size to be unregistered
  1139. */
  1140. void __ref kmemleak_free_part_phys(phys_addr_t phys, size_t size)
  1141. {
  1142. pr_debug("%s(0x%px)\n", __func__, &phys);
  1143. if (kmemleak_enabled)
  1144. delete_object_part((unsigned long)phys, size, OBJECT_PHYS);
  1145. }
  1146. EXPORT_SYMBOL(kmemleak_free_part_phys);
  1147. /**
  1148. * kmemleak_ignore_phys - similar to kmemleak_ignore but taking a physical
  1149. * address argument
  1150. * @phys: physical address of the object
  1151. */
  1152. void __ref kmemleak_ignore_phys(phys_addr_t phys)
  1153. {
  1154. pr_debug("%s(0x%px)\n", __func__, &phys);
  1155. if (kmemleak_enabled)
  1156. make_black_object((unsigned long)phys, OBJECT_PHYS);
  1157. }
  1158. EXPORT_SYMBOL(kmemleak_ignore_phys);
  1159. /*
  1160. * Update an object's checksum and return true if it was modified.
  1161. */
  1162. static bool update_checksum(struct kmemleak_object *object)
  1163. {
  1164. u32 old_csum = object->checksum;
  1165. if (WARN_ON_ONCE(object->flags & OBJECT_PHYS))
  1166. return false;
  1167. kasan_disable_current();
  1168. kcsan_disable_current();
  1169. if (object->flags & OBJECT_PERCPU) {
  1170. unsigned int cpu;
  1171. object->checksum = 0;
  1172. for_each_possible_cpu(cpu) {
  1173. void *ptr = per_cpu_ptr((void __percpu *)object->pointer, cpu);
  1174. object->checksum ^= crc32(0, kasan_reset_tag((void *)ptr), object->size);
  1175. }
  1176. } else {
  1177. object->checksum = crc32(0, kasan_reset_tag((void *)object->pointer), object->size);
  1178. }
  1179. kasan_enable_current();
  1180. kcsan_enable_current();
  1181. return object->checksum != old_csum;
  1182. }
  1183. /*
  1184. * Update an object's references. object->lock must be held by the caller.
  1185. */
  1186. static void update_refs(struct kmemleak_object *object)
  1187. {
  1188. if (!color_white(object)) {
  1189. /* non-orphan, ignored or new */
  1190. return;
  1191. }
  1192. /*
  1193. * Increase the object's reference count (number of pointers to the
  1194. * memory block). If this count reaches the required minimum, the
  1195. * object's color will become gray and it will be added to the
  1196. * gray_list.
  1197. */
  1198. object->count++;
  1199. if (color_gray(object)) {
  1200. /* put_object() called when removing from gray_list */
  1201. WARN_ON(!get_object(object));
  1202. list_add_tail(&object->gray_list, &gray_list);
  1203. }
  1204. }
  1205. static void pointer_update_refs(struct kmemleak_object *scanned,
  1206. unsigned long pointer, unsigned int objflags)
  1207. {
  1208. struct kmemleak_object *object;
  1209. unsigned long untagged_ptr;
  1210. unsigned long excess_ref;
  1211. untagged_ptr = (unsigned long)kasan_reset_tag((void *)pointer);
  1212. if (objflags & OBJECT_PERCPU) {
  1213. if (untagged_ptr < min_percpu_addr || untagged_ptr >= max_percpu_addr)
  1214. return;
  1215. } else {
  1216. if (untagged_ptr < min_addr || untagged_ptr >= max_addr)
  1217. return;
  1218. }
  1219. /*
  1220. * No need for get_object() here since we hold kmemleak_lock.
  1221. * object->use_count cannot be dropped to 0 while the object
  1222. * is still present in object_tree_root and object_list
  1223. * (with updates protected by kmemleak_lock).
  1224. */
  1225. object = __lookup_object(pointer, 1, objflags);
  1226. if (!object)
  1227. return;
  1228. if (object == scanned)
  1229. /* self referenced, ignore */
  1230. return;
  1231. /*
  1232. * Avoid the lockdep recursive warning on object->lock being
  1233. * previously acquired in scan_object(). These locks are
  1234. * enclosed by scan_mutex.
  1235. */
  1236. raw_spin_lock_nested(&object->lock, SINGLE_DEPTH_NESTING);
  1237. /* only pass surplus references (object already gray) */
  1238. if (color_gray(object)) {
  1239. excess_ref = object->excess_ref;
  1240. /* no need for update_refs() if object already gray */
  1241. } else {
  1242. excess_ref = 0;
  1243. update_refs(object);
  1244. }
  1245. raw_spin_unlock(&object->lock);
  1246. if (excess_ref) {
  1247. object = lookup_object(excess_ref, 0);
  1248. if (!object)
  1249. return;
  1250. if (object == scanned)
  1251. /* circular reference, ignore */
  1252. return;
  1253. raw_spin_lock_nested(&object->lock, SINGLE_DEPTH_NESTING);
  1254. update_refs(object);
  1255. raw_spin_unlock(&object->lock);
  1256. }
  1257. }
  1258. /*
  1259. * Memory scanning is a long process and it needs to be interruptible. This
  1260. * function checks whether such interrupt condition occurred.
  1261. */
  1262. static int scan_should_stop(void)
  1263. {
  1264. if (!kmemleak_enabled)
  1265. return 1;
  1266. /*
  1267. * This function may be called from either process or kthread context,
  1268. * hence the need to check for both stop conditions.
  1269. */
  1270. if (current->mm)
  1271. return signal_pending(current);
  1272. else
  1273. return kthread_should_stop();
  1274. return 0;
  1275. }
  1276. /*
  1277. * Scan a memory block (exclusive range) for valid pointers and add those
  1278. * found to the gray list.
  1279. */
  1280. static void scan_block(void *_start, void *_end,
  1281. struct kmemleak_object *scanned)
  1282. {
  1283. unsigned long *ptr;
  1284. unsigned long *start = PTR_ALIGN(_start, BYTES_PER_POINTER);
  1285. unsigned long *end = _end - (BYTES_PER_POINTER - 1);
  1286. unsigned long flags;
  1287. raw_spin_lock_irqsave(&kmemleak_lock, flags);
  1288. for (ptr = start; ptr < end; ptr++) {
  1289. unsigned long pointer;
  1290. if (scan_should_stop())
  1291. break;
  1292. kasan_disable_current();
  1293. pointer = *(unsigned long *)kasan_reset_tag((void *)ptr);
  1294. kasan_enable_current();
  1295. pointer_update_refs(scanned, pointer, 0);
  1296. pointer_update_refs(scanned, pointer, OBJECT_PERCPU);
  1297. }
  1298. raw_spin_unlock_irqrestore(&kmemleak_lock, flags);
  1299. }
  1300. /*
  1301. * Scan a large memory block in MAX_SCAN_SIZE chunks to reduce the latency.
  1302. */
  1303. #ifdef CONFIG_SMP
  1304. static void scan_large_block(void *start, void *end)
  1305. {
  1306. void *next;
  1307. while (start < end) {
  1308. next = min(start + MAX_SCAN_SIZE, end);
  1309. scan_block(start, next, NULL);
  1310. start = next;
  1311. cond_resched();
  1312. }
  1313. }
  1314. #endif
  1315. /*
  1316. * Scan a memory block corresponding to a kmemleak_object. A condition is
  1317. * that object->use_count >= 1.
  1318. */
  1319. static void scan_object(struct kmemleak_object *object)
  1320. {
  1321. struct kmemleak_scan_area *area;
  1322. unsigned long flags;
  1323. /*
  1324. * Once the object->lock is acquired, the corresponding memory block
  1325. * cannot be freed (the same lock is acquired in delete_object).
  1326. */
  1327. raw_spin_lock_irqsave(&object->lock, flags);
  1328. if (object->flags & OBJECT_NO_SCAN)
  1329. goto out;
  1330. if (!(object->flags & OBJECT_ALLOCATED))
  1331. /* already freed object */
  1332. goto out;
  1333. if (object->flags & OBJECT_PERCPU) {
  1334. unsigned int cpu;
  1335. for_each_possible_cpu(cpu) {
  1336. void *start = per_cpu_ptr((void __percpu *)object->pointer, cpu);
  1337. void *end = start + object->size;
  1338. scan_block(start, end, object);
  1339. raw_spin_unlock_irqrestore(&object->lock, flags);
  1340. cond_resched();
  1341. raw_spin_lock_irqsave(&object->lock, flags);
  1342. if (!(object->flags & OBJECT_ALLOCATED))
  1343. break;
  1344. }
  1345. } else if (hlist_empty(&object->area_list) ||
  1346. object->flags & OBJECT_FULL_SCAN) {
  1347. void *start = object->flags & OBJECT_PHYS ?
  1348. __va((phys_addr_t)object->pointer) :
  1349. (void *)object->pointer;
  1350. void *end = start + object->size;
  1351. void *next;
  1352. do {
  1353. next = min(start + MAX_SCAN_SIZE, end);
  1354. scan_block(start, next, object);
  1355. start = next;
  1356. if (start >= end)
  1357. break;
  1358. raw_spin_unlock_irqrestore(&object->lock, flags);
  1359. cond_resched();
  1360. raw_spin_lock_irqsave(&object->lock, flags);
  1361. } while (object->flags & OBJECT_ALLOCATED);
  1362. } else {
  1363. hlist_for_each_entry(area, &object->area_list, node)
  1364. scan_block((void *)area->start,
  1365. (void *)(area->start + area->size),
  1366. object);
  1367. }
  1368. out:
  1369. raw_spin_unlock_irqrestore(&object->lock, flags);
  1370. }
  1371. /*
  1372. * Scan the objects already referenced (gray objects). More objects will be
  1373. * referenced and, if there are no memory leaks, all the objects are scanned.
  1374. */
  1375. static void scan_gray_list(void)
  1376. {
  1377. struct kmemleak_object *object, *tmp;
  1378. /*
  1379. * The list traversal is safe for both tail additions and removals
  1380. * from inside the loop. The kmemleak objects cannot be freed from
  1381. * outside the loop because their use_count was incremented.
  1382. */
  1383. object = list_entry(gray_list.next, typeof(*object), gray_list);
  1384. while (&object->gray_list != &gray_list) {
  1385. cond_resched();
  1386. /* may add new objects to the list */
  1387. if (!scan_should_stop())
  1388. scan_object(object);
  1389. tmp = list_entry(object->gray_list.next, typeof(*object),
  1390. gray_list);
  1391. /* remove the object from the list and release it */
  1392. list_del(&object->gray_list);
  1393. put_object(object);
  1394. object = tmp;
  1395. }
  1396. WARN_ON(!list_empty(&gray_list));
  1397. }
  1398. /*
  1399. * Conditionally call resched() in an object iteration loop while making sure
  1400. * that the given object won't go away without RCU read lock by performing a
  1401. * get_object() if necessaary.
  1402. */
  1403. static void kmemleak_cond_resched(struct kmemleak_object *object)
  1404. {
  1405. if (!get_object(object))
  1406. return; /* Try next object */
  1407. raw_spin_lock_irq(&kmemleak_lock);
  1408. if (object->del_state & DELSTATE_REMOVED)
  1409. goto unlock_put; /* Object removed */
  1410. object->del_state |= DELSTATE_NO_DELETE;
  1411. raw_spin_unlock_irq(&kmemleak_lock);
  1412. rcu_read_unlock();
  1413. cond_resched();
  1414. rcu_read_lock();
  1415. raw_spin_lock_irq(&kmemleak_lock);
  1416. if (object->del_state & DELSTATE_REMOVED)
  1417. list_del_rcu(&object->object_list);
  1418. object->del_state &= ~DELSTATE_NO_DELETE;
  1419. unlock_put:
  1420. raw_spin_unlock_irq(&kmemleak_lock);
  1421. put_object(object);
  1422. }
  1423. /*
  1424. * Scan data sections and all the referenced memory blocks allocated via the
  1425. * kernel's standard allocators. This function must be called with the
  1426. * scan_mutex held.
  1427. */
  1428. static void kmemleak_scan(void)
  1429. {
  1430. struct kmemleak_object *object;
  1431. struct zone *zone;
  1432. int __maybe_unused i;
  1433. int new_leaks = 0;
  1434. jiffies_last_scan = jiffies;
  1435. /* prepare the kmemleak_object's */
  1436. rcu_read_lock();
  1437. list_for_each_entry_rcu(object, &object_list, object_list) {
  1438. raw_spin_lock_irq(&object->lock);
  1439. #ifdef DEBUG
  1440. /*
  1441. * With a few exceptions there should be a maximum of
  1442. * 1 reference to any object at this point.
  1443. */
  1444. if (atomic_read(&object->use_count) > 1) {
  1445. pr_debug("object->use_count = %d\n",
  1446. atomic_read(&object->use_count));
  1447. dump_object_info(object);
  1448. }
  1449. #endif
  1450. /* ignore objects outside lowmem (paint them black) */
  1451. if ((object->flags & OBJECT_PHYS) &&
  1452. !(object->flags & OBJECT_NO_SCAN)) {
  1453. unsigned long phys = object->pointer;
  1454. if (PHYS_PFN(phys) < min_low_pfn ||
  1455. PHYS_PFN(phys + object->size) > max_low_pfn)
  1456. __paint_it(object, KMEMLEAK_BLACK);
  1457. }
  1458. /* reset the reference count (whiten the object) */
  1459. object->count = 0;
  1460. if (color_gray(object) && get_object(object))
  1461. list_add_tail(&object->gray_list, &gray_list);
  1462. raw_spin_unlock_irq(&object->lock);
  1463. if (need_resched())
  1464. kmemleak_cond_resched(object);
  1465. }
  1466. rcu_read_unlock();
  1467. #ifdef CONFIG_SMP
  1468. /* per-cpu sections scanning */
  1469. for_each_possible_cpu(i)
  1470. scan_large_block(__per_cpu_start + per_cpu_offset(i),
  1471. __per_cpu_end + per_cpu_offset(i));
  1472. #endif
  1473. /*
  1474. * Struct page scanning for each node.
  1475. */
  1476. get_online_mems();
  1477. for_each_populated_zone(zone) {
  1478. unsigned long start_pfn = zone->zone_start_pfn;
  1479. unsigned long end_pfn = zone_end_pfn(zone);
  1480. unsigned long pfn;
  1481. for (pfn = start_pfn; pfn < end_pfn; pfn++) {
  1482. struct page *page = pfn_to_online_page(pfn);
  1483. if (!(pfn & 63))
  1484. cond_resched();
  1485. if (!page)
  1486. continue;
  1487. /* only scan pages belonging to this zone */
  1488. if (page_zone(page) != zone)
  1489. continue;
  1490. /* only scan if page is in use */
  1491. if (page_count(page) == 0)
  1492. continue;
  1493. scan_block(page, page + 1, NULL);
  1494. }
  1495. }
  1496. put_online_mems();
  1497. /*
  1498. * Scanning the task stacks (may introduce false negatives).
  1499. */
  1500. if (kmemleak_stack_scan) {
  1501. struct task_struct *p, *g;
  1502. rcu_read_lock();
  1503. for_each_process_thread(g, p) {
  1504. void *stack = try_get_task_stack(p);
  1505. if (stack) {
  1506. scan_block(stack, stack + THREAD_SIZE, NULL);
  1507. put_task_stack(p);
  1508. }
  1509. }
  1510. rcu_read_unlock();
  1511. }
  1512. /*
  1513. * Scan the objects already referenced from the sections scanned
  1514. * above.
  1515. */
  1516. scan_gray_list();
  1517. /*
  1518. * Check for new or unreferenced objects modified since the previous
  1519. * scan and color them gray until the next scan.
  1520. */
  1521. rcu_read_lock();
  1522. list_for_each_entry_rcu(object, &object_list, object_list) {
  1523. if (need_resched())
  1524. kmemleak_cond_resched(object);
  1525. /*
  1526. * This is racy but we can save the overhead of lock/unlock
  1527. * calls. The missed objects, if any, should be caught in
  1528. * the next scan.
  1529. */
  1530. if (!color_white(object))
  1531. continue;
  1532. raw_spin_lock_irq(&object->lock);
  1533. if (color_white(object) && (object->flags & OBJECT_ALLOCATED)
  1534. && update_checksum(object) && get_object(object)) {
  1535. /* color it gray temporarily */
  1536. object->count = object->min_count;
  1537. list_add_tail(&object->gray_list, &gray_list);
  1538. }
  1539. raw_spin_unlock_irq(&object->lock);
  1540. }
  1541. rcu_read_unlock();
  1542. /*
  1543. * Re-scan the gray list for modified unreferenced objects.
  1544. */
  1545. scan_gray_list();
  1546. /*
  1547. * If scanning was stopped do not report any new unreferenced objects.
  1548. */
  1549. if (scan_should_stop())
  1550. return;
  1551. /*
  1552. * Scanning result reporting.
  1553. */
  1554. rcu_read_lock();
  1555. list_for_each_entry_rcu(object, &object_list, object_list) {
  1556. if (need_resched())
  1557. kmemleak_cond_resched(object);
  1558. /*
  1559. * This is racy but we can save the overhead of lock/unlock
  1560. * calls. The missed objects, if any, should be caught in
  1561. * the next scan.
  1562. */
  1563. if (!color_white(object))
  1564. continue;
  1565. raw_spin_lock_irq(&object->lock);
  1566. if (unreferenced_object(object) &&
  1567. !(object->flags & OBJECT_REPORTED)) {
  1568. object->flags |= OBJECT_REPORTED;
  1569. if (kmemleak_verbose)
  1570. print_unreferenced(NULL, object);
  1571. new_leaks++;
  1572. }
  1573. raw_spin_unlock_irq(&object->lock);
  1574. }
  1575. rcu_read_unlock();
  1576. if (new_leaks) {
  1577. kmemleak_found_leaks = true;
  1578. pr_info("%d new suspected memory leaks (see /sys/kernel/debug/kmemleak)\n",
  1579. new_leaks);
  1580. }
  1581. }
  1582. /*
  1583. * Thread function performing automatic memory scanning. Unreferenced objects
  1584. * at the end of a memory scan are reported but only the first time.
  1585. */
  1586. static int kmemleak_scan_thread(void *arg)
  1587. {
  1588. static int first_run = IS_ENABLED(CONFIG_DEBUG_KMEMLEAK_AUTO_SCAN);
  1589. pr_info("Automatic memory scanning thread started\n");
  1590. set_user_nice(current, 10);
  1591. /*
  1592. * Wait before the first scan to allow the system to fully initialize.
  1593. */
  1594. if (first_run) {
  1595. signed long timeout = msecs_to_jiffies(SECS_FIRST_SCAN * 1000);
  1596. first_run = 0;
  1597. while (timeout && !kthread_should_stop())
  1598. timeout = schedule_timeout_interruptible(timeout);
  1599. }
  1600. while (!kthread_should_stop()) {
  1601. signed long timeout = READ_ONCE(jiffies_scan_wait);
  1602. mutex_lock(&scan_mutex);
  1603. kmemleak_scan();
  1604. mutex_unlock(&scan_mutex);
  1605. /* wait before the next scan */
  1606. while (timeout && !kthread_should_stop())
  1607. timeout = schedule_timeout_interruptible(timeout);
  1608. }
  1609. pr_info("Automatic memory scanning thread ended\n");
  1610. return 0;
  1611. }
  1612. /*
  1613. * Start the automatic memory scanning thread. This function must be called
  1614. * with the scan_mutex held.
  1615. */
  1616. static void start_scan_thread(void)
  1617. {
  1618. if (scan_thread)
  1619. return;
  1620. scan_thread = kthread_run(kmemleak_scan_thread, NULL, "kmemleak");
  1621. if (IS_ERR(scan_thread)) {
  1622. pr_warn("Failed to create the scan thread\n");
  1623. scan_thread = NULL;
  1624. }
  1625. }
  1626. /*
  1627. * Stop the automatic memory scanning thread.
  1628. */
  1629. static void stop_scan_thread(void)
  1630. {
  1631. if (scan_thread) {
  1632. kthread_stop(scan_thread);
  1633. scan_thread = NULL;
  1634. }
  1635. }
  1636. /*
  1637. * Iterate over the object_list and return the first valid object at or after
  1638. * the required position with its use_count incremented. The function triggers
  1639. * a memory scanning when the pos argument points to the first position.
  1640. */
  1641. static void *kmemleak_seq_start(struct seq_file *seq, loff_t *pos)
  1642. {
  1643. struct kmemleak_object *object;
  1644. loff_t n = *pos;
  1645. int err;
  1646. err = mutex_lock_interruptible(&scan_mutex);
  1647. if (err < 0)
  1648. return ERR_PTR(err);
  1649. rcu_read_lock();
  1650. list_for_each_entry_rcu(object, &object_list, object_list) {
  1651. if (n-- > 0)
  1652. continue;
  1653. if (get_object(object))
  1654. goto out;
  1655. }
  1656. object = NULL;
  1657. out:
  1658. return object;
  1659. }
  1660. /*
  1661. * Return the next object in the object_list. The function decrements the
  1662. * use_count of the previous object and increases that of the next one.
  1663. */
  1664. static void *kmemleak_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  1665. {
  1666. struct kmemleak_object *prev_obj = v;
  1667. struct kmemleak_object *next_obj = NULL;
  1668. struct kmemleak_object *obj = prev_obj;
  1669. ++(*pos);
  1670. list_for_each_entry_continue_rcu(obj, &object_list, object_list) {
  1671. if (get_object(obj)) {
  1672. next_obj = obj;
  1673. break;
  1674. }
  1675. }
  1676. put_object(prev_obj);
  1677. return next_obj;
  1678. }
  1679. /*
  1680. * Decrement the use_count of the last object required, if any.
  1681. */
  1682. static void kmemleak_seq_stop(struct seq_file *seq, void *v)
  1683. {
  1684. if (!IS_ERR(v)) {
  1685. /*
  1686. * kmemleak_seq_start may return ERR_PTR if the scan_mutex
  1687. * waiting was interrupted, so only release it if !IS_ERR.
  1688. */
  1689. rcu_read_unlock();
  1690. mutex_unlock(&scan_mutex);
  1691. if (v)
  1692. put_object(v);
  1693. }
  1694. }
  1695. /*
  1696. * Print the information for an unreferenced object to the seq file.
  1697. */
  1698. static int kmemleak_seq_show(struct seq_file *seq, void *v)
  1699. {
  1700. struct kmemleak_object *object = v;
  1701. unsigned long flags;
  1702. raw_spin_lock_irqsave(&object->lock, flags);
  1703. if ((object->flags & OBJECT_REPORTED) && unreferenced_object(object))
  1704. print_unreferenced(seq, object);
  1705. raw_spin_unlock_irqrestore(&object->lock, flags);
  1706. return 0;
  1707. }
  1708. static const struct seq_operations kmemleak_seq_ops = {
  1709. .start = kmemleak_seq_start,
  1710. .next = kmemleak_seq_next,
  1711. .stop = kmemleak_seq_stop,
  1712. .show = kmemleak_seq_show,
  1713. };
  1714. static int kmemleak_open(struct inode *inode, struct file *file)
  1715. {
  1716. return seq_open(file, &kmemleak_seq_ops);
  1717. }
  1718. static int dump_str_object_info(const char *str)
  1719. {
  1720. unsigned long flags;
  1721. struct kmemleak_object *object;
  1722. unsigned long addr;
  1723. if (kstrtoul(str, 0, &addr))
  1724. return -EINVAL;
  1725. object = find_and_get_object(addr, 0);
  1726. if (!object) {
  1727. pr_info("Unknown object at 0x%08lx\n", addr);
  1728. return -EINVAL;
  1729. }
  1730. raw_spin_lock_irqsave(&object->lock, flags);
  1731. dump_object_info(object);
  1732. raw_spin_unlock_irqrestore(&object->lock, flags);
  1733. put_object(object);
  1734. return 0;
  1735. }
  1736. /*
  1737. * We use grey instead of black to ensure we can do future scans on the same
  1738. * objects. If we did not do future scans these black objects could
  1739. * potentially contain references to newly allocated objects in the future and
  1740. * we'd end up with false positives.
  1741. */
  1742. static void kmemleak_clear(void)
  1743. {
  1744. struct kmemleak_object *object;
  1745. rcu_read_lock();
  1746. list_for_each_entry_rcu(object, &object_list, object_list) {
  1747. raw_spin_lock_irq(&object->lock);
  1748. if ((object->flags & OBJECT_REPORTED) &&
  1749. unreferenced_object(object))
  1750. __paint_it(object, KMEMLEAK_GREY);
  1751. raw_spin_unlock_irq(&object->lock);
  1752. }
  1753. rcu_read_unlock();
  1754. kmemleak_found_leaks = false;
  1755. }
  1756. static void __kmemleak_do_cleanup(void);
  1757. /*
  1758. * File write operation to configure kmemleak at run-time. The following
  1759. * commands can be written to the /sys/kernel/debug/kmemleak file:
  1760. * off - disable kmemleak (irreversible)
  1761. * stack=on - enable the task stacks scanning
  1762. * stack=off - disable the tasks stacks scanning
  1763. * scan=on - start the automatic memory scanning thread
  1764. * scan=off - stop the automatic memory scanning thread
  1765. * scan=... - set the automatic memory scanning period in seconds (0 to
  1766. * disable it)
  1767. * scan - trigger a memory scan
  1768. * clear - mark all current reported unreferenced kmemleak objects as
  1769. * grey to ignore printing them, or free all kmemleak objects
  1770. * if kmemleak has been disabled.
  1771. * dump=... - dump information about the object found at the given address
  1772. */
  1773. static ssize_t kmemleak_write(struct file *file, const char __user *user_buf,
  1774. size_t size, loff_t *ppos)
  1775. {
  1776. char buf[64];
  1777. int buf_size;
  1778. int ret;
  1779. buf_size = min(size, (sizeof(buf) - 1));
  1780. if (strncpy_from_user(buf, user_buf, buf_size) < 0)
  1781. return -EFAULT;
  1782. buf[buf_size] = 0;
  1783. ret = mutex_lock_interruptible(&scan_mutex);
  1784. if (ret < 0)
  1785. return ret;
  1786. if (strncmp(buf, "clear", 5) == 0) {
  1787. if (kmemleak_enabled)
  1788. kmemleak_clear();
  1789. else
  1790. __kmemleak_do_cleanup();
  1791. goto out;
  1792. }
  1793. if (!kmemleak_enabled) {
  1794. ret = -EPERM;
  1795. goto out;
  1796. }
  1797. if (strncmp(buf, "off", 3) == 0)
  1798. kmemleak_disable();
  1799. else if (strncmp(buf, "stack=on", 8) == 0)
  1800. kmemleak_stack_scan = 1;
  1801. else if (strncmp(buf, "stack=off", 9) == 0)
  1802. kmemleak_stack_scan = 0;
  1803. else if (strncmp(buf, "scan=on", 7) == 0)
  1804. start_scan_thread();
  1805. else if (strncmp(buf, "scan=off", 8) == 0)
  1806. stop_scan_thread();
  1807. else if (strncmp(buf, "scan=", 5) == 0) {
  1808. unsigned secs;
  1809. unsigned long msecs;
  1810. ret = kstrtouint(buf + 5, 0, &secs);
  1811. if (ret < 0)
  1812. goto out;
  1813. msecs = secs * MSEC_PER_SEC;
  1814. if (msecs > UINT_MAX)
  1815. msecs = UINT_MAX;
  1816. stop_scan_thread();
  1817. if (msecs) {
  1818. WRITE_ONCE(jiffies_scan_wait, msecs_to_jiffies(msecs));
  1819. start_scan_thread();
  1820. }
  1821. } else if (strncmp(buf, "scan", 4) == 0)
  1822. kmemleak_scan();
  1823. else if (strncmp(buf, "dump=", 5) == 0)
  1824. ret = dump_str_object_info(buf + 5);
  1825. else
  1826. ret = -EINVAL;
  1827. out:
  1828. mutex_unlock(&scan_mutex);
  1829. if (ret < 0)
  1830. return ret;
  1831. /* ignore the rest of the buffer, only one command at a time */
  1832. *ppos += size;
  1833. return size;
  1834. }
  1835. static const struct file_operations kmemleak_fops = {
  1836. .owner = THIS_MODULE,
  1837. .open = kmemleak_open,
  1838. .read = seq_read,
  1839. .write = kmemleak_write,
  1840. .llseek = seq_lseek,
  1841. .release = seq_release,
  1842. };
  1843. static void __kmemleak_do_cleanup(void)
  1844. {
  1845. struct kmemleak_object *object, *tmp;
  1846. /*
  1847. * Kmemleak has already been disabled, no need for RCU list traversal
  1848. * or kmemleak_lock held.
  1849. */
  1850. list_for_each_entry_safe(object, tmp, &object_list, object_list) {
  1851. __remove_object(object);
  1852. __delete_object(object);
  1853. }
  1854. }
  1855. /*
  1856. * Stop the memory scanning thread and free the kmemleak internal objects if
  1857. * no previous scan thread (otherwise, kmemleak may still have some useful
  1858. * information on memory leaks).
  1859. */
  1860. static void kmemleak_do_cleanup(struct work_struct *work)
  1861. {
  1862. stop_scan_thread();
  1863. mutex_lock(&scan_mutex);
  1864. /*
  1865. * Once it is made sure that kmemleak_scan has stopped, it is safe to no
  1866. * longer track object freeing. Ordering of the scan thread stopping and
  1867. * the memory accesses below is guaranteed by the kthread_stop()
  1868. * function.
  1869. */
  1870. kmemleak_free_enabled = 0;
  1871. mutex_unlock(&scan_mutex);
  1872. if (!kmemleak_found_leaks)
  1873. __kmemleak_do_cleanup();
  1874. else
  1875. pr_info("Kmemleak disabled without freeing internal data. Reclaim the memory with \"echo clear > /sys/kernel/debug/kmemleak\".\n");
  1876. }
  1877. static DECLARE_WORK(cleanup_work, kmemleak_do_cleanup);
  1878. /*
  1879. * Disable kmemleak. No memory allocation/freeing will be traced once this
  1880. * function is called. Disabling kmemleak is an irreversible operation.
  1881. */
  1882. static void kmemleak_disable(void)
  1883. {
  1884. /* atomically check whether it was already invoked */
  1885. if (cmpxchg(&kmemleak_error, 0, 1))
  1886. return;
  1887. /* stop any memory operation tracing */
  1888. kmemleak_enabled = 0;
  1889. /* check whether it is too early for a kernel thread */
  1890. if (kmemleak_late_initialized)
  1891. schedule_work(&cleanup_work);
  1892. else
  1893. kmemleak_free_enabled = 0;
  1894. pr_info("Kernel memory leak detector disabled\n");
  1895. }
  1896. /*
  1897. * Allow boot-time kmemleak disabling (enabled by default).
  1898. */
  1899. static int __init kmemleak_boot_config(char *str)
  1900. {
  1901. if (!str)
  1902. return -EINVAL;
  1903. if (strcmp(str, "off") == 0)
  1904. kmemleak_disable();
  1905. else if (strcmp(str, "on") == 0) {
  1906. kmemleak_skip_disable = 1;
  1907. stack_depot_request_early_init();
  1908. }
  1909. else
  1910. return -EINVAL;
  1911. return 0;
  1912. }
  1913. early_param("kmemleak", kmemleak_boot_config);
  1914. /*
  1915. * Kmemleak initialization.
  1916. */
  1917. void __init kmemleak_init(void)
  1918. {
  1919. #ifdef CONFIG_DEBUG_KMEMLEAK_DEFAULT_OFF
  1920. if (!kmemleak_skip_disable) {
  1921. kmemleak_disable();
  1922. return;
  1923. }
  1924. #endif
  1925. if (kmemleak_error)
  1926. return;
  1927. jiffies_min_age = msecs_to_jiffies(MSECS_MIN_AGE);
  1928. jiffies_scan_wait = msecs_to_jiffies(SECS_SCAN_WAIT * 1000);
  1929. object_cache = KMEM_CACHE(kmemleak_object, SLAB_NOLEAKTRACE);
  1930. scan_area_cache = KMEM_CACHE(kmemleak_scan_area, SLAB_NOLEAKTRACE);
  1931. /* register the data/bss sections */
  1932. create_object((unsigned long)_sdata, _edata - _sdata,
  1933. KMEMLEAK_GREY, GFP_ATOMIC);
  1934. create_object((unsigned long)__bss_start, __bss_stop - __bss_start,
  1935. KMEMLEAK_GREY, GFP_ATOMIC);
  1936. /* only register .data..ro_after_init if not within .data */
  1937. if (&__start_ro_after_init < &_sdata || &__end_ro_after_init > &_edata)
  1938. create_object((unsigned long)__start_ro_after_init,
  1939. __end_ro_after_init - __start_ro_after_init,
  1940. KMEMLEAK_GREY, GFP_ATOMIC);
  1941. }
  1942. /*
  1943. * Late initialization function.
  1944. */
  1945. static int __init kmemleak_late_init(void)
  1946. {
  1947. kmemleak_late_initialized = 1;
  1948. debugfs_create_file("kmemleak", 0644, NULL, NULL, &kmemleak_fops);
  1949. if (kmemleak_error) {
  1950. /*
  1951. * Some error occurred and kmemleak was disabled. There is a
  1952. * small chance that kmemleak_disable() was called immediately
  1953. * after setting kmemleak_late_initialized and we may end up with
  1954. * two clean-up threads but serialized by scan_mutex.
  1955. */
  1956. schedule_work(&cleanup_work);
  1957. return -ENOMEM;
  1958. }
  1959. if (IS_ENABLED(CONFIG_DEBUG_KMEMLEAK_AUTO_SCAN)) {
  1960. mutex_lock(&scan_mutex);
  1961. start_scan_thread();
  1962. mutex_unlock(&scan_mutex);
  1963. }
  1964. pr_info("Kernel memory leak detector initialized (mem pool available: %d)\n",
  1965. mem_pool_free_count);
  1966. return 0;
  1967. }
  1968. late_initcall(kmemleak_late_init);