kmemleak.c 40 KB

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