kmemleak.c 56 KB

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