kmemleak.c 64 KB

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