kmemleak.c 50 KB

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