kmemleak.c 56 KB

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