kmemleak.c 55 KB

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