kmemleak.c 59 KB

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