slab_common.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Slab allocator functions that are independent of the allocator strategy
  4. *
  5. * (C) 2012 Christoph Lameter <cl@linux.com>
  6. */
  7. #include <linux/slab.h>
  8. #include <linux/mm.h>
  9. #include <linux/poison.h>
  10. #include <linux/interrupt.h>
  11. #include <linux/memory.h>
  12. #include <linux/cache.h>
  13. #include <linux/compiler.h>
  14. #include <linux/kfence.h>
  15. #include <linux/module.h>
  16. #include <linux/cpu.h>
  17. #include <linux/uaccess.h>
  18. #include <linux/seq_file.h>
  19. #include <linux/proc_fs.h>
  20. #include <linux/debugfs.h>
  21. #include <linux/kasan.h>
  22. #include <asm/cacheflush.h>
  23. #include <asm/tlbflush.h>
  24. #include <asm/page.h>
  25. #include <linux/memcontrol.h>
  26. #define CREATE_TRACE_POINTS
  27. #include <trace/events/kmem.h>
  28. #undef CREATE_TRACE_POINTS
  29. #include <trace/hooks/mm.h>
  30. #include "internal.h"
  31. #include "slab.h"
  32. enum slab_state slab_state;
  33. LIST_HEAD(slab_caches);
  34. DEFINE_MUTEX(slab_mutex);
  35. struct kmem_cache *kmem_cache;
  36. #ifdef CONFIG_HARDENED_USERCOPY
  37. bool usercopy_fallback __ro_after_init =
  38. IS_ENABLED(CONFIG_HARDENED_USERCOPY_FALLBACK);
  39. module_param(usercopy_fallback, bool, 0400);
  40. MODULE_PARM_DESC(usercopy_fallback,
  41. "WARN instead of reject usercopy whitelist violations");
  42. #endif
  43. static LIST_HEAD(slab_caches_to_rcu_destroy);
  44. static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work);
  45. static DECLARE_WORK(slab_caches_to_rcu_destroy_work,
  46. slab_caches_to_rcu_destroy_workfn);
  47. /*
  48. * Set of flags that will prevent slab merging
  49. */
  50. #define SLAB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
  51. SLAB_TRACE | SLAB_TYPESAFE_BY_RCU | SLAB_NOLEAKTRACE | \
  52. SLAB_FAILSLAB | kasan_never_merge())
  53. #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
  54. SLAB_CACHE_DMA32 | SLAB_ACCOUNT)
  55. /*
  56. * Merge control. If this is set then no merging of slab caches will occur.
  57. */
  58. static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT);
  59. static int __init setup_slab_nomerge(char *str)
  60. {
  61. slab_nomerge = true;
  62. return 1;
  63. }
  64. #ifdef CONFIG_SLUB
  65. __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
  66. #endif
  67. __setup("slab_nomerge", setup_slab_nomerge);
  68. /*
  69. * Determine the size of a slab object
  70. */
  71. unsigned int kmem_cache_size(struct kmem_cache *s)
  72. {
  73. return s->object_size;
  74. }
  75. EXPORT_SYMBOL(kmem_cache_size);
  76. #ifdef CONFIG_DEBUG_VM
  77. static int kmem_cache_sanity_check(const char *name, unsigned int size)
  78. {
  79. if (!name || in_interrupt() || size > KMALLOC_MAX_SIZE) {
  80. pr_err("kmem_cache_create(%s) integrity check failed\n", name);
  81. return -EINVAL;
  82. }
  83. WARN_ON(strchr(name, ' ')); /* It confuses parsers */
  84. return 0;
  85. }
  86. #else
  87. static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
  88. {
  89. return 0;
  90. }
  91. #endif
  92. void __kmem_cache_free_bulk(struct kmem_cache *s, size_t nr, void **p)
  93. {
  94. size_t i;
  95. for (i = 0; i < nr; i++) {
  96. if (s)
  97. kmem_cache_free(s, p[i]);
  98. else
  99. kfree(p[i]);
  100. }
  101. }
  102. int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t nr,
  103. void **p)
  104. {
  105. size_t i;
  106. for (i = 0; i < nr; i++) {
  107. void *x = p[i] = kmem_cache_alloc(s, flags);
  108. if (!x) {
  109. __kmem_cache_free_bulk(s, i, p);
  110. return 0;
  111. }
  112. }
  113. return i;
  114. }
  115. /*
  116. * Figure out what the alignment of the objects will be given a set of
  117. * flags, a user specified alignment and the size of the objects.
  118. */
  119. static unsigned int calculate_alignment(slab_flags_t flags,
  120. unsigned int align, unsigned int size)
  121. {
  122. /*
  123. * If the user wants hardware cache aligned objects then follow that
  124. * suggestion if the object is sufficiently large.
  125. *
  126. * The hardware cache alignment cannot override the specified
  127. * alignment though. If that is greater then use it.
  128. */
  129. if (flags & SLAB_HWCACHE_ALIGN) {
  130. unsigned int ralign;
  131. ralign = cache_line_size();
  132. while (size <= ralign / 2)
  133. ralign /= 2;
  134. align = max(align, ralign);
  135. }
  136. if (align < ARCH_SLAB_MINALIGN)
  137. align = ARCH_SLAB_MINALIGN;
  138. return ALIGN(align, sizeof(void *));
  139. }
  140. /*
  141. * Find a mergeable slab cache
  142. */
  143. int slab_unmergeable(struct kmem_cache *s)
  144. {
  145. if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
  146. return 1;
  147. if (s->ctor)
  148. return 1;
  149. if (s->usersize)
  150. return 1;
  151. /*
  152. * We may have set a slab to be unmergeable during bootstrap.
  153. */
  154. if (s->refcount < 0)
  155. return 1;
  156. return 0;
  157. }
  158. struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
  159. slab_flags_t flags, const char *name, void (*ctor)(void *))
  160. {
  161. struct kmem_cache *s;
  162. if (slab_nomerge)
  163. return NULL;
  164. if (ctor)
  165. return NULL;
  166. size = ALIGN(size, sizeof(void *));
  167. align = calculate_alignment(flags, align, size);
  168. size = ALIGN(size, align);
  169. flags = kmem_cache_flags(size, flags, name);
  170. if (flags & SLAB_NEVER_MERGE)
  171. return NULL;
  172. list_for_each_entry_reverse(s, &slab_caches, list) {
  173. if (slab_unmergeable(s))
  174. continue;
  175. if (size > s->size)
  176. continue;
  177. if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
  178. continue;
  179. /*
  180. * Check if alignment is compatible.
  181. * Courtesy of Adrian Drzewiecki
  182. */
  183. if ((s->size & ~(align - 1)) != s->size)
  184. continue;
  185. if (s->size - size >= sizeof(void *))
  186. continue;
  187. if (IS_ENABLED(CONFIG_SLAB) && align &&
  188. (align > s->align || s->align % align))
  189. continue;
  190. return s;
  191. }
  192. return NULL;
  193. }
  194. static struct kmem_cache *create_cache(const char *name,
  195. unsigned int object_size, unsigned int align,
  196. slab_flags_t flags, unsigned int useroffset,
  197. unsigned int usersize, void (*ctor)(void *),
  198. struct kmem_cache *root_cache)
  199. {
  200. struct kmem_cache *s;
  201. int err;
  202. if (WARN_ON(useroffset + usersize > object_size))
  203. useroffset = usersize = 0;
  204. err = -ENOMEM;
  205. s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
  206. if (!s)
  207. goto out;
  208. s->name = name;
  209. s->size = s->object_size = object_size;
  210. s->align = align;
  211. s->ctor = ctor;
  212. s->useroffset = useroffset;
  213. s->usersize = usersize;
  214. err = __kmem_cache_create(s, flags);
  215. if (err)
  216. goto out_free_cache;
  217. s->refcount = 1;
  218. list_add(&s->list, &slab_caches);
  219. out:
  220. if (err)
  221. return ERR_PTR(err);
  222. return s;
  223. out_free_cache:
  224. kmem_cache_free(kmem_cache, s);
  225. goto out;
  226. }
  227. /**
  228. * kmem_cache_create_usercopy - Create a cache with a region suitable
  229. * for copying to userspace
  230. * @name: A string which is used in /proc/slabinfo to identify this cache.
  231. * @size: The size of objects to be created in this cache.
  232. * @align: The required alignment for the objects.
  233. * @flags: SLAB flags
  234. * @useroffset: Usercopy region offset
  235. * @usersize: Usercopy region size
  236. * @ctor: A constructor for the objects.
  237. *
  238. * Cannot be called within a interrupt, but can be interrupted.
  239. * The @ctor is run when new pages are allocated by the cache.
  240. *
  241. * The flags are
  242. *
  243. * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
  244. * to catch references to uninitialised memory.
  245. *
  246. * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
  247. * for buffer overruns.
  248. *
  249. * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
  250. * cacheline. This can be beneficial if you're counting cycles as closely
  251. * as davem.
  252. *
  253. * Return: a pointer to the cache on success, NULL on failure.
  254. */
  255. struct kmem_cache *
  256. kmem_cache_create_usercopy(const char *name,
  257. unsigned int size, unsigned int align,
  258. slab_flags_t flags,
  259. unsigned int useroffset, unsigned int usersize,
  260. void (*ctor)(void *))
  261. {
  262. struct kmem_cache *s = NULL;
  263. const char *cache_name;
  264. int err;
  265. get_online_cpus();
  266. get_online_mems();
  267. #ifdef CONFIG_SLUB_DEBUG
  268. /*
  269. * If no slub_debug was enabled globally, the static key is not yet
  270. * enabled by setup_slub_debug(). Enable it if the cache is being
  271. * created with any of the debugging flags passed explicitly.
  272. */
  273. if (flags & SLAB_DEBUG_FLAGS)
  274. static_branch_enable(&slub_debug_enabled);
  275. #endif
  276. mutex_lock(&slab_mutex);
  277. err = kmem_cache_sanity_check(name, size);
  278. if (err) {
  279. goto out_unlock;
  280. }
  281. /* Refuse requests with allocator specific flags */
  282. if (flags & ~SLAB_FLAGS_PERMITTED) {
  283. err = -EINVAL;
  284. goto out_unlock;
  285. }
  286. /*
  287. * Some allocators will constraint the set of valid flags to a subset
  288. * of all flags. We expect them to define CACHE_CREATE_MASK in this
  289. * case, and we'll just provide them with a sanitized version of the
  290. * passed flags.
  291. */
  292. flags &= CACHE_CREATE_MASK;
  293. /* Fail closed on bad usersize of useroffset values. */
  294. if (WARN_ON(!usersize && useroffset) ||
  295. WARN_ON(size < usersize || size - usersize < useroffset))
  296. usersize = useroffset = 0;
  297. if (!usersize)
  298. s = __kmem_cache_alias(name, size, align, flags, ctor);
  299. if (s)
  300. goto out_unlock;
  301. cache_name = kstrdup_const(name, GFP_KERNEL);
  302. if (!cache_name) {
  303. err = -ENOMEM;
  304. goto out_unlock;
  305. }
  306. s = create_cache(cache_name, size,
  307. calculate_alignment(flags, align, size),
  308. flags, useroffset, usersize, ctor, NULL);
  309. if (IS_ERR(s)) {
  310. err = PTR_ERR(s);
  311. kfree_const(cache_name);
  312. }
  313. out_unlock:
  314. mutex_unlock(&slab_mutex);
  315. put_online_mems();
  316. put_online_cpus();
  317. if (err) {
  318. if (flags & SLAB_PANIC)
  319. panic("kmem_cache_create: Failed to create slab '%s'. Error %d\n",
  320. name, err);
  321. else {
  322. pr_warn("kmem_cache_create(%s) failed with error %d\n",
  323. name, err);
  324. dump_stack();
  325. }
  326. return NULL;
  327. }
  328. return s;
  329. }
  330. EXPORT_SYMBOL(kmem_cache_create_usercopy);
  331. /**
  332. * kmem_cache_create - Create a cache.
  333. * @name: A string which is used in /proc/slabinfo to identify this cache.
  334. * @size: The size of objects to be created in this cache.
  335. * @align: The required alignment for the objects.
  336. * @flags: SLAB flags
  337. * @ctor: A constructor for the objects.
  338. *
  339. * Cannot be called within a interrupt, but can be interrupted.
  340. * The @ctor is run when new pages are allocated by the cache.
  341. *
  342. * The flags are
  343. *
  344. * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
  345. * to catch references to uninitialised memory.
  346. *
  347. * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
  348. * for buffer overruns.
  349. *
  350. * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
  351. * cacheline. This can be beneficial if you're counting cycles as closely
  352. * as davem.
  353. *
  354. * Return: a pointer to the cache on success, NULL on failure.
  355. */
  356. struct kmem_cache *
  357. kmem_cache_create(const char *name, unsigned int size, unsigned int align,
  358. slab_flags_t flags, void (*ctor)(void *))
  359. {
  360. return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
  361. ctor);
  362. }
  363. EXPORT_SYMBOL(kmem_cache_create);
  364. static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
  365. {
  366. LIST_HEAD(to_destroy);
  367. struct kmem_cache *s, *s2;
  368. /*
  369. * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
  370. * @slab_caches_to_rcu_destroy list. The slab pages are freed
  371. * through RCU and the associated kmem_cache are dereferenced
  372. * while freeing the pages, so the kmem_caches should be freed only
  373. * after the pending RCU operations are finished. As rcu_barrier()
  374. * is a pretty slow operation, we batch all pending destructions
  375. * asynchronously.
  376. */
  377. mutex_lock(&slab_mutex);
  378. list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
  379. mutex_unlock(&slab_mutex);
  380. if (list_empty(&to_destroy))
  381. return;
  382. rcu_barrier();
  383. list_for_each_entry_safe(s, s2, &to_destroy, list) {
  384. debugfs_slab_release(s);
  385. kfence_shutdown_cache(s);
  386. #ifdef SLAB_SUPPORTS_SYSFS
  387. sysfs_slab_release(s);
  388. #else
  389. slab_kmem_cache_release(s);
  390. #endif
  391. }
  392. }
  393. static int shutdown_cache(struct kmem_cache *s)
  394. {
  395. /* free asan quarantined objects */
  396. kasan_cache_shutdown(s);
  397. if (__kmem_cache_shutdown(s) != 0)
  398. return -EBUSY;
  399. list_del(&s->list);
  400. if (s->flags & SLAB_TYPESAFE_BY_RCU) {
  401. #ifdef SLAB_SUPPORTS_SYSFS
  402. sysfs_slab_unlink(s);
  403. #endif
  404. list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
  405. schedule_work(&slab_caches_to_rcu_destroy_work);
  406. } else {
  407. kfence_shutdown_cache(s);
  408. debugfs_slab_release(s);
  409. #ifdef SLAB_SUPPORTS_SYSFS
  410. sysfs_slab_unlink(s);
  411. sysfs_slab_release(s);
  412. #else
  413. slab_kmem_cache_release(s);
  414. #endif
  415. }
  416. return 0;
  417. }
  418. void slab_kmem_cache_release(struct kmem_cache *s)
  419. {
  420. __kmem_cache_release(s);
  421. kfree_const(s->name);
  422. kmem_cache_free(kmem_cache, s);
  423. }
  424. void kmem_cache_destroy(struct kmem_cache *s)
  425. {
  426. int err;
  427. if (unlikely(!s))
  428. return;
  429. get_online_cpus();
  430. get_online_mems();
  431. mutex_lock(&slab_mutex);
  432. s->refcount--;
  433. if (s->refcount)
  434. goto out_unlock;
  435. err = shutdown_cache(s);
  436. if (err) {
  437. pr_err("kmem_cache_destroy %s: Slab cache still has objects\n",
  438. s->name);
  439. dump_stack();
  440. }
  441. out_unlock:
  442. mutex_unlock(&slab_mutex);
  443. put_online_mems();
  444. put_online_cpus();
  445. }
  446. EXPORT_SYMBOL(kmem_cache_destroy);
  447. /**
  448. * kmem_cache_shrink - Shrink a cache.
  449. * @cachep: The cache to shrink.
  450. *
  451. * Releases as many slabs as possible for a cache.
  452. * To help debugging, a zero exit status indicates all slabs were released.
  453. *
  454. * Return: %0 if all slabs were released, non-zero otherwise
  455. */
  456. int kmem_cache_shrink(struct kmem_cache *cachep)
  457. {
  458. int ret;
  459. get_online_cpus();
  460. get_online_mems();
  461. kasan_cache_shrink(cachep);
  462. ret = __kmem_cache_shrink(cachep);
  463. put_online_mems();
  464. put_online_cpus();
  465. return ret;
  466. }
  467. EXPORT_SYMBOL(kmem_cache_shrink);
  468. bool slab_is_available(void)
  469. {
  470. return slab_state >= UP;
  471. }
  472. #ifndef CONFIG_SLOB
  473. /* Create a cache during boot when no slab services are available yet */
  474. void __init create_boot_cache(struct kmem_cache *s, const char *name,
  475. unsigned int size, slab_flags_t flags,
  476. unsigned int useroffset, unsigned int usersize)
  477. {
  478. int err;
  479. unsigned int align = ARCH_KMALLOC_MINALIGN;
  480. s->name = name;
  481. s->size = s->object_size = size;
  482. /*
  483. * For power of two sizes, guarantee natural alignment for kmalloc
  484. * caches, regardless of SL*B debugging options.
  485. */
  486. if (is_power_of_2(size))
  487. align = max(align, size);
  488. s->align = calculate_alignment(flags, align, size);
  489. s->useroffset = useroffset;
  490. s->usersize = usersize;
  491. err = __kmem_cache_create(s, flags);
  492. if (err)
  493. panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
  494. name, size, err);
  495. s->refcount = -1; /* Exempt from merging for now */
  496. }
  497. struct kmem_cache *__init create_kmalloc_cache(const char *name,
  498. unsigned int size, slab_flags_t flags,
  499. unsigned int useroffset, unsigned int usersize)
  500. {
  501. struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
  502. if (!s)
  503. panic("Out of memory when creating slab %s\n", name);
  504. create_boot_cache(s, name, size, flags, useroffset, usersize);
  505. kasan_cache_create_kmalloc(s);
  506. list_add(&s->list, &slab_caches);
  507. s->refcount = 1;
  508. return s;
  509. }
  510. struct kmem_cache *
  511. kmalloc_caches[NR_KMALLOC_TYPES][KMALLOC_SHIFT_HIGH + 1] __ro_after_init =
  512. { /* initialization for https://bugs.llvm.org/show_bug.cgi?id=42570 */ };
  513. EXPORT_SYMBOL(kmalloc_caches);
  514. /*
  515. * Conversion table for small slabs sizes / 8 to the index in the
  516. * kmalloc array. This is necessary for slabs < 192 since we have non power
  517. * of two cache sizes there. The size of larger slabs can be determined using
  518. * fls.
  519. */
  520. static u8 size_index[24] __ro_after_init = {
  521. 3, /* 8 */
  522. 4, /* 16 */
  523. 5, /* 24 */
  524. 5, /* 32 */
  525. 6, /* 40 */
  526. 6, /* 48 */
  527. 6, /* 56 */
  528. 6, /* 64 */
  529. 1, /* 72 */
  530. 1, /* 80 */
  531. 1, /* 88 */
  532. 1, /* 96 */
  533. 7, /* 104 */
  534. 7, /* 112 */
  535. 7, /* 120 */
  536. 7, /* 128 */
  537. 2, /* 136 */
  538. 2, /* 144 */
  539. 2, /* 152 */
  540. 2, /* 160 */
  541. 2, /* 168 */
  542. 2, /* 176 */
  543. 2, /* 184 */
  544. 2 /* 192 */
  545. };
  546. static inline unsigned int size_index_elem(unsigned int bytes)
  547. {
  548. return (bytes - 1) / 8;
  549. }
  550. /*
  551. * Find the kmem_cache structure that serves a given size of
  552. * allocation
  553. */
  554. struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
  555. {
  556. unsigned int index;
  557. struct kmem_cache *s = NULL;
  558. if (size <= 192) {
  559. if (!size)
  560. return ZERO_SIZE_PTR;
  561. index = size_index[size_index_elem(size)];
  562. } else {
  563. if (WARN_ON_ONCE(size > KMALLOC_MAX_CACHE_SIZE))
  564. return NULL;
  565. index = fls(size - 1);
  566. }
  567. trace_android_vh_kmalloc_slab(index, flags, &s);
  568. if (s)
  569. return s;
  570. return kmalloc_caches[kmalloc_type(flags)][index];
  571. }
  572. #ifdef CONFIG_ZONE_DMA
  573. #define INIT_KMALLOC_INFO(__size, __short_size) \
  574. { \
  575. .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
  576. .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
  577. .name[KMALLOC_DMA] = "dma-kmalloc-" #__short_size, \
  578. .size = __size, \
  579. }
  580. #else
  581. #define INIT_KMALLOC_INFO(__size, __short_size) \
  582. { \
  583. .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
  584. .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
  585. .size = __size, \
  586. }
  587. #endif
  588. /*
  589. * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
  590. * kmalloc_index() supports up to 2^26=64MB, so the final entry of the table is
  591. * kmalloc-67108864.
  592. */
  593. const struct kmalloc_info_struct kmalloc_info[] __initconst = {
  594. INIT_KMALLOC_INFO(0, 0),
  595. INIT_KMALLOC_INFO(96, 96),
  596. INIT_KMALLOC_INFO(192, 192),
  597. INIT_KMALLOC_INFO(8, 8),
  598. INIT_KMALLOC_INFO(16, 16),
  599. INIT_KMALLOC_INFO(32, 32),
  600. INIT_KMALLOC_INFO(64, 64),
  601. INIT_KMALLOC_INFO(128, 128),
  602. INIT_KMALLOC_INFO(256, 256),
  603. INIT_KMALLOC_INFO(512, 512),
  604. INIT_KMALLOC_INFO(1024, 1k),
  605. INIT_KMALLOC_INFO(2048, 2k),
  606. INIT_KMALLOC_INFO(4096, 4k),
  607. INIT_KMALLOC_INFO(8192, 8k),
  608. INIT_KMALLOC_INFO(16384, 16k),
  609. INIT_KMALLOC_INFO(32768, 32k),
  610. INIT_KMALLOC_INFO(65536, 64k),
  611. INIT_KMALLOC_INFO(131072, 128k),
  612. INIT_KMALLOC_INFO(262144, 256k),
  613. INIT_KMALLOC_INFO(524288, 512k),
  614. INIT_KMALLOC_INFO(1048576, 1M),
  615. INIT_KMALLOC_INFO(2097152, 2M),
  616. INIT_KMALLOC_INFO(4194304, 4M),
  617. INIT_KMALLOC_INFO(8388608, 8M),
  618. INIT_KMALLOC_INFO(16777216, 16M),
  619. INIT_KMALLOC_INFO(33554432, 32M),
  620. INIT_KMALLOC_INFO(67108864, 64M)
  621. };
  622. /*
  623. * Patch up the size_index table if we have strange large alignment
  624. * requirements for the kmalloc array. This is only the case for
  625. * MIPS it seems. The standard arches will not generate any code here.
  626. *
  627. * Largest permitted alignment is 256 bytes due to the way we
  628. * handle the index determination for the smaller caches.
  629. *
  630. * Make sure that nothing crazy happens if someone starts tinkering
  631. * around with ARCH_KMALLOC_MINALIGN
  632. */
  633. void __init setup_kmalloc_cache_index_table(void)
  634. {
  635. unsigned int i;
  636. BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
  637. (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
  638. for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
  639. unsigned int elem = size_index_elem(i);
  640. if (elem >= ARRAY_SIZE(size_index))
  641. break;
  642. size_index[elem] = KMALLOC_SHIFT_LOW;
  643. }
  644. if (KMALLOC_MIN_SIZE >= 64) {
  645. /*
  646. * The 96 byte size cache is not used if the alignment
  647. * is 64 byte.
  648. */
  649. for (i = 64 + 8; i <= 96; i += 8)
  650. size_index[size_index_elem(i)] = 7;
  651. }
  652. if (KMALLOC_MIN_SIZE >= 128) {
  653. /*
  654. * The 192 byte sized cache is not used if the alignment
  655. * is 128 byte. Redirect kmalloc to use the 256 byte cache
  656. * instead.
  657. */
  658. for (i = 128 + 8; i <= 192; i += 8)
  659. size_index[size_index_elem(i)] = 8;
  660. }
  661. }
  662. static void __init
  663. new_kmalloc_cache(int idx, enum kmalloc_cache_type type, slab_flags_t flags)
  664. {
  665. if (type == KMALLOC_RECLAIM)
  666. flags |= SLAB_RECLAIM_ACCOUNT;
  667. kmalloc_caches[type][idx] = create_kmalloc_cache(
  668. kmalloc_info[idx].name[type],
  669. kmalloc_info[idx].size, flags, 0,
  670. kmalloc_info[idx].size);
  671. }
  672. /*
  673. * Create the kmalloc array. Some of the regular kmalloc arrays
  674. * may already have been created because they were needed to
  675. * enable allocations for slab creation.
  676. */
  677. void __init create_kmalloc_caches(slab_flags_t flags)
  678. {
  679. int i;
  680. enum kmalloc_cache_type type;
  681. for (type = KMALLOC_NORMAL; type <= KMALLOC_RECLAIM; type++) {
  682. for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
  683. if (!kmalloc_caches[type][i])
  684. new_kmalloc_cache(i, type, flags);
  685. /*
  686. * Caches that are not of the two-to-the-power-of size.
  687. * These have to be created immediately after the
  688. * earlier power of two caches
  689. */
  690. if (KMALLOC_MIN_SIZE <= 32 && i == 6 &&
  691. !kmalloc_caches[type][1])
  692. new_kmalloc_cache(1, type, flags);
  693. if (KMALLOC_MIN_SIZE <= 64 && i == 7 &&
  694. !kmalloc_caches[type][2])
  695. new_kmalloc_cache(2, type, flags);
  696. }
  697. }
  698. /* Kmalloc array is now usable */
  699. slab_state = UP;
  700. #ifdef CONFIG_ZONE_DMA
  701. for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
  702. struct kmem_cache *s = kmalloc_caches[KMALLOC_NORMAL][i];
  703. if (s) {
  704. kmalloc_caches[KMALLOC_DMA][i] = create_kmalloc_cache(
  705. kmalloc_info[i].name[KMALLOC_DMA],
  706. kmalloc_info[i].size,
  707. SLAB_CACHE_DMA | flags, 0,
  708. kmalloc_info[i].size);
  709. }
  710. }
  711. #endif
  712. }
  713. #endif /* !CONFIG_SLOB */
  714. gfp_t kmalloc_fix_flags(gfp_t flags)
  715. {
  716. gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
  717. flags &= ~GFP_SLAB_BUG_MASK;
  718. pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
  719. invalid_mask, &invalid_mask, flags, &flags);
  720. dump_stack();
  721. return flags;
  722. }
  723. /*
  724. * To avoid unnecessary overhead, we pass through large allocation requests
  725. * directly to the page allocator. We use __GFP_COMP, because we will need to
  726. * know the allocation order to free the pages properly in kfree.
  727. */
  728. void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
  729. {
  730. void *ret = NULL;
  731. struct page *page;
  732. if (unlikely(flags & GFP_SLAB_BUG_MASK))
  733. flags = kmalloc_fix_flags(flags);
  734. flags |= __GFP_COMP;
  735. page = alloc_pages(flags, order);
  736. if (likely(page)) {
  737. ret = page_address(page);
  738. mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
  739. PAGE_SIZE << order);
  740. }
  741. ret = kasan_kmalloc_large(ret, size, flags);
  742. /* As ret might get tagged, call kmemleak hook after KASAN. */
  743. kmemleak_alloc(ret, size, 1, flags);
  744. return ret;
  745. }
  746. EXPORT_SYMBOL(kmalloc_order);
  747. #ifdef CONFIG_TRACING
  748. void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
  749. {
  750. void *ret = kmalloc_order(size, flags, order);
  751. trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
  752. return ret;
  753. }
  754. EXPORT_SYMBOL(kmalloc_order_trace);
  755. #endif
  756. #ifdef CONFIG_SLAB_FREELIST_RANDOM
  757. /* Randomize a generic freelist */
  758. static void freelist_randomize(struct rnd_state *state, unsigned int *list,
  759. unsigned int count)
  760. {
  761. unsigned int rand;
  762. unsigned int i;
  763. for (i = 0; i < count; i++)
  764. list[i] = i;
  765. /* Fisher-Yates shuffle */
  766. for (i = count - 1; i > 0; i--) {
  767. rand = prandom_u32_state(state);
  768. rand %= (i + 1);
  769. swap(list[i], list[rand]);
  770. }
  771. }
  772. /* Create a random sequence per cache */
  773. int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
  774. gfp_t gfp)
  775. {
  776. struct rnd_state state;
  777. if (count < 2 || cachep->random_seq)
  778. return 0;
  779. cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
  780. if (!cachep->random_seq)
  781. return -ENOMEM;
  782. /* Get best entropy at this stage of boot */
  783. prandom_seed_state(&state, get_random_long());
  784. freelist_randomize(&state, cachep->random_seq, count);
  785. return 0;
  786. }
  787. /* Destroy the per-cache random freelist sequence */
  788. void cache_random_seq_destroy(struct kmem_cache *cachep)
  789. {
  790. kfree(cachep->random_seq);
  791. cachep->random_seq = NULL;
  792. }
  793. #endif /* CONFIG_SLAB_FREELIST_RANDOM */
  794. #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
  795. #ifdef CONFIG_SLAB
  796. #define SLABINFO_RIGHTS (0600)
  797. #else
  798. #define SLABINFO_RIGHTS (0400)
  799. #endif
  800. static void print_slabinfo_header(struct seq_file *m)
  801. {
  802. /*
  803. * Output format version, so at least we can change it
  804. * without _too_ many complaints.
  805. */
  806. #ifdef CONFIG_DEBUG_SLAB
  807. seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
  808. #else
  809. seq_puts(m, "slabinfo - version: 2.1\n");
  810. #endif
  811. seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
  812. seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
  813. seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
  814. #ifdef CONFIG_DEBUG_SLAB
  815. seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
  816. seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
  817. #endif
  818. seq_putc(m, '\n');
  819. }
  820. void *slab_start(struct seq_file *m, loff_t *pos)
  821. {
  822. mutex_lock(&slab_mutex);
  823. return seq_list_start(&slab_caches, *pos);
  824. }
  825. void *slab_next(struct seq_file *m, void *p, loff_t *pos)
  826. {
  827. return seq_list_next(p, &slab_caches, pos);
  828. }
  829. void slab_stop(struct seq_file *m, void *p)
  830. {
  831. mutex_unlock(&slab_mutex);
  832. }
  833. static void cache_show(struct kmem_cache *s, struct seq_file *m)
  834. {
  835. struct slabinfo sinfo;
  836. memset(&sinfo, 0, sizeof(sinfo));
  837. get_slabinfo(s, &sinfo);
  838. seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
  839. s->name, sinfo.active_objs, sinfo.num_objs, s->size,
  840. sinfo.objects_per_slab, (1 << sinfo.cache_order));
  841. seq_printf(m, " : tunables %4u %4u %4u",
  842. sinfo.limit, sinfo.batchcount, sinfo.shared);
  843. seq_printf(m, " : slabdata %6lu %6lu %6lu",
  844. sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
  845. slabinfo_show_stats(m, s);
  846. seq_putc(m, '\n');
  847. }
  848. static int slab_show(struct seq_file *m, void *p)
  849. {
  850. struct kmem_cache *s = list_entry(p, struct kmem_cache, list);
  851. if (p == slab_caches.next)
  852. print_slabinfo_header(m);
  853. cache_show(s, m);
  854. return 0;
  855. }
  856. void dump_unreclaimable_slab(void)
  857. {
  858. struct kmem_cache *s, *s2;
  859. struct slabinfo sinfo;
  860. /*
  861. * Here acquiring slab_mutex is risky since we don't prefer to get
  862. * sleep in oom path. But, without mutex hold, it may introduce a
  863. * risk of crash.
  864. * Use mutex_trylock to protect the list traverse, dump nothing
  865. * without acquiring the mutex.
  866. */
  867. if (!mutex_trylock(&slab_mutex)) {
  868. pr_warn("excessive unreclaimable slab but cannot dump stats\n");
  869. return;
  870. }
  871. pr_info("Unreclaimable slab info:\n");
  872. pr_info("Name Used Total\n");
  873. list_for_each_entry_safe(s, s2, &slab_caches, list) {
  874. if (s->flags & SLAB_RECLAIM_ACCOUNT)
  875. continue;
  876. get_slabinfo(s, &sinfo);
  877. if (sinfo.num_objs > 0)
  878. pr_info("%-17s %10luKB %10luKB\n", s->name,
  879. (sinfo.active_objs * s->size) / 1024,
  880. (sinfo.num_objs * s->size) / 1024);
  881. }
  882. mutex_unlock(&slab_mutex);
  883. }
  884. #if defined(CONFIG_MEMCG_KMEM)
  885. int memcg_slab_show(struct seq_file *m, void *p)
  886. {
  887. /*
  888. * Deprecated.
  889. * Please, take a look at tools/cgroup/slabinfo.py .
  890. */
  891. return 0;
  892. }
  893. #endif
  894. /*
  895. * slabinfo_op - iterator that generates /proc/slabinfo
  896. *
  897. * Output layout:
  898. * cache-name
  899. * num-active-objs
  900. * total-objs
  901. * object size
  902. * num-active-slabs
  903. * total-slabs
  904. * num-pages-per-slab
  905. * + further values on SMP and with statistics enabled
  906. */
  907. static const struct seq_operations slabinfo_op = {
  908. .start = slab_start,
  909. .next = slab_next,
  910. .stop = slab_stop,
  911. .show = slab_show,
  912. };
  913. static int slabinfo_open(struct inode *inode, struct file *file)
  914. {
  915. return seq_open(file, &slabinfo_op);
  916. }
  917. static const struct proc_ops slabinfo_proc_ops = {
  918. .proc_flags = PROC_ENTRY_PERMANENT,
  919. .proc_open = slabinfo_open,
  920. .proc_read = seq_read,
  921. .proc_write = slabinfo_write,
  922. .proc_lseek = seq_lseek,
  923. .proc_release = seq_release,
  924. };
  925. static int __init slab_proc_init(void)
  926. {
  927. proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops);
  928. return 0;
  929. }
  930. module_init(slab_proc_init);
  931. #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
  932. static __always_inline void *__do_krealloc(const void *p, size_t new_size,
  933. gfp_t flags)
  934. {
  935. void *ret;
  936. size_t ks;
  937. /* Don't use instrumented ksize to allow precise KASAN poisoning. */
  938. if (likely(!ZERO_OR_NULL_PTR(p))) {
  939. if (!kasan_check_byte(p))
  940. return NULL;
  941. ks = kfence_ksize(p) ?: __ksize(p);
  942. } else
  943. ks = 0;
  944. /* If the object still fits, repoison it precisely. */
  945. if (ks >= new_size) {
  946. p = kasan_krealloc((void *)p, new_size, flags);
  947. return (void *)p;
  948. }
  949. ret = kmalloc_track_caller(new_size, flags);
  950. if (ret && p) {
  951. /* Disable KASAN checks as the object's redzone is accessed. */
  952. kasan_disable_current();
  953. memcpy(ret, kasan_reset_tag(p), ks);
  954. kasan_enable_current();
  955. }
  956. return ret;
  957. }
  958. /**
  959. * krealloc - reallocate memory. The contents will remain unchanged.
  960. * @p: object to reallocate memory for.
  961. * @new_size: how many bytes of memory are required.
  962. * @flags: the type of memory to allocate.
  963. *
  964. * The contents of the object pointed to are preserved up to the
  965. * lesser of the new and old sizes. If @p is %NULL, krealloc()
  966. * behaves exactly like kmalloc(). If @new_size is 0 and @p is not a
  967. * %NULL pointer, the object pointed to is freed.
  968. *
  969. * Return: pointer to the allocated memory or %NULL in case of error
  970. */
  971. void *krealloc(const void *p, size_t new_size, gfp_t flags)
  972. {
  973. void *ret;
  974. if (unlikely(!new_size)) {
  975. kfree(p);
  976. return ZERO_SIZE_PTR;
  977. }
  978. ret = __do_krealloc(p, new_size, flags);
  979. if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
  980. kfree(p);
  981. return ret;
  982. }
  983. EXPORT_SYMBOL(krealloc);
  984. /**
  985. * kfree_sensitive - Clear sensitive information in memory before freeing
  986. * @p: object to free memory of
  987. *
  988. * The memory of the object @p points to is zeroed before freed.
  989. * If @p is %NULL, kfree_sensitive() does nothing.
  990. *
  991. * Note: this function zeroes the whole allocated buffer which can be a good
  992. * deal bigger than the requested buffer size passed to kmalloc(). So be
  993. * careful when using this function in performance sensitive code.
  994. */
  995. void kfree_sensitive(const void *p)
  996. {
  997. size_t ks;
  998. void *mem = (void *)p;
  999. ks = ksize(mem);
  1000. if (ks)
  1001. memzero_explicit(mem, ks);
  1002. kfree(mem);
  1003. }
  1004. EXPORT_SYMBOL(kfree_sensitive);
  1005. /**
  1006. * ksize - get the actual amount of memory allocated for a given object
  1007. * @objp: Pointer to the object
  1008. *
  1009. * kmalloc may internally round up allocations and return more memory
  1010. * than requested. ksize() can be used to determine the actual amount of
  1011. * memory allocated. The caller may use this additional memory, even though
  1012. * a smaller amount of memory was initially specified with the kmalloc call.
  1013. * The caller must guarantee that objp points to a valid object previously
  1014. * allocated with either kmalloc() or kmem_cache_alloc(). The object
  1015. * must not be freed during the duration of the call.
  1016. *
  1017. * Return: size of the actual memory used by @objp in bytes
  1018. */
  1019. size_t ksize(const void *objp)
  1020. {
  1021. size_t size;
  1022. /*
  1023. * We need to first check that the pointer to the object is valid, and
  1024. * only then unpoison the memory. The report printed from ksize() is
  1025. * more useful, then when it's printed later when the behaviour could
  1026. * be undefined due to a potential use-after-free or double-free.
  1027. *
  1028. * We use kasan_check_byte(), which is supported for the hardware
  1029. * tag-based KASAN mode, unlike kasan_check_read/write().
  1030. *
  1031. * If the pointed to memory is invalid, we return 0 to avoid users of
  1032. * ksize() writing to and potentially corrupting the memory region.
  1033. *
  1034. * We want to perform the check before __ksize(), to avoid potentially
  1035. * crashing in __ksize() due to accessing invalid metadata.
  1036. */
  1037. if (unlikely(ZERO_OR_NULL_PTR(objp)) || !kasan_check_byte(objp))
  1038. return 0;
  1039. size = kfence_ksize(objp) ?: __ksize(objp);
  1040. /*
  1041. * We assume that ksize callers could use whole allocated area,
  1042. * so we need to unpoison this area.
  1043. */
  1044. kasan_unpoison_range(objp, size);
  1045. return size;
  1046. }
  1047. EXPORT_SYMBOL(ksize);
  1048. /* Tracepoints definitions. */
  1049. EXPORT_TRACEPOINT_SYMBOL(kmalloc);
  1050. EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
  1051. EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
  1052. EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
  1053. EXPORT_TRACEPOINT_SYMBOL(kfree);
  1054. EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
  1055. int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
  1056. {
  1057. if (__should_failslab(s, gfpflags))
  1058. return -ENOMEM;
  1059. return 0;
  1060. }
  1061. ALLOW_ERROR_INJECTION(should_failslab, ERRNO);