kmemleak.c 48 KB

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