kmemleak.c 40 KB

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