core.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * KFENCE guarded object allocator and fault handling.
  4. *
  5. * Copyright (C) 2020, Google LLC.
  6. */
  7. #define pr_fmt(fmt) "kfence: " fmt
  8. #include <linux/atomic.h>
  9. #include <linux/bug.h>
  10. #include <linux/debugfs.h>
  11. #include <linux/hash.h>
  12. #include <linux/irq_work.h>
  13. #include <linux/jhash.h>
  14. #include <linux/kasan-enabled.h>
  15. #include <linux/kcsan-checks.h>
  16. #include <linux/kfence.h>
  17. #include <linux/kmemleak.h>
  18. #include <linux/list.h>
  19. #include <linux/lockdep.h>
  20. #include <linux/log2.h>
  21. #include <linux/memblock.h>
  22. #include <linux/moduleparam.h>
  23. #include <linux/nodemask.h>
  24. #include <linux/notifier.h>
  25. #include <linux/panic_notifier.h>
  26. #include <linux/random.h>
  27. #include <linux/rcupdate.h>
  28. #include <linux/reboot.h>
  29. #include <linux/sched/clock.h>
  30. #include <linux/seq_file.h>
  31. #include <linux/slab.h>
  32. #include <linux/spinlock.h>
  33. #include <linux/string.h>
  34. #include <asm/kfence.h>
  35. #include "kfence.h"
  36. /* Disables KFENCE on the first warning assuming an irrecoverable error. */
  37. #define KFENCE_WARN_ON(cond) \
  38. ({ \
  39. const bool __cond = WARN_ON(cond); \
  40. if (unlikely(__cond)) { \
  41. WRITE_ONCE(kfence_enabled, false); \
  42. disabled_by_warn = true; \
  43. } \
  44. __cond; \
  45. })
  46. /* === Data ================================================================= */
  47. static bool kfence_enabled __read_mostly;
  48. static bool disabled_by_warn __read_mostly;
  49. unsigned long kfence_sample_interval __read_mostly = CONFIG_KFENCE_SAMPLE_INTERVAL;
  50. EXPORT_SYMBOL_GPL(kfence_sample_interval); /* Export for test modules. */
  51. #ifdef MODULE_PARAM_PREFIX
  52. #undef MODULE_PARAM_PREFIX
  53. #endif
  54. #define MODULE_PARAM_PREFIX "kfence."
  55. static int kfence_enable_late(void);
  56. static int param_set_sample_interval(const char *val, const struct kernel_param *kp)
  57. {
  58. unsigned long num;
  59. int ret = kstrtoul(val, 0, &num);
  60. if (ret < 0)
  61. return ret;
  62. /* Using 0 to indicate KFENCE is disabled. */
  63. if (!num && READ_ONCE(kfence_enabled)) {
  64. pr_info("disabled\n");
  65. WRITE_ONCE(kfence_enabled, false);
  66. }
  67. *((unsigned long *)kp->arg) = num;
  68. if (num && !READ_ONCE(kfence_enabled) && system_state != SYSTEM_BOOTING)
  69. return disabled_by_warn ? -EINVAL : kfence_enable_late();
  70. return 0;
  71. }
  72. static int param_get_sample_interval(char *buffer, const struct kernel_param *kp)
  73. {
  74. if (!READ_ONCE(kfence_enabled))
  75. return sprintf(buffer, "0\n");
  76. return param_get_ulong(buffer, kp);
  77. }
  78. static const struct kernel_param_ops sample_interval_param_ops = {
  79. .set = param_set_sample_interval,
  80. .get = param_get_sample_interval,
  81. };
  82. module_param_cb(sample_interval, &sample_interval_param_ops, &kfence_sample_interval, 0600);
  83. /* Pool usage% threshold when currently covered allocations are skipped. */
  84. static unsigned long kfence_skip_covered_thresh __read_mostly = 75;
  85. module_param_named(skip_covered_thresh, kfence_skip_covered_thresh, ulong, 0644);
  86. /* Allocation burst count: number of excess KFENCE allocations per sample. */
  87. static unsigned int kfence_burst __read_mostly;
  88. module_param_named(burst, kfence_burst, uint, 0644);
  89. /* If true, use a deferrable timer. */
  90. static bool kfence_deferrable __read_mostly = IS_ENABLED(CONFIG_KFENCE_DEFERRABLE);
  91. module_param_named(deferrable, kfence_deferrable, bool, 0444);
  92. /* If true, check all canary bytes on panic. */
  93. static bool kfence_check_on_panic __read_mostly;
  94. module_param_named(check_on_panic, kfence_check_on_panic, bool, 0444);
  95. /* The pool of pages used for guard pages and objects. */
  96. char *__kfence_pool __read_mostly;
  97. EXPORT_SYMBOL(__kfence_pool); /* Export for test modules. */
  98. /*
  99. * Per-object metadata, with one-to-one mapping of object metadata to
  100. * backing pages (in __kfence_pool).
  101. */
  102. static_assert(CONFIG_KFENCE_NUM_OBJECTS > 0);
  103. struct kfence_metadata *kfence_metadata __read_mostly;
  104. /*
  105. * If kfence_metadata is not NULL, it may be accessed by kfence_shutdown_cache().
  106. * So introduce kfence_metadata_init to initialize metadata, and then make
  107. * kfence_metadata visible after initialization is successful. This prevents
  108. * potential UAF or access to uninitialized metadata.
  109. */
  110. static struct kfence_metadata *kfence_metadata_init __read_mostly;
  111. /* Freelist with available objects. */
  112. DEFINE_RAW_SPINLOCK(kfence_freelist_lock); /* Lock protecting freelist. */
  113. static struct list_head kfence_freelist __guarded_by(&kfence_freelist_lock) = LIST_HEAD_INIT(kfence_freelist);
  114. /*
  115. * The static key to set up a KFENCE allocation; or if static keys are not used
  116. * to gate allocations, to avoid a load and compare if KFENCE is disabled.
  117. */
  118. DEFINE_STATIC_KEY_FALSE(kfence_allocation_key);
  119. /* Gates the allocation, ensuring only one succeeds in a given period. */
  120. atomic_t kfence_allocation_gate = ATOMIC_INIT(1);
  121. /*
  122. * A Counting Bloom filter of allocation coverage: limits currently covered
  123. * allocations of the same source filling up the pool.
  124. *
  125. * Assuming a range of 15%-85% unique allocations in the pool at any point in
  126. * time, the below parameters provide a probablity of 0.02-0.33 for false
  127. * positive hits respectively:
  128. *
  129. * P(alloc_traces) = (1 - e^(-HNUM * (alloc_traces / SIZE)) ^ HNUM
  130. */
  131. #define ALLOC_COVERED_HNUM 2
  132. #define ALLOC_COVERED_ORDER (const_ilog2(CONFIG_KFENCE_NUM_OBJECTS) + 2)
  133. #define ALLOC_COVERED_SIZE (1 << ALLOC_COVERED_ORDER)
  134. #define ALLOC_COVERED_HNEXT(h) hash_32(h, ALLOC_COVERED_ORDER)
  135. #define ALLOC_COVERED_MASK (ALLOC_COVERED_SIZE - 1)
  136. static atomic_t alloc_covered[ALLOC_COVERED_SIZE];
  137. /* Stack depth used to determine uniqueness of an allocation. */
  138. #define UNIQUE_ALLOC_STACK_DEPTH ((size_t)8)
  139. /*
  140. * Randomness for stack hashes, making the same collisions across reboots and
  141. * different machines less likely.
  142. */
  143. static u32 stack_hash_seed __ro_after_init;
  144. /* Statistics counters for debugfs. */
  145. enum kfence_counter_id {
  146. KFENCE_COUNTER_ALLOCATED,
  147. KFENCE_COUNTER_ALLOCS,
  148. KFENCE_COUNTER_FREES,
  149. KFENCE_COUNTER_ZOMBIES,
  150. KFENCE_COUNTER_BUGS,
  151. KFENCE_COUNTER_SKIP_INCOMPAT,
  152. KFENCE_COUNTER_SKIP_CAPACITY,
  153. KFENCE_COUNTER_SKIP_COVERED,
  154. KFENCE_COUNTER_COUNT,
  155. };
  156. static atomic_long_t counters[KFENCE_COUNTER_COUNT];
  157. static const char *const counter_names[] = {
  158. [KFENCE_COUNTER_ALLOCATED] = "currently allocated",
  159. [KFENCE_COUNTER_ALLOCS] = "total allocations",
  160. [KFENCE_COUNTER_FREES] = "total frees",
  161. [KFENCE_COUNTER_ZOMBIES] = "zombie allocations",
  162. [KFENCE_COUNTER_BUGS] = "total bugs",
  163. [KFENCE_COUNTER_SKIP_INCOMPAT] = "skipped allocations (incompatible)",
  164. [KFENCE_COUNTER_SKIP_CAPACITY] = "skipped allocations (capacity)",
  165. [KFENCE_COUNTER_SKIP_COVERED] = "skipped allocations (covered)",
  166. };
  167. static_assert(ARRAY_SIZE(counter_names) == KFENCE_COUNTER_COUNT);
  168. /* === Internals ============================================================ */
  169. static inline bool should_skip_covered(void)
  170. {
  171. unsigned long thresh = (CONFIG_KFENCE_NUM_OBJECTS * kfence_skip_covered_thresh) / 100;
  172. return atomic_long_read(&counters[KFENCE_COUNTER_ALLOCATED]) > thresh;
  173. }
  174. static u32 get_alloc_stack_hash(unsigned long *stack_entries, size_t num_entries)
  175. {
  176. num_entries = min(num_entries, UNIQUE_ALLOC_STACK_DEPTH);
  177. num_entries = filter_irq_stacks(stack_entries, num_entries);
  178. return jhash(stack_entries, num_entries * sizeof(stack_entries[0]), stack_hash_seed);
  179. }
  180. /*
  181. * Adds (or subtracts) count @val for allocation stack trace hash
  182. * @alloc_stack_hash from Counting Bloom filter.
  183. */
  184. static void alloc_covered_add(u32 alloc_stack_hash, int val)
  185. {
  186. int i;
  187. for (i = 0; i < ALLOC_COVERED_HNUM; i++) {
  188. atomic_add(val, &alloc_covered[alloc_stack_hash & ALLOC_COVERED_MASK]);
  189. alloc_stack_hash = ALLOC_COVERED_HNEXT(alloc_stack_hash);
  190. }
  191. }
  192. /*
  193. * Returns true if the allocation stack trace hash @alloc_stack_hash is
  194. * currently contained (non-zero count) in Counting Bloom filter.
  195. */
  196. static bool alloc_covered_contains(u32 alloc_stack_hash)
  197. {
  198. int i;
  199. for (i = 0; i < ALLOC_COVERED_HNUM; i++) {
  200. if (!atomic_read(&alloc_covered[alloc_stack_hash & ALLOC_COVERED_MASK]))
  201. return false;
  202. alloc_stack_hash = ALLOC_COVERED_HNEXT(alloc_stack_hash);
  203. }
  204. return true;
  205. }
  206. static bool kfence_protect(unsigned long addr)
  207. {
  208. return !KFENCE_WARN_ON(!kfence_protect_page(ALIGN_DOWN(addr, PAGE_SIZE), true));
  209. }
  210. static bool kfence_unprotect(unsigned long addr)
  211. {
  212. return !KFENCE_WARN_ON(!kfence_protect_page(ALIGN_DOWN(addr, PAGE_SIZE), false));
  213. }
  214. static inline unsigned long metadata_to_pageaddr(const struct kfence_metadata *meta)
  215. __must_hold(&meta->lock)
  216. {
  217. unsigned long offset = (meta - kfence_metadata + 1) * PAGE_SIZE * 2;
  218. unsigned long pageaddr = (unsigned long)&__kfence_pool[offset];
  219. /* The checks do not affect performance; only called from slow-paths. */
  220. /* Only call with a pointer into kfence_metadata. */
  221. if (KFENCE_WARN_ON(meta < kfence_metadata ||
  222. meta >= kfence_metadata + CONFIG_KFENCE_NUM_OBJECTS))
  223. return 0;
  224. /*
  225. * This metadata object only ever maps to 1 page; verify that the stored
  226. * address is in the expected range.
  227. */
  228. if (KFENCE_WARN_ON(ALIGN_DOWN(meta->addr, PAGE_SIZE) != pageaddr))
  229. return 0;
  230. return pageaddr;
  231. }
  232. static inline bool kfence_obj_allocated(const struct kfence_metadata *meta)
  233. {
  234. enum kfence_object_state state = READ_ONCE(meta->state);
  235. return state == KFENCE_OBJECT_ALLOCATED || state == KFENCE_OBJECT_RCU_FREEING;
  236. }
  237. /*
  238. * Update the object's metadata state, including updating the alloc/free stacks
  239. * depending on the state transition.
  240. */
  241. static noinline void
  242. metadata_update_state(struct kfence_metadata *meta, enum kfence_object_state next,
  243. unsigned long *stack_entries, size_t num_stack_entries)
  244. __must_hold(&meta->lock)
  245. {
  246. struct kfence_track *track =
  247. next == KFENCE_OBJECT_ALLOCATED ? &meta->alloc_track : &meta->free_track;
  248. lockdep_assert_held(&meta->lock);
  249. /* Stack has been saved when calling rcu, skip. */
  250. if (READ_ONCE(meta->state) == KFENCE_OBJECT_RCU_FREEING)
  251. goto out;
  252. if (stack_entries) {
  253. memcpy(track->stack_entries, stack_entries,
  254. num_stack_entries * sizeof(stack_entries[0]));
  255. } else {
  256. /*
  257. * Skip over 1 (this) functions; noinline ensures we do not
  258. * accidentally skip over the caller by never inlining.
  259. */
  260. num_stack_entries = stack_trace_save(track->stack_entries, KFENCE_STACK_DEPTH, 1);
  261. }
  262. track->num_stack_entries = num_stack_entries;
  263. track->pid = task_pid_nr(current);
  264. track->cpu = raw_smp_processor_id();
  265. track->ts_nsec = local_clock(); /* Same source as printk timestamps. */
  266. out:
  267. /*
  268. * Pairs with READ_ONCE() in
  269. * kfence_shutdown_cache(),
  270. * kfence_handle_page_fault().
  271. */
  272. WRITE_ONCE(meta->state, next);
  273. }
  274. #ifdef CONFIG_KMSAN
  275. #define check_canary_attributes noinline __no_kmsan_checks
  276. #else
  277. #define check_canary_attributes inline
  278. #endif
  279. /* Check canary byte at @addr. */
  280. static check_canary_attributes bool check_canary_byte(u8 *addr)
  281. {
  282. struct kfence_metadata *meta;
  283. unsigned long flags;
  284. if (likely(*addr == KFENCE_CANARY_PATTERN_U8(addr)))
  285. return true;
  286. atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
  287. meta = addr_to_metadata((unsigned long)addr);
  288. raw_spin_lock_irqsave(&meta->lock, flags);
  289. kfence_report_error((unsigned long)addr, false, NULL, meta, KFENCE_ERROR_CORRUPTION);
  290. raw_spin_unlock_irqrestore(&meta->lock, flags);
  291. return false;
  292. }
  293. static inline void set_canary(const struct kfence_metadata *meta)
  294. {
  295. const unsigned long pageaddr = ALIGN_DOWN(meta->addr, PAGE_SIZE);
  296. unsigned long addr = pageaddr;
  297. /*
  298. * The canary may be written to part of the object memory, but it does
  299. * not affect it. The user should initialize the object before using it.
  300. */
  301. for (; addr < meta->addr; addr += sizeof(u64))
  302. *((u64 *)addr) = KFENCE_CANARY_PATTERN_U64;
  303. addr = ALIGN_DOWN(meta->addr + meta->size, sizeof(u64));
  304. for (; addr - pageaddr < PAGE_SIZE; addr += sizeof(u64))
  305. *((u64 *)addr) = KFENCE_CANARY_PATTERN_U64;
  306. }
  307. static check_canary_attributes void
  308. check_canary(const struct kfence_metadata *meta)
  309. {
  310. const unsigned long pageaddr = ALIGN_DOWN(meta->addr, PAGE_SIZE);
  311. unsigned long addr = pageaddr;
  312. /*
  313. * We'll iterate over each canary byte per-side until a corrupted byte
  314. * is found. However, we'll still iterate over the canary bytes to the
  315. * right of the object even if there was an error in the canary bytes to
  316. * the left of the object. Specifically, if check_canary_byte()
  317. * generates an error, showing both sides might give more clues as to
  318. * what the error is about when displaying which bytes were corrupted.
  319. */
  320. /* Apply to left of object. */
  321. for (; meta->addr - addr >= sizeof(u64); addr += sizeof(u64)) {
  322. if (unlikely(*((u64 *)addr) != KFENCE_CANARY_PATTERN_U64))
  323. break;
  324. }
  325. /*
  326. * If the canary is corrupted in a certain 64 bytes, or the canary
  327. * memory cannot be completely covered by multiple consecutive 64 bytes,
  328. * it needs to be checked one by one.
  329. */
  330. for (; addr < meta->addr; addr++) {
  331. if (unlikely(!check_canary_byte((u8 *)addr)))
  332. break;
  333. }
  334. /* Apply to right of object. */
  335. for (addr = meta->addr + meta->size; addr % sizeof(u64) != 0; addr++) {
  336. if (unlikely(!check_canary_byte((u8 *)addr)))
  337. return;
  338. }
  339. for (; addr - pageaddr < PAGE_SIZE; addr += sizeof(u64)) {
  340. if (unlikely(*((u64 *)addr) != KFENCE_CANARY_PATTERN_U64)) {
  341. for (; addr - pageaddr < PAGE_SIZE; addr++) {
  342. if (!check_canary_byte((u8 *)addr))
  343. return;
  344. }
  345. }
  346. }
  347. }
  348. static void *kfence_guarded_alloc(struct kmem_cache *cache, size_t size, gfp_t gfp,
  349. unsigned long *stack_entries, size_t num_stack_entries,
  350. u32 alloc_stack_hash)
  351. {
  352. struct kfence_metadata *meta = NULL;
  353. unsigned long flags;
  354. struct slab *slab;
  355. void *addr;
  356. const bool random_right_allocate = get_random_u32_below(2);
  357. const bool random_fault = CONFIG_KFENCE_STRESS_TEST_FAULTS &&
  358. !get_random_u32_below(CONFIG_KFENCE_STRESS_TEST_FAULTS);
  359. /* Try to obtain a free object. */
  360. raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
  361. if (!list_empty(&kfence_freelist)) {
  362. meta = list_entry(kfence_freelist.next, struct kfence_metadata, list);
  363. list_del_init(&meta->list);
  364. }
  365. raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
  366. if (!meta) {
  367. atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_CAPACITY]);
  368. return NULL;
  369. }
  370. if (unlikely(!raw_spin_trylock_irqsave(&meta->lock, flags))) {
  371. /*
  372. * This is extremely unlikely -- we are reporting on a
  373. * use-after-free, which locked meta->lock, and the reporting
  374. * code via printk calls kmalloc() which ends up in
  375. * kfence_alloc() and tries to grab the same object that we're
  376. * reporting on. While it has never been observed, lockdep does
  377. * report that there is a possibility of deadlock. Fix it by
  378. * using trylock and bailing out gracefully.
  379. */
  380. raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
  381. /* Put the object back on the freelist. */
  382. list_add_tail(&meta->list, &kfence_freelist);
  383. raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
  384. return NULL;
  385. }
  386. meta->addr = metadata_to_pageaddr(meta);
  387. /* Unprotect if we're reusing this page. */
  388. if (meta->state == KFENCE_OBJECT_FREED)
  389. kfence_unprotect(meta->addr);
  390. /*
  391. * Note: for allocations made before RNG initialization, will always
  392. * return zero. We still benefit from enabling KFENCE as early as
  393. * possible, even when the RNG is not yet available, as this will allow
  394. * KFENCE to detect bugs due to earlier allocations. The only downside
  395. * is that the out-of-bounds accesses detected are deterministic for
  396. * such allocations.
  397. */
  398. if (random_right_allocate) {
  399. /* Allocate on the "right" side, re-calculate address. */
  400. meta->addr += PAGE_SIZE - size;
  401. meta->addr = ALIGN_DOWN(meta->addr, cache->align);
  402. }
  403. addr = (void *)meta->addr;
  404. /* Update remaining metadata. */
  405. metadata_update_state(meta, KFENCE_OBJECT_ALLOCATED, stack_entries, num_stack_entries);
  406. /* Pairs with READ_ONCE() in kfence_shutdown_cache(). */
  407. WRITE_ONCE(meta->cache, cache);
  408. meta->size = size;
  409. meta->alloc_stack_hash = alloc_stack_hash;
  410. raw_spin_unlock_irqrestore(&meta->lock, flags);
  411. alloc_covered_add(alloc_stack_hash, 1);
  412. /* Set required slab fields. */
  413. slab = virt_to_slab(addr);
  414. slab->slab_cache = cache;
  415. slab->objects = 1;
  416. /* Memory initialization. */
  417. set_canary(meta);
  418. /*
  419. * We check slab_want_init_on_alloc() ourselves, rather than letting
  420. * SL*B do the initialization, as otherwise we might overwrite KFENCE's
  421. * redzone.
  422. */
  423. if (unlikely(slab_want_init_on_alloc(gfp, cache)))
  424. memzero_explicit(addr, size);
  425. if (cache->ctor)
  426. cache->ctor(addr);
  427. if (random_fault)
  428. kfence_protect(meta->addr); /* Random "faults" by protecting the object. */
  429. atomic_long_inc(&counters[KFENCE_COUNTER_ALLOCATED]);
  430. atomic_long_inc(&counters[KFENCE_COUNTER_ALLOCS]);
  431. return addr;
  432. }
  433. static void kfence_guarded_free(void *addr, struct kfence_metadata *meta, bool zombie)
  434. {
  435. struct kcsan_scoped_access assert_page_exclusive;
  436. u32 alloc_stack_hash;
  437. unsigned long flags;
  438. bool init;
  439. raw_spin_lock_irqsave(&meta->lock, flags);
  440. if (!kfence_obj_allocated(meta) || meta->addr != (unsigned long)addr) {
  441. /* Invalid or double-free, bail out. */
  442. atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
  443. kfence_report_error((unsigned long)addr, false, NULL, meta,
  444. KFENCE_ERROR_INVALID_FREE);
  445. raw_spin_unlock_irqrestore(&meta->lock, flags);
  446. return;
  447. }
  448. /* Detect racy use-after-free, or incorrect reallocation of this page by KFENCE. */
  449. kcsan_begin_scoped_access((void *)ALIGN_DOWN((unsigned long)addr, PAGE_SIZE), PAGE_SIZE,
  450. KCSAN_ACCESS_SCOPED | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT,
  451. &assert_page_exclusive);
  452. if (CONFIG_KFENCE_STRESS_TEST_FAULTS)
  453. kfence_unprotect((unsigned long)addr); /* To check canary bytes. */
  454. /* Restore page protection if there was an OOB access. */
  455. if (meta->unprotected_page) {
  456. memzero_explicit((void *)ALIGN_DOWN(meta->unprotected_page, PAGE_SIZE), PAGE_SIZE);
  457. kfence_protect(meta->unprotected_page);
  458. meta->unprotected_page = 0;
  459. }
  460. /* Mark the object as freed. */
  461. metadata_update_state(meta, KFENCE_OBJECT_FREED, NULL, 0);
  462. init = slab_want_init_on_free(meta->cache);
  463. alloc_stack_hash = meta->alloc_stack_hash;
  464. raw_spin_unlock_irqrestore(&meta->lock, flags);
  465. alloc_covered_add(alloc_stack_hash, -1);
  466. /* Check canary bytes for memory corruption. */
  467. check_canary(meta);
  468. /*
  469. * Clear memory if init-on-free is set. While we protect the page, the
  470. * data is still there, and after a use-after-free is detected, we
  471. * unprotect the page, so the data is still accessible.
  472. */
  473. if (!zombie && unlikely(init))
  474. memzero_explicit(addr, meta->size);
  475. /* Protect to detect use-after-frees. */
  476. kfence_protect((unsigned long)addr);
  477. kcsan_end_scoped_access(&assert_page_exclusive);
  478. if (!zombie) {
  479. /* Add it to the tail of the freelist for reuse. */
  480. raw_spin_lock_irqsave(&kfence_freelist_lock, flags);
  481. KFENCE_WARN_ON(!list_empty(&meta->list));
  482. list_add_tail(&meta->list, &kfence_freelist);
  483. raw_spin_unlock_irqrestore(&kfence_freelist_lock, flags);
  484. atomic_long_dec(&counters[KFENCE_COUNTER_ALLOCATED]);
  485. atomic_long_inc(&counters[KFENCE_COUNTER_FREES]);
  486. } else {
  487. /* See kfence_shutdown_cache(). */
  488. atomic_long_inc(&counters[KFENCE_COUNTER_ZOMBIES]);
  489. }
  490. }
  491. static void rcu_guarded_free(struct rcu_head *h)
  492. {
  493. struct kfence_metadata *meta = container_of(h, struct kfence_metadata, rcu_head);
  494. kfence_guarded_free((void *)meta->addr, meta, false);
  495. }
  496. /*
  497. * Initialization of the KFENCE pool after its allocation.
  498. * Returns 0 on success; otherwise returns the address up to
  499. * which partial initialization succeeded.
  500. */
  501. static unsigned long kfence_init_pool(void)
  502. __context_unsafe(/* constructor */)
  503. {
  504. unsigned long addr, start_pfn;
  505. int i, rand;
  506. if (!arch_kfence_init_pool())
  507. return (unsigned long)__kfence_pool;
  508. addr = (unsigned long)__kfence_pool;
  509. start_pfn = PHYS_PFN(virt_to_phys(__kfence_pool));
  510. /*
  511. * Set up object pages: they must have PGTY_slab set to avoid freeing
  512. * them as real pages.
  513. *
  514. * We also want to avoid inserting kfence_free() in the kfree()
  515. * fast-path in SLUB, and therefore need to ensure kfree() correctly
  516. * enters __slab_free() slow-path.
  517. */
  518. for (i = 0; i < KFENCE_POOL_SIZE / PAGE_SIZE; i++) {
  519. struct page *page;
  520. if (!i || (i % 2))
  521. continue;
  522. page = pfn_to_page(start_pfn + i);
  523. __SetPageSlab(page);
  524. #ifdef CONFIG_MEMCG
  525. struct slab *slab = page_slab(page);
  526. slab->obj_exts = (unsigned long)&kfence_metadata_init[i / 2 - 1].obj_exts |
  527. MEMCG_DATA_OBJEXTS;
  528. #endif
  529. }
  530. /*
  531. * Protect the first 2 pages. The first page is mostly unnecessary, and
  532. * merely serves as an extended guard page. However, adding one
  533. * additional page in the beginning gives us an even number of pages,
  534. * which simplifies the mapping of address to metadata index.
  535. */
  536. for (i = 0; i < 2; i++) {
  537. if (unlikely(!kfence_protect(addr)))
  538. return addr;
  539. addr += PAGE_SIZE;
  540. }
  541. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  542. struct kfence_metadata *meta = &kfence_metadata_init[i];
  543. /* Initialize metadata. */
  544. INIT_LIST_HEAD(&meta->list);
  545. raw_spin_lock_init(&meta->lock);
  546. meta->state = KFENCE_OBJECT_UNUSED;
  547. /* Use addr to randomize the freelist. */
  548. meta->addr = i;
  549. /* Protect the right redzone. */
  550. if (unlikely(!kfence_protect(addr + 2 * i * PAGE_SIZE + PAGE_SIZE)))
  551. goto reset_slab;
  552. }
  553. for (i = CONFIG_KFENCE_NUM_OBJECTS; i > 0; i--) {
  554. rand = get_random_u32_below(i);
  555. swap(kfence_metadata_init[i - 1].addr, kfence_metadata_init[rand].addr);
  556. }
  557. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  558. struct kfence_metadata *meta_1 = &kfence_metadata_init[i];
  559. struct kfence_metadata *meta_2 = &kfence_metadata_init[meta_1->addr];
  560. list_add_tail(&meta_2->list, &kfence_freelist);
  561. }
  562. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  563. kfence_metadata_init[i].addr = addr;
  564. addr += 2 * PAGE_SIZE;
  565. }
  566. /*
  567. * Make kfence_metadata visible only when initialization is successful.
  568. * Otherwise, if the initialization fails and kfence_metadata is freed,
  569. * it may cause UAF in kfence_shutdown_cache().
  570. */
  571. smp_store_release(&kfence_metadata, kfence_metadata_init);
  572. return 0;
  573. reset_slab:
  574. addr += 2 * i * PAGE_SIZE;
  575. for (i = 0; i < KFENCE_POOL_SIZE / PAGE_SIZE; i++) {
  576. struct page *page;
  577. if (!i || (i % 2))
  578. continue;
  579. page = pfn_to_page(start_pfn + i);
  580. #ifdef CONFIG_MEMCG
  581. struct slab *slab = page_slab(page);
  582. slab->obj_exts = 0;
  583. #endif
  584. __ClearPageSlab(page);
  585. }
  586. return addr;
  587. }
  588. static bool __init kfence_init_pool_early(void)
  589. {
  590. unsigned long addr;
  591. if (!__kfence_pool)
  592. return false;
  593. addr = kfence_init_pool();
  594. if (!addr) {
  595. /*
  596. * The pool is live and will never be deallocated from this point on.
  597. * Ignore the pool object from the kmemleak phys object tree, as it would
  598. * otherwise overlap with allocations returned by kfence_alloc(), which
  599. * are registered with kmemleak through the slab post-alloc hook.
  600. */
  601. kmemleak_ignore_phys(__pa(__kfence_pool));
  602. return true;
  603. }
  604. /*
  605. * Only release unprotected pages, and do not try to go back and change
  606. * page attributes due to risk of failing to do so as well. If changing
  607. * page attributes for some pages fails, it is very likely that it also
  608. * fails for the first page, and therefore expect addr==__kfence_pool in
  609. * most failure cases.
  610. */
  611. memblock_free_late(__pa(addr), KFENCE_POOL_SIZE - (addr - (unsigned long)__kfence_pool));
  612. __kfence_pool = NULL;
  613. memblock_free_late(__pa(kfence_metadata_init), KFENCE_METADATA_SIZE);
  614. kfence_metadata_init = NULL;
  615. return false;
  616. }
  617. /* === DebugFS Interface ==================================================== */
  618. static int stats_show(struct seq_file *seq, void *v)
  619. {
  620. int i;
  621. seq_printf(seq, "enabled: %i\n", READ_ONCE(kfence_enabled));
  622. for (i = 0; i < KFENCE_COUNTER_COUNT; i++)
  623. seq_printf(seq, "%s: %ld\n", counter_names[i], atomic_long_read(&counters[i]));
  624. return 0;
  625. }
  626. DEFINE_SHOW_ATTRIBUTE(stats);
  627. /*
  628. * debugfs seq_file operations for /sys/kernel/debug/kfence/objects.
  629. * start_object() and next_object() return the object index + 1, because NULL is used
  630. * to stop iteration.
  631. */
  632. static void *start_object(struct seq_file *seq, loff_t *pos)
  633. {
  634. if (*pos < CONFIG_KFENCE_NUM_OBJECTS)
  635. return (void *)((long)*pos + 1);
  636. return NULL;
  637. }
  638. static void stop_object(struct seq_file *seq, void *v)
  639. {
  640. }
  641. static void *next_object(struct seq_file *seq, void *v, loff_t *pos)
  642. {
  643. ++*pos;
  644. if (*pos < CONFIG_KFENCE_NUM_OBJECTS)
  645. return (void *)((long)*pos + 1);
  646. return NULL;
  647. }
  648. static int show_object(struct seq_file *seq, void *v)
  649. {
  650. struct kfence_metadata *meta = &kfence_metadata[(long)v - 1];
  651. unsigned long flags;
  652. raw_spin_lock_irqsave(&meta->lock, flags);
  653. kfence_print_object(seq, meta);
  654. raw_spin_unlock_irqrestore(&meta->lock, flags);
  655. seq_puts(seq, "---------------------------------\n");
  656. return 0;
  657. }
  658. static const struct seq_operations objects_sops = {
  659. .start = start_object,
  660. .next = next_object,
  661. .stop = stop_object,
  662. .show = show_object,
  663. };
  664. DEFINE_SEQ_ATTRIBUTE(objects);
  665. static int kfence_debugfs_init(void)
  666. {
  667. struct dentry *kfence_dir;
  668. if (!READ_ONCE(kfence_enabled))
  669. return 0;
  670. kfence_dir = debugfs_create_dir("kfence", NULL);
  671. debugfs_create_file("stats", 0444, kfence_dir, NULL, &stats_fops);
  672. debugfs_create_file("objects", 0400, kfence_dir, NULL, &objects_fops);
  673. return 0;
  674. }
  675. late_initcall(kfence_debugfs_init);
  676. /* === Panic Notifier ====================================================== */
  677. static void kfence_check_all_canary(void)
  678. {
  679. int i;
  680. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  681. struct kfence_metadata *meta = &kfence_metadata[i];
  682. if (kfence_obj_allocated(meta))
  683. check_canary(meta);
  684. }
  685. }
  686. static int kfence_check_canary_callback(struct notifier_block *nb,
  687. unsigned long reason, void *arg)
  688. {
  689. kfence_check_all_canary();
  690. return NOTIFY_OK;
  691. }
  692. static struct notifier_block kfence_check_canary_notifier = {
  693. .notifier_call = kfence_check_canary_callback,
  694. };
  695. /* === Allocation Gate Timer ================================================ */
  696. static struct delayed_work kfence_timer;
  697. #ifdef CONFIG_KFENCE_STATIC_KEYS
  698. /* Wait queue to wake up allocation-gate timer task. */
  699. static DECLARE_WAIT_QUEUE_HEAD(allocation_wait);
  700. static int kfence_reboot_callback(struct notifier_block *nb,
  701. unsigned long action, void *data)
  702. {
  703. /*
  704. * Disable kfence to avoid static keys IPI synchronization during
  705. * late shutdown/kexec
  706. */
  707. WRITE_ONCE(kfence_enabled, false);
  708. /* Cancel any pending timer work */
  709. cancel_delayed_work(&kfence_timer);
  710. /*
  711. * Wake up any blocked toggle_allocation_gate() so it can complete
  712. * early while the system is still able to handle IPIs.
  713. */
  714. wake_up(&allocation_wait);
  715. return NOTIFY_OK;
  716. }
  717. static struct notifier_block kfence_reboot_notifier = {
  718. .notifier_call = kfence_reboot_callback,
  719. .priority = INT_MAX, /* Run early to stop timers ASAP */
  720. };
  721. static void wake_up_kfence_timer(struct irq_work *work)
  722. {
  723. wake_up(&allocation_wait);
  724. }
  725. static DEFINE_IRQ_WORK(wake_up_kfence_timer_work, wake_up_kfence_timer);
  726. #endif
  727. /*
  728. * Set up delayed work, which will enable and disable the static key. We need to
  729. * use a work queue (rather than a simple timer), since enabling and disabling a
  730. * static key cannot be done from an interrupt.
  731. *
  732. * Note: Toggling a static branch currently causes IPIs, and here we'll end up
  733. * with a total of 2 IPIs to all CPUs. If this ends up a problem in future (with
  734. * more aggressive sampling intervals), we could get away with a variant that
  735. * avoids IPIs, at the cost of not immediately capturing allocations if the
  736. * instructions remain cached.
  737. */
  738. static void toggle_allocation_gate(struct work_struct *work)
  739. {
  740. if (!READ_ONCE(kfence_enabled))
  741. return;
  742. atomic_set(&kfence_allocation_gate, -kfence_burst);
  743. #ifdef CONFIG_KFENCE_STATIC_KEYS
  744. /* Enable static key, and await allocation to happen. */
  745. static_branch_enable(&kfence_allocation_key);
  746. wait_event_idle(allocation_wait,
  747. atomic_read(&kfence_allocation_gate) > 0 ||
  748. !READ_ONCE(kfence_enabled));
  749. /* Disable static key and reset timer. */
  750. static_branch_disable(&kfence_allocation_key);
  751. #endif
  752. queue_delayed_work(system_dfl_wq, &kfence_timer,
  753. msecs_to_jiffies(kfence_sample_interval));
  754. }
  755. /* === Public interface ===================================================== */
  756. void __init kfence_alloc_pool_and_metadata(void)
  757. {
  758. if (!kfence_sample_interval)
  759. return;
  760. /*
  761. * If KASAN hardware tags are enabled, disable KFENCE, because it
  762. * does not support MTE yet.
  763. */
  764. if (kasan_hw_tags_enabled()) {
  765. pr_info("disabled as KASAN HW tags are enabled\n");
  766. if (__kfence_pool) {
  767. memblock_free(__kfence_pool, KFENCE_POOL_SIZE);
  768. __kfence_pool = NULL;
  769. }
  770. kfence_sample_interval = 0;
  771. return;
  772. }
  773. /*
  774. * If the pool has already been initialized by arch, there is no need to
  775. * re-allocate the memory pool.
  776. */
  777. if (!__kfence_pool)
  778. __kfence_pool = memblock_alloc(KFENCE_POOL_SIZE, PAGE_SIZE);
  779. if (!__kfence_pool) {
  780. pr_err("failed to allocate pool\n");
  781. return;
  782. }
  783. /* The memory allocated by memblock has been zeroed out. */
  784. kfence_metadata_init = memblock_alloc(KFENCE_METADATA_SIZE, PAGE_SIZE);
  785. if (!kfence_metadata_init) {
  786. pr_err("failed to allocate metadata\n");
  787. memblock_free(__kfence_pool, KFENCE_POOL_SIZE);
  788. __kfence_pool = NULL;
  789. }
  790. }
  791. static void kfence_init_enable(void)
  792. {
  793. if (!IS_ENABLED(CONFIG_KFENCE_STATIC_KEYS))
  794. static_branch_enable(&kfence_allocation_key);
  795. if (kfence_deferrable)
  796. INIT_DEFERRABLE_WORK(&kfence_timer, toggle_allocation_gate);
  797. else
  798. INIT_DELAYED_WORK(&kfence_timer, toggle_allocation_gate);
  799. if (kfence_check_on_panic)
  800. atomic_notifier_chain_register(&panic_notifier_list, &kfence_check_canary_notifier);
  801. #ifdef CONFIG_KFENCE_STATIC_KEYS
  802. register_reboot_notifier(&kfence_reboot_notifier);
  803. #endif
  804. WRITE_ONCE(kfence_enabled, true);
  805. queue_delayed_work(system_dfl_wq, &kfence_timer, 0);
  806. pr_info("initialized - using %lu bytes for %d objects at 0x%p-0x%p\n", KFENCE_POOL_SIZE,
  807. CONFIG_KFENCE_NUM_OBJECTS, (void *)__kfence_pool,
  808. (void *)(__kfence_pool + KFENCE_POOL_SIZE));
  809. }
  810. void __init kfence_init(void)
  811. {
  812. stack_hash_seed = get_random_u32();
  813. /* Setting kfence_sample_interval to 0 on boot disables KFENCE. */
  814. if (!kfence_sample_interval)
  815. return;
  816. if (!kfence_init_pool_early()) {
  817. pr_err("%s failed\n", __func__);
  818. return;
  819. }
  820. kfence_init_enable();
  821. }
  822. static int kfence_init_late(void)
  823. {
  824. const unsigned long nr_pages_pool = KFENCE_POOL_SIZE / PAGE_SIZE;
  825. const unsigned long nr_pages_meta = KFENCE_METADATA_SIZE / PAGE_SIZE;
  826. unsigned long addr = (unsigned long)__kfence_pool;
  827. unsigned long free_size = KFENCE_POOL_SIZE;
  828. int err = -ENOMEM;
  829. #ifdef CONFIG_CONTIG_ALLOC
  830. struct page *pages;
  831. pages = alloc_contig_pages(nr_pages_pool, GFP_KERNEL | __GFP_SKIP_KASAN,
  832. first_online_node, NULL);
  833. if (!pages)
  834. return -ENOMEM;
  835. __kfence_pool = page_to_virt(pages);
  836. pages = alloc_contig_pages(nr_pages_meta, GFP_KERNEL | __GFP_SKIP_KASAN,
  837. first_online_node, NULL);
  838. if (pages)
  839. kfence_metadata_init = page_to_virt(pages);
  840. #else
  841. if (nr_pages_pool > MAX_ORDER_NR_PAGES ||
  842. nr_pages_meta > MAX_ORDER_NR_PAGES) {
  843. pr_warn("KFENCE_NUM_OBJECTS too large for buddy allocator\n");
  844. return -EINVAL;
  845. }
  846. __kfence_pool = alloc_pages_exact(KFENCE_POOL_SIZE,
  847. GFP_KERNEL | __GFP_SKIP_KASAN);
  848. if (!__kfence_pool)
  849. return -ENOMEM;
  850. kfence_metadata_init = alloc_pages_exact(KFENCE_METADATA_SIZE,
  851. GFP_KERNEL | __GFP_SKIP_KASAN);
  852. #endif
  853. if (!kfence_metadata_init)
  854. goto free_pool;
  855. memzero_explicit(kfence_metadata_init, KFENCE_METADATA_SIZE);
  856. addr = kfence_init_pool();
  857. if (!addr) {
  858. kfence_init_enable();
  859. kfence_debugfs_init();
  860. return 0;
  861. }
  862. pr_err("%s failed\n", __func__);
  863. free_size = KFENCE_POOL_SIZE - (addr - (unsigned long)__kfence_pool);
  864. err = -EBUSY;
  865. #ifdef CONFIG_CONTIG_ALLOC
  866. free_contig_range(page_to_pfn(virt_to_page((void *)kfence_metadata_init)),
  867. nr_pages_meta);
  868. free_pool:
  869. free_contig_range(page_to_pfn(virt_to_page((void *)addr)),
  870. free_size / PAGE_SIZE);
  871. #else
  872. free_pages_exact((void *)kfence_metadata_init, KFENCE_METADATA_SIZE);
  873. free_pool:
  874. free_pages_exact((void *)addr, free_size);
  875. #endif
  876. kfence_metadata_init = NULL;
  877. __kfence_pool = NULL;
  878. return err;
  879. }
  880. static int kfence_enable_late(void)
  881. {
  882. if (!__kfence_pool)
  883. return kfence_init_late();
  884. WRITE_ONCE(kfence_enabled, true);
  885. queue_delayed_work(system_dfl_wq, &kfence_timer, 0);
  886. pr_info("re-enabled\n");
  887. return 0;
  888. }
  889. void kfence_shutdown_cache(struct kmem_cache *s)
  890. {
  891. unsigned long flags;
  892. struct kfence_metadata *meta;
  893. int i;
  894. /* Pairs with release in kfence_init_pool(). */
  895. if (!smp_load_acquire(&kfence_metadata))
  896. return;
  897. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  898. bool in_use;
  899. meta = &kfence_metadata[i];
  900. /*
  901. * If we observe some inconsistent cache and state pair where we
  902. * should have returned false here, cache destruction is racing
  903. * with either kmem_cache_alloc() or kmem_cache_free(). Taking
  904. * the lock will not help, as different critical section
  905. * serialization will have the same outcome.
  906. */
  907. if (READ_ONCE(meta->cache) != s || !kfence_obj_allocated(meta))
  908. continue;
  909. raw_spin_lock_irqsave(&meta->lock, flags);
  910. in_use = meta->cache == s && kfence_obj_allocated(meta);
  911. raw_spin_unlock_irqrestore(&meta->lock, flags);
  912. if (in_use) {
  913. /*
  914. * This cache still has allocations, and we should not
  915. * release them back into the freelist so they can still
  916. * safely be used and retain the kernel's default
  917. * behaviour of keeping the allocations alive (leak the
  918. * cache); however, they effectively become "zombie
  919. * allocations" as the KFENCE objects are the only ones
  920. * still in use and the owning cache is being destroyed.
  921. *
  922. * We mark them freed, so that any subsequent use shows
  923. * more useful error messages that will include stack
  924. * traces of the user of the object, the original
  925. * allocation, and caller to shutdown_cache().
  926. */
  927. kfence_guarded_free((void *)meta->addr, meta, /*zombie=*/true);
  928. }
  929. }
  930. for (i = 0; i < CONFIG_KFENCE_NUM_OBJECTS; i++) {
  931. meta = &kfence_metadata[i];
  932. /* See above. */
  933. if (READ_ONCE(meta->cache) != s || READ_ONCE(meta->state) != KFENCE_OBJECT_FREED)
  934. continue;
  935. raw_spin_lock_irqsave(&meta->lock, flags);
  936. if (meta->cache == s && meta->state == KFENCE_OBJECT_FREED)
  937. meta->cache = NULL;
  938. raw_spin_unlock_irqrestore(&meta->lock, flags);
  939. }
  940. }
  941. void *__kfence_alloc(struct kmem_cache *s, size_t size, gfp_t flags)
  942. {
  943. unsigned long stack_entries[KFENCE_STACK_DEPTH];
  944. size_t num_stack_entries;
  945. u32 alloc_stack_hash;
  946. int allocation_gate;
  947. /*
  948. * Perform size check before switching kfence_allocation_gate, so that
  949. * we don't disable KFENCE without making an allocation.
  950. */
  951. if (size > PAGE_SIZE) {
  952. atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_INCOMPAT]);
  953. return NULL;
  954. }
  955. /*
  956. * Skip allocations from non-default zones, including DMA. We cannot
  957. * guarantee that pages in the KFENCE pool will have the requested
  958. * properties (e.g. reside in DMAable memory).
  959. */
  960. if ((flags & GFP_ZONEMASK) ||
  961. ((flags & __GFP_THISNODE) && num_online_nodes() > 1) ||
  962. (s->flags & (SLAB_CACHE_DMA | SLAB_CACHE_DMA32))) {
  963. atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_INCOMPAT]);
  964. return NULL;
  965. }
  966. /*
  967. * Skip allocations for this slab, if KFENCE has been disabled for
  968. * this slab.
  969. */
  970. if (s->flags & SLAB_SKIP_KFENCE)
  971. return NULL;
  972. allocation_gate = atomic_inc_return(&kfence_allocation_gate);
  973. if (allocation_gate > 1)
  974. return NULL;
  975. #ifdef CONFIG_KFENCE_STATIC_KEYS
  976. /*
  977. * waitqueue_active() is fully ordered after the update of
  978. * kfence_allocation_gate per atomic_inc_return().
  979. */
  980. if (allocation_gate == 1 && waitqueue_active(&allocation_wait)) {
  981. /*
  982. * Calling wake_up() here may deadlock when allocations happen
  983. * from within timer code. Use an irq_work to defer it.
  984. */
  985. irq_work_queue(&wake_up_kfence_timer_work);
  986. }
  987. #endif
  988. if (!READ_ONCE(kfence_enabled))
  989. return NULL;
  990. num_stack_entries = stack_trace_save(stack_entries, KFENCE_STACK_DEPTH, 0);
  991. /*
  992. * Do expensive check for coverage of allocation in slow-path after
  993. * allocation_gate has already become non-zero, even though it might
  994. * mean not making any allocation within a given sample interval.
  995. *
  996. * This ensures reasonable allocation coverage when the pool is almost
  997. * full, including avoiding long-lived allocations of the same source
  998. * filling up the pool (e.g. pagecache allocations).
  999. */
  1000. alloc_stack_hash = get_alloc_stack_hash(stack_entries, num_stack_entries);
  1001. if (should_skip_covered() && alloc_covered_contains(alloc_stack_hash)) {
  1002. atomic_long_inc(&counters[KFENCE_COUNTER_SKIP_COVERED]);
  1003. return NULL;
  1004. }
  1005. return kfence_guarded_alloc(s, size, flags, stack_entries, num_stack_entries,
  1006. alloc_stack_hash);
  1007. }
  1008. size_t kfence_ksize(const void *addr)
  1009. {
  1010. const struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
  1011. /*
  1012. * Read locklessly -- if there is a race with __kfence_alloc(), this is
  1013. * either a use-after-free or invalid access.
  1014. */
  1015. return meta ? meta->size : 0;
  1016. }
  1017. void *kfence_object_start(const void *addr)
  1018. {
  1019. const struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
  1020. /*
  1021. * Read locklessly -- if there is a race with __kfence_alloc(), this is
  1022. * either a use-after-free or invalid access.
  1023. */
  1024. return meta ? (void *)meta->addr : NULL;
  1025. }
  1026. void __kfence_free(void *addr)
  1027. {
  1028. struct kfence_metadata *meta = addr_to_metadata((unsigned long)addr);
  1029. #ifdef CONFIG_MEMCG
  1030. KFENCE_WARN_ON(meta->obj_exts.objcg);
  1031. #endif
  1032. /*
  1033. * If the objects of the cache are SLAB_TYPESAFE_BY_RCU, defer freeing
  1034. * the object, as the object page may be recycled for other-typed
  1035. * objects once it has been freed. meta->cache may be NULL if the cache
  1036. * was destroyed.
  1037. * Save the stack trace here so that reports show where the user freed
  1038. * the object.
  1039. */
  1040. if (unlikely(meta->cache && (meta->cache->flags & SLAB_TYPESAFE_BY_RCU))) {
  1041. unsigned long flags;
  1042. raw_spin_lock_irqsave(&meta->lock, flags);
  1043. metadata_update_state(meta, KFENCE_OBJECT_RCU_FREEING, NULL, 0);
  1044. raw_spin_unlock_irqrestore(&meta->lock, flags);
  1045. call_rcu(&meta->rcu_head, rcu_guarded_free);
  1046. } else {
  1047. kfence_guarded_free(addr, meta, false);
  1048. }
  1049. }
  1050. bool kfence_handle_page_fault(unsigned long addr, bool is_write, struct pt_regs *regs)
  1051. {
  1052. const int page_index = (addr - (unsigned long)__kfence_pool) / PAGE_SIZE;
  1053. struct kfence_metadata *to_report = NULL;
  1054. unsigned long unprotected_page = 0;
  1055. enum kfence_error_type error_type;
  1056. unsigned long flags;
  1057. if (!is_kfence_address((void *)addr))
  1058. return false;
  1059. if (!READ_ONCE(kfence_enabled)) /* If disabled at runtime ... */
  1060. return kfence_unprotect(addr); /* ... unprotect and proceed. */
  1061. atomic_long_inc(&counters[KFENCE_COUNTER_BUGS]);
  1062. if (page_index % 2) {
  1063. /* This is a redzone, report a buffer overflow. */
  1064. struct kfence_metadata *meta;
  1065. int distance = 0;
  1066. meta = addr_to_metadata(addr - PAGE_SIZE);
  1067. if (meta && kfence_obj_allocated(meta)) {
  1068. to_report = meta;
  1069. /* Data race ok; distance calculation approximate. */
  1070. distance = addr - data_race(meta->addr + meta->size);
  1071. }
  1072. meta = addr_to_metadata(addr + PAGE_SIZE);
  1073. if (meta && kfence_obj_allocated(meta)) {
  1074. /* Data race ok; distance calculation approximate. */
  1075. if (!to_report || distance > data_race(meta->addr) - addr)
  1076. to_report = meta;
  1077. }
  1078. if (!to_report)
  1079. goto out;
  1080. error_type = KFENCE_ERROR_OOB;
  1081. unprotected_page = addr;
  1082. /*
  1083. * If the object was freed before we took the look we can still
  1084. * report this as an OOB -- the report will simply show the
  1085. * stacktrace of the free as well.
  1086. */
  1087. } else {
  1088. to_report = addr_to_metadata(addr);
  1089. if (!to_report)
  1090. goto out;
  1091. error_type = KFENCE_ERROR_UAF;
  1092. /*
  1093. * We may race with __kfence_alloc(), and it is possible that a
  1094. * freed object may be reallocated. We simply report this as a
  1095. * use-after-free, with the stack trace showing the place where
  1096. * the object was re-allocated.
  1097. */
  1098. }
  1099. out:
  1100. if (to_report) {
  1101. raw_spin_lock_irqsave(&to_report->lock, flags);
  1102. to_report->unprotected_page = unprotected_page;
  1103. kfence_report_error(addr, is_write, regs, to_report, error_type);
  1104. raw_spin_unlock_irqrestore(&to_report->lock, flags);
  1105. } else {
  1106. /* This may be a UAF or OOB access, but we can't be sure. */
  1107. kfence_report_error(addr, is_write, regs, NULL, KFENCE_ERROR_INVALID);
  1108. }
  1109. return kfence_unprotect(addr); /* Unprotect and let access proceed. */
  1110. }