kmemleak.c 61 KB

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