slab.c 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * linux/mm/slab.c
  4. * Written by Mark Hemment, 1996/97.
  5. * ([email protected])
  6. *
  7. * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
  8. *
  9. * Major cleanup, different bufctl logic, per-cpu arrays
  10. * (c) 2000 Manfred Spraul
  11. *
  12. * Cleanup, make the head arrays unconditional, preparation for NUMA
  13. * (c) 2002 Manfred Spraul
  14. *
  15. * An implementation of the Slab Allocator as described in outline in;
  16. * UNIX Internals: The New Frontiers by Uresh Vahalia
  17. * Pub: Prentice Hall ISBN 0-13-101908-2
  18. * or with a little more detail in;
  19. * The Slab Allocator: An Object-Caching Kernel Memory Allocator
  20. * Jeff Bonwick (Sun Microsystems).
  21. * Presented at: USENIX Summer 1994 Technical Conference
  22. *
  23. * The memory is organized in caches, one cache for each object type.
  24. * (e.g. inode_cache, dentry_cache, buffer_head, vm_area_struct)
  25. * Each cache consists out of many slabs (they are small (usually one
  26. * page long) and always contiguous), and each slab contains multiple
  27. * initialized objects.
  28. *
  29. * This means, that your constructor is used only for newly allocated
  30. * slabs and you must pass objects with the same initializations to
  31. * kmem_cache_free.
  32. *
  33. * Each cache can only support one memory type (GFP_DMA, GFP_HIGHMEM,
  34. * normal). If you need a special memory type, then must create a new
  35. * cache for that memory type.
  36. *
  37. * In order to reduce fragmentation, the slabs are sorted in 3 groups:
  38. * full slabs with 0 free objects
  39. * partial slabs
  40. * empty slabs with no allocated objects
  41. *
  42. * If partial slabs exist, then new allocations come from these slabs,
  43. * otherwise from empty slabs or new slabs are allocated.
  44. *
  45. * kmem_cache_destroy() CAN CRASH if you try to allocate from the cache
  46. * during kmem_cache_destroy(). The caller must prevent concurrent allocs.
  47. *
  48. * Each cache has a short per-cpu head array, most allocs
  49. * and frees go into that array, and if that array overflows, then 1/2
  50. * of the entries in the array are given back into the global cache.
  51. * The head array is strictly LIFO and should improve the cache hit rates.
  52. * On SMP, it additionally reduces the spinlock operations.
  53. *
  54. * The c_cpuarray may not be read with enabled local interrupts -
  55. * it's changed with a smp_call_function().
  56. *
  57. * SMP synchronization:
  58. * constructors and destructors are called without any locking.
  59. * Several members in struct kmem_cache and struct slab never change, they
  60. * are accessed without any locking.
  61. * The per-cpu arrays are never accessed from the wrong cpu, no locking,
  62. * and local interrupts are disabled so slab code is preempt-safe.
  63. * The non-constant members are protected with a per-cache irq spinlock.
  64. *
  65. * Many thanks to Mark Hemment, who wrote another per-cpu slab patch
  66. * in 2000 - many ideas in the current implementation are derived from
  67. * his patch.
  68. *
  69. * Further notes from the original documentation:
  70. *
  71. * 11 April '97. Started multi-threading - markhe
  72. * The global cache-chain is protected by the mutex 'slab_mutex'.
  73. * The sem is only needed when accessing/extending the cache-chain, which
  74. * can never happen inside an interrupt (kmem_cache_create(),
  75. * kmem_cache_shrink() and kmem_cache_reap()).
  76. *
  77. * At present, each engine can be growing a cache. This should be blocked.
  78. *
  79. * 15 March 2005. NUMA slab allocator.
  80. * Shai Fultheim <[email protected]>.
  81. * Shobhit Dayal <[email protected]>
  82. * Alok N Kataria <[email protected]>
  83. * Christoph Lameter <[email protected]>
  84. *
  85. * Modified the slab allocator to be node aware on NUMA systems.
  86. * Each node has its own list of partial, free and full slabs.
  87. * All object allocations for a node occur from node specific slab lists.
  88. */
  89. #include <linux/slab.h>
  90. #include <linux/mm.h>
  91. #include <linux/poison.h>
  92. #include <linux/swap.h>
  93. #include <linux/cache.h>
  94. #include <linux/interrupt.h>
  95. #include <linux/init.h>
  96. #include <linux/compiler.h>
  97. #include <linux/cpuset.h>
  98. #include <linux/proc_fs.h>
  99. #include <linux/seq_file.h>
  100. #include <linux/notifier.h>
  101. #include <linux/kallsyms.h>
  102. #include <linux/kfence.h>
  103. #include <linux/cpu.h>
  104. #include <linux/sysctl.h>
  105. #include <linux/module.h>
  106. #include <linux/rcupdate.h>
  107. #include <linux/string.h>
  108. #include <linux/uaccess.h>
  109. #include <linux/nodemask.h>
  110. #include <linux/kmemleak.h>
  111. #include <linux/mempolicy.h>
  112. #include <linux/mutex.h>
  113. #include <linux/fault-inject.h>
  114. #include <linux/rtmutex.h>
  115. #include <linux/reciprocal_div.h>
  116. #include <linux/debugobjects.h>
  117. #include <linux/memory.h>
  118. #include <linux/prefetch.h>
  119. #include <linux/sched/task_stack.h>
  120. #include <net/sock.h>
  121. #include <asm/cacheflush.h>
  122. #include <asm/tlbflush.h>
  123. #include <asm/page.h>
  124. #include <trace/events/kmem.h>
  125. #include "internal.h"
  126. #include "slab.h"
  127. /*
  128. * DEBUG - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
  129. * 0 for faster, smaller code (especially in the critical paths).
  130. *
  131. * STATS - 1 to collect stats for /proc/slabinfo.
  132. * 0 for faster, smaller code (especially in the critical paths).
  133. *
  134. * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
  135. */
  136. #ifdef CONFIG_DEBUG_SLAB
  137. #define DEBUG 1
  138. #define STATS 1
  139. #define FORCED_DEBUG 1
  140. #else
  141. #define DEBUG 0
  142. #define STATS 0
  143. #define FORCED_DEBUG 0
  144. #endif
  145. /* Shouldn't this be in a header file somewhere? */
  146. #define BYTES_PER_WORD sizeof(void *)
  147. #define REDZONE_ALIGN max(BYTES_PER_WORD, __alignof__(unsigned long long))
  148. #ifndef ARCH_KMALLOC_FLAGS
  149. #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
  150. #endif
  151. #define FREELIST_BYTE_INDEX (((PAGE_SIZE >> BITS_PER_BYTE) \
  152. <= SLAB_OBJ_MIN_SIZE) ? 1 : 0)
  153. #if FREELIST_BYTE_INDEX
  154. typedef unsigned char freelist_idx_t;
  155. #else
  156. typedef unsigned short freelist_idx_t;
  157. #endif
  158. #define SLAB_OBJ_MAX_NUM ((1 << sizeof(freelist_idx_t) * BITS_PER_BYTE) - 1)
  159. /*
  160. * struct array_cache
  161. *
  162. * Purpose:
  163. * - LIFO ordering, to hand out cache-warm objects from _alloc
  164. * - reduce the number of linked list operations
  165. * - reduce spinlock operations
  166. *
  167. * The limit is stored in the per-cpu structure to reduce the data cache
  168. * footprint.
  169. *
  170. */
  171. struct array_cache {
  172. unsigned int avail;
  173. unsigned int limit;
  174. unsigned int batchcount;
  175. unsigned int touched;
  176. void *entry[]; /*
  177. * Must have this definition in here for the proper
  178. * alignment of array_cache. Also simplifies accessing
  179. * the entries.
  180. */
  181. };
  182. struct alien_cache {
  183. spinlock_t lock;
  184. struct array_cache ac;
  185. };
  186. /*
  187. * Need this for bootstrapping a per node allocator.
  188. */
  189. #define NUM_INIT_LISTS (2 * MAX_NUMNODES)
  190. static struct kmem_cache_node __initdata init_kmem_cache_node[NUM_INIT_LISTS];
  191. #define CACHE_CACHE 0
  192. #define SIZE_NODE (MAX_NUMNODES)
  193. static int drain_freelist(struct kmem_cache *cache,
  194. struct kmem_cache_node *n, int tofree);
  195. static void free_block(struct kmem_cache *cachep, void **objpp, int len,
  196. int node, struct list_head *list);
  197. static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list);
  198. static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
  199. static void cache_reap(struct work_struct *unused);
  200. static inline void fixup_objfreelist_debug(struct kmem_cache *cachep,
  201. void **list);
  202. static inline void fixup_slab_list(struct kmem_cache *cachep,
  203. struct kmem_cache_node *n, struct slab *slab,
  204. void **list);
  205. static int slab_early_init = 1;
  206. #define INDEX_NODE kmalloc_index(sizeof(struct kmem_cache_node))
  207. static void kmem_cache_node_init(struct kmem_cache_node *parent)
  208. {
  209. INIT_LIST_HEAD(&parent->slabs_full);
  210. INIT_LIST_HEAD(&parent->slabs_partial);
  211. INIT_LIST_HEAD(&parent->slabs_free);
  212. parent->total_slabs = 0;
  213. parent->free_slabs = 0;
  214. parent->shared = NULL;
  215. parent->alien = NULL;
  216. parent->colour_next = 0;
  217. spin_lock_init(&parent->list_lock);
  218. parent->free_objects = 0;
  219. parent->free_touched = 0;
  220. }
  221. #define MAKE_LIST(cachep, listp, slab, nodeid) \
  222. do { \
  223. INIT_LIST_HEAD(listp); \
  224. list_splice(&get_node(cachep, nodeid)->slab, listp); \
  225. } while (0)
  226. #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
  227. do { \
  228. MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
  229. MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
  230. MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
  231. } while (0)
  232. #define CFLGS_OBJFREELIST_SLAB ((slab_flags_t __force)0x40000000U)
  233. #define CFLGS_OFF_SLAB ((slab_flags_t __force)0x80000000U)
  234. #define OBJFREELIST_SLAB(x) ((x)->flags & CFLGS_OBJFREELIST_SLAB)
  235. #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
  236. #define BATCHREFILL_LIMIT 16
  237. /*
  238. * Optimization question: fewer reaps means less probability for unnecessary
  239. * cpucache drain/refill cycles.
  240. *
  241. * OTOH the cpuarrays can contain lots of objects,
  242. * which could lock up otherwise freeable slabs.
  243. */
  244. #define REAPTIMEOUT_AC (2*HZ)
  245. #define REAPTIMEOUT_NODE (4*HZ)
  246. #if STATS
  247. #define STATS_INC_ACTIVE(x) ((x)->num_active++)
  248. #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
  249. #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
  250. #define STATS_INC_GROWN(x) ((x)->grown++)
  251. #define STATS_ADD_REAPED(x, y) ((x)->reaped += (y))
  252. #define STATS_SET_HIGH(x) \
  253. do { \
  254. if ((x)->num_active > (x)->high_mark) \
  255. (x)->high_mark = (x)->num_active; \
  256. } while (0)
  257. #define STATS_INC_ERR(x) ((x)->errors++)
  258. #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
  259. #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
  260. #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
  261. #define STATS_SET_FREEABLE(x, i) \
  262. do { \
  263. if ((x)->max_freeable < i) \
  264. (x)->max_freeable = i; \
  265. } while (0)
  266. #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
  267. #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
  268. #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
  269. #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
  270. #else
  271. #define STATS_INC_ACTIVE(x) do { } while (0)
  272. #define STATS_DEC_ACTIVE(x) do { } while (0)
  273. #define STATS_INC_ALLOCED(x) do { } while (0)
  274. #define STATS_INC_GROWN(x) do { } while (0)
  275. #define STATS_ADD_REAPED(x, y) do { (void)(y); } while (0)
  276. #define STATS_SET_HIGH(x) do { } while (0)
  277. #define STATS_INC_ERR(x) do { } while (0)
  278. #define STATS_INC_NODEALLOCS(x) do { } while (0)
  279. #define STATS_INC_NODEFREES(x) do { } while (0)
  280. #define STATS_INC_ACOVERFLOW(x) do { } while (0)
  281. #define STATS_SET_FREEABLE(x, i) do { } while (0)
  282. #define STATS_INC_ALLOCHIT(x) do { } while (0)
  283. #define STATS_INC_ALLOCMISS(x) do { } while (0)
  284. #define STATS_INC_FREEHIT(x) do { } while (0)
  285. #define STATS_INC_FREEMISS(x) do { } while (0)
  286. #endif
  287. #if DEBUG
  288. /*
  289. * memory layout of objects:
  290. * 0 : objp
  291. * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
  292. * the end of an object is aligned with the end of the real
  293. * allocation. Catches writes behind the end of the allocation.
  294. * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
  295. * redzone word.
  296. * cachep->obj_offset: The real object.
  297. * cachep->size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
  298. * cachep->size - 1* BYTES_PER_WORD: last caller address
  299. * [BYTES_PER_WORD long]
  300. */
  301. static int obj_offset(struct kmem_cache *cachep)
  302. {
  303. return cachep->obj_offset;
  304. }
  305. static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
  306. {
  307. BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
  308. return (unsigned long long *) (objp + obj_offset(cachep) -
  309. sizeof(unsigned long long));
  310. }
  311. static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
  312. {
  313. BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
  314. if (cachep->flags & SLAB_STORE_USER)
  315. return (unsigned long long *)(objp + cachep->size -
  316. sizeof(unsigned long long) -
  317. REDZONE_ALIGN);
  318. return (unsigned long long *) (objp + cachep->size -
  319. sizeof(unsigned long long));
  320. }
  321. static void **dbg_userword(struct kmem_cache *cachep, void *objp)
  322. {
  323. BUG_ON(!(cachep->flags & SLAB_STORE_USER));
  324. return (void **)(objp + cachep->size - BYTES_PER_WORD);
  325. }
  326. #else
  327. #define obj_offset(x) 0
  328. #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
  329. #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
  330. #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
  331. #endif
  332. /*
  333. * Do not go above this order unless 0 objects fit into the slab or
  334. * overridden on the command line.
  335. */
  336. #define SLAB_MAX_ORDER_HI 1
  337. #define SLAB_MAX_ORDER_LO 0
  338. static int slab_max_order = SLAB_MAX_ORDER_LO;
  339. static bool slab_max_order_set __initdata;
  340. static inline void *index_to_obj(struct kmem_cache *cache,
  341. const struct slab *slab, unsigned int idx)
  342. {
  343. return slab->s_mem + cache->size * idx;
  344. }
  345. #define BOOT_CPUCACHE_ENTRIES 1
  346. /* internal cache of cache description objs */
  347. static struct kmem_cache kmem_cache_boot = {
  348. .batchcount = 1,
  349. .limit = BOOT_CPUCACHE_ENTRIES,
  350. .shared = 1,
  351. .size = sizeof(struct kmem_cache),
  352. .name = "kmem_cache",
  353. };
  354. static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
  355. static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
  356. {
  357. return this_cpu_ptr(cachep->cpu_cache);
  358. }
  359. /*
  360. * Calculate the number of objects and left-over bytes for a given buffer size.
  361. */
  362. static unsigned int cache_estimate(unsigned long gfporder, size_t buffer_size,
  363. slab_flags_t flags, size_t *left_over)
  364. {
  365. unsigned int num;
  366. size_t slab_size = PAGE_SIZE << gfporder;
  367. /*
  368. * The slab management structure can be either off the slab or
  369. * on it. For the latter case, the memory allocated for a
  370. * slab is used for:
  371. *
  372. * - @buffer_size bytes for each object
  373. * - One freelist_idx_t for each object
  374. *
  375. * We don't need to consider alignment of freelist because
  376. * freelist will be at the end of slab page. The objects will be
  377. * at the correct alignment.
  378. *
  379. * If the slab management structure is off the slab, then the
  380. * alignment will already be calculated into the size. Because
  381. * the slabs are all pages aligned, the objects will be at the
  382. * correct alignment when allocated.
  383. */
  384. if (flags & (CFLGS_OBJFREELIST_SLAB | CFLGS_OFF_SLAB)) {
  385. num = slab_size / buffer_size;
  386. *left_over = slab_size % buffer_size;
  387. } else {
  388. num = slab_size / (buffer_size + sizeof(freelist_idx_t));
  389. *left_over = slab_size %
  390. (buffer_size + sizeof(freelist_idx_t));
  391. }
  392. return num;
  393. }
  394. #if DEBUG
  395. #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
  396. static void __slab_error(const char *function, struct kmem_cache *cachep,
  397. char *msg)
  398. {
  399. pr_err("slab error in %s(): cache `%s': %s\n",
  400. function, cachep->name, msg);
  401. dump_stack();
  402. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  403. }
  404. #endif
  405. /*
  406. * By default on NUMA we use alien caches to stage the freeing of
  407. * objects allocated from other nodes. This causes massive memory
  408. * inefficiencies when using fake NUMA setup to split memory into a
  409. * large number of small nodes, so it can be disabled on the command
  410. * line
  411. */
  412. static int use_alien_caches __read_mostly = 1;
  413. static int __init noaliencache_setup(char *s)
  414. {
  415. use_alien_caches = 0;
  416. return 1;
  417. }
  418. __setup("noaliencache", noaliencache_setup);
  419. static int __init slab_max_order_setup(char *str)
  420. {
  421. get_option(&str, &slab_max_order);
  422. slab_max_order = slab_max_order < 0 ? 0 :
  423. min(slab_max_order, MAX_ORDER - 1);
  424. slab_max_order_set = true;
  425. return 1;
  426. }
  427. __setup("slab_max_order=", slab_max_order_setup);
  428. #ifdef CONFIG_NUMA
  429. /*
  430. * Special reaping functions for NUMA systems called from cache_reap().
  431. * These take care of doing round robin flushing of alien caches (containing
  432. * objects freed on different nodes from which they were allocated) and the
  433. * flushing of remote pcps by calling drain_node_pages.
  434. */
  435. static DEFINE_PER_CPU(unsigned long, slab_reap_node);
  436. static void init_reap_node(int cpu)
  437. {
  438. per_cpu(slab_reap_node, cpu) = next_node_in(cpu_to_mem(cpu),
  439. node_online_map);
  440. }
  441. static void next_reap_node(void)
  442. {
  443. int node = __this_cpu_read(slab_reap_node);
  444. node = next_node_in(node, node_online_map);
  445. __this_cpu_write(slab_reap_node, node);
  446. }
  447. #else
  448. #define init_reap_node(cpu) do { } while (0)
  449. #define next_reap_node(void) do { } while (0)
  450. #endif
  451. /*
  452. * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
  453. * via the workqueue/eventd.
  454. * Add the CPU number into the expiration time to minimize the possibility of
  455. * the CPUs getting into lockstep and contending for the global cache chain
  456. * lock.
  457. */
  458. static void start_cpu_timer(int cpu)
  459. {
  460. struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
  461. if (reap_work->work.func == NULL) {
  462. init_reap_node(cpu);
  463. INIT_DEFERRABLE_WORK(reap_work, cache_reap);
  464. schedule_delayed_work_on(cpu, reap_work,
  465. __round_jiffies_relative(HZ, cpu));
  466. }
  467. }
  468. static void init_arraycache(struct array_cache *ac, int limit, int batch)
  469. {
  470. if (ac) {
  471. ac->avail = 0;
  472. ac->limit = limit;
  473. ac->batchcount = batch;
  474. ac->touched = 0;
  475. }
  476. }
  477. static struct array_cache *alloc_arraycache(int node, int entries,
  478. int batchcount, gfp_t gfp)
  479. {
  480. size_t memsize = sizeof(void *) * entries + sizeof(struct array_cache);
  481. struct array_cache *ac = NULL;
  482. ac = kmalloc_node(memsize, gfp, node);
  483. /*
  484. * The array_cache structures contain pointers to free object.
  485. * However, when such objects are allocated or transferred to another
  486. * cache the pointers are not cleared and they could be counted as
  487. * valid references during a kmemleak scan. Therefore, kmemleak must
  488. * not scan such objects.
  489. */
  490. kmemleak_no_scan(ac);
  491. init_arraycache(ac, entries, batchcount);
  492. return ac;
  493. }
  494. static noinline void cache_free_pfmemalloc(struct kmem_cache *cachep,
  495. struct slab *slab, void *objp)
  496. {
  497. struct kmem_cache_node *n;
  498. int slab_node;
  499. LIST_HEAD(list);
  500. slab_node = slab_nid(slab);
  501. n = get_node(cachep, slab_node);
  502. spin_lock(&n->list_lock);
  503. free_block(cachep, &objp, 1, slab_node, &list);
  504. spin_unlock(&n->list_lock);
  505. slabs_destroy(cachep, &list);
  506. }
  507. /*
  508. * Transfer objects in one arraycache to another.
  509. * Locking must be handled by the caller.
  510. *
  511. * Return the number of entries transferred.
  512. */
  513. static int transfer_objects(struct array_cache *to,
  514. struct array_cache *from, unsigned int max)
  515. {
  516. /* Figure out how many entries to transfer */
  517. int nr = min3(from->avail, max, to->limit - to->avail);
  518. if (!nr)
  519. return 0;
  520. memcpy(to->entry + to->avail, from->entry + from->avail - nr,
  521. sizeof(void *) *nr);
  522. from->avail -= nr;
  523. to->avail += nr;
  524. return nr;
  525. }
  526. /* &alien->lock must be held by alien callers. */
  527. static __always_inline void __free_one(struct array_cache *ac, void *objp)
  528. {
  529. /* Avoid trivial double-free. */
  530. if (IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) &&
  531. WARN_ON_ONCE(ac->avail > 0 && ac->entry[ac->avail - 1] == objp))
  532. return;
  533. ac->entry[ac->avail++] = objp;
  534. }
  535. #ifndef CONFIG_NUMA
  536. #define drain_alien_cache(cachep, alien) do { } while (0)
  537. #define reap_alien(cachep, n) do { } while (0)
  538. static inline struct alien_cache **alloc_alien_cache(int node,
  539. int limit, gfp_t gfp)
  540. {
  541. return NULL;
  542. }
  543. static inline void free_alien_cache(struct alien_cache **ac_ptr)
  544. {
  545. }
  546. static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
  547. {
  548. return 0;
  549. }
  550. static inline gfp_t gfp_exact_node(gfp_t flags)
  551. {
  552. return flags & ~__GFP_NOFAIL;
  553. }
  554. #else /* CONFIG_NUMA */
  555. static struct alien_cache *__alloc_alien_cache(int node, int entries,
  556. int batch, gfp_t gfp)
  557. {
  558. size_t memsize = sizeof(void *) * entries + sizeof(struct alien_cache);
  559. struct alien_cache *alc = NULL;
  560. alc = kmalloc_node(memsize, gfp, node);
  561. if (alc) {
  562. kmemleak_no_scan(alc);
  563. init_arraycache(&alc->ac, entries, batch);
  564. spin_lock_init(&alc->lock);
  565. }
  566. return alc;
  567. }
  568. static struct alien_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
  569. {
  570. struct alien_cache **alc_ptr;
  571. int i;
  572. if (limit > 1)
  573. limit = 12;
  574. alc_ptr = kcalloc_node(nr_node_ids, sizeof(void *), gfp, node);
  575. if (!alc_ptr)
  576. return NULL;
  577. for_each_node(i) {
  578. if (i == node || !node_online(i))
  579. continue;
  580. alc_ptr[i] = __alloc_alien_cache(node, limit, 0xbaadf00d, gfp);
  581. if (!alc_ptr[i]) {
  582. for (i--; i >= 0; i--)
  583. kfree(alc_ptr[i]);
  584. kfree(alc_ptr);
  585. return NULL;
  586. }
  587. }
  588. return alc_ptr;
  589. }
  590. static void free_alien_cache(struct alien_cache **alc_ptr)
  591. {
  592. int i;
  593. if (!alc_ptr)
  594. return;
  595. for_each_node(i)
  596. kfree(alc_ptr[i]);
  597. kfree(alc_ptr);
  598. }
  599. static void __drain_alien_cache(struct kmem_cache *cachep,
  600. struct array_cache *ac, int node,
  601. struct list_head *list)
  602. {
  603. struct kmem_cache_node *n = get_node(cachep, node);
  604. if (ac->avail) {
  605. spin_lock(&n->list_lock);
  606. /*
  607. * Stuff objects into the remote nodes shared array first.
  608. * That way we could avoid the overhead of putting the objects
  609. * into the free lists and getting them back later.
  610. */
  611. if (n->shared)
  612. transfer_objects(n->shared, ac, ac->limit);
  613. free_block(cachep, ac->entry, ac->avail, node, list);
  614. ac->avail = 0;
  615. spin_unlock(&n->list_lock);
  616. }
  617. }
  618. /*
  619. * Called from cache_reap() to regularly drain alien caches round robin.
  620. */
  621. static void reap_alien(struct kmem_cache *cachep, struct kmem_cache_node *n)
  622. {
  623. int node = __this_cpu_read(slab_reap_node);
  624. if (n->alien) {
  625. struct alien_cache *alc = n->alien[node];
  626. struct array_cache *ac;
  627. if (alc) {
  628. ac = &alc->ac;
  629. if (ac->avail && spin_trylock_irq(&alc->lock)) {
  630. LIST_HEAD(list);
  631. __drain_alien_cache(cachep, ac, node, &list);
  632. spin_unlock_irq(&alc->lock);
  633. slabs_destroy(cachep, &list);
  634. }
  635. }
  636. }
  637. }
  638. static void drain_alien_cache(struct kmem_cache *cachep,
  639. struct alien_cache **alien)
  640. {
  641. int i = 0;
  642. struct alien_cache *alc;
  643. struct array_cache *ac;
  644. unsigned long flags;
  645. for_each_online_node(i) {
  646. alc = alien[i];
  647. if (alc) {
  648. LIST_HEAD(list);
  649. ac = &alc->ac;
  650. spin_lock_irqsave(&alc->lock, flags);
  651. __drain_alien_cache(cachep, ac, i, &list);
  652. spin_unlock_irqrestore(&alc->lock, flags);
  653. slabs_destroy(cachep, &list);
  654. }
  655. }
  656. }
  657. static int __cache_free_alien(struct kmem_cache *cachep, void *objp,
  658. int node, int slab_node)
  659. {
  660. struct kmem_cache_node *n;
  661. struct alien_cache *alien = NULL;
  662. struct array_cache *ac;
  663. LIST_HEAD(list);
  664. n = get_node(cachep, node);
  665. STATS_INC_NODEFREES(cachep);
  666. if (n->alien && n->alien[slab_node]) {
  667. alien = n->alien[slab_node];
  668. ac = &alien->ac;
  669. spin_lock(&alien->lock);
  670. if (unlikely(ac->avail == ac->limit)) {
  671. STATS_INC_ACOVERFLOW(cachep);
  672. __drain_alien_cache(cachep, ac, slab_node, &list);
  673. }
  674. __free_one(ac, objp);
  675. spin_unlock(&alien->lock);
  676. slabs_destroy(cachep, &list);
  677. } else {
  678. n = get_node(cachep, slab_node);
  679. spin_lock(&n->list_lock);
  680. free_block(cachep, &objp, 1, slab_node, &list);
  681. spin_unlock(&n->list_lock);
  682. slabs_destroy(cachep, &list);
  683. }
  684. return 1;
  685. }
  686. static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
  687. {
  688. int slab_node = slab_nid(virt_to_slab(objp));
  689. int node = numa_mem_id();
  690. /*
  691. * Make sure we are not freeing an object from another node to the array
  692. * cache on this cpu.
  693. */
  694. if (likely(node == slab_node))
  695. return 0;
  696. return __cache_free_alien(cachep, objp, node, slab_node);
  697. }
  698. /*
  699. * Construct gfp mask to allocate from a specific node but do not reclaim or
  700. * warn about failures.
  701. */
  702. static inline gfp_t gfp_exact_node(gfp_t flags)
  703. {
  704. return (flags | __GFP_THISNODE | __GFP_NOWARN) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
  705. }
  706. #endif
  707. static int init_cache_node(struct kmem_cache *cachep, int node, gfp_t gfp)
  708. {
  709. struct kmem_cache_node *n;
  710. /*
  711. * Set up the kmem_cache_node for cpu before we can
  712. * begin anything. Make sure some other cpu on this
  713. * node has not already allocated this
  714. */
  715. n = get_node(cachep, node);
  716. if (n) {
  717. spin_lock_irq(&n->list_lock);
  718. n->free_limit = (1 + nr_cpus_node(node)) * cachep->batchcount +
  719. cachep->num;
  720. spin_unlock_irq(&n->list_lock);
  721. return 0;
  722. }
  723. n = kmalloc_node(sizeof(struct kmem_cache_node), gfp, node);
  724. if (!n)
  725. return -ENOMEM;
  726. kmem_cache_node_init(n);
  727. n->next_reap = jiffies + REAPTIMEOUT_NODE +
  728. ((unsigned long)cachep) % REAPTIMEOUT_NODE;
  729. n->free_limit =
  730. (1 + nr_cpus_node(node)) * cachep->batchcount + cachep->num;
  731. /*
  732. * The kmem_cache_nodes don't come and go as CPUs
  733. * come and go. slab_mutex provides sufficient
  734. * protection here.
  735. */
  736. cachep->node[node] = n;
  737. return 0;
  738. }
  739. #if defined(CONFIG_NUMA) || defined(CONFIG_SMP)
  740. /*
  741. * Allocates and initializes node for a node on each slab cache, used for
  742. * either memory or cpu hotplug. If memory is being hot-added, the kmem_cache_node
  743. * will be allocated off-node since memory is not yet online for the new node.
  744. * When hotplugging memory or a cpu, existing nodes are not replaced if
  745. * already in use.
  746. *
  747. * Must hold slab_mutex.
  748. */
  749. static int init_cache_node_node(int node)
  750. {
  751. int ret;
  752. struct kmem_cache *cachep;
  753. list_for_each_entry(cachep, &slab_caches, list) {
  754. ret = init_cache_node(cachep, node, GFP_KERNEL);
  755. if (ret)
  756. return ret;
  757. }
  758. return 0;
  759. }
  760. #endif
  761. static int setup_kmem_cache_node(struct kmem_cache *cachep,
  762. int node, gfp_t gfp, bool force_change)
  763. {
  764. int ret = -ENOMEM;
  765. struct kmem_cache_node *n;
  766. struct array_cache *old_shared = NULL;
  767. struct array_cache *new_shared = NULL;
  768. struct alien_cache **new_alien = NULL;
  769. LIST_HEAD(list);
  770. if (use_alien_caches) {
  771. new_alien = alloc_alien_cache(node, cachep->limit, gfp);
  772. if (!new_alien)
  773. goto fail;
  774. }
  775. if (cachep->shared) {
  776. new_shared = alloc_arraycache(node,
  777. cachep->shared * cachep->batchcount, 0xbaadf00d, gfp);
  778. if (!new_shared)
  779. goto fail;
  780. }
  781. ret = init_cache_node(cachep, node, gfp);
  782. if (ret)
  783. goto fail;
  784. n = get_node(cachep, node);
  785. spin_lock_irq(&n->list_lock);
  786. if (n->shared && force_change) {
  787. free_block(cachep, n->shared->entry,
  788. n->shared->avail, node, &list);
  789. n->shared->avail = 0;
  790. }
  791. if (!n->shared || force_change) {
  792. old_shared = n->shared;
  793. n->shared = new_shared;
  794. new_shared = NULL;
  795. }
  796. if (!n->alien) {
  797. n->alien = new_alien;
  798. new_alien = NULL;
  799. }
  800. spin_unlock_irq(&n->list_lock);
  801. slabs_destroy(cachep, &list);
  802. /*
  803. * To protect lockless access to n->shared during irq disabled context.
  804. * If n->shared isn't NULL in irq disabled context, accessing to it is
  805. * guaranteed to be valid until irq is re-enabled, because it will be
  806. * freed after synchronize_rcu().
  807. */
  808. if (old_shared && force_change)
  809. synchronize_rcu();
  810. fail:
  811. kfree(old_shared);
  812. kfree(new_shared);
  813. free_alien_cache(new_alien);
  814. return ret;
  815. }
  816. #ifdef CONFIG_SMP
  817. static void cpuup_canceled(long cpu)
  818. {
  819. struct kmem_cache *cachep;
  820. struct kmem_cache_node *n = NULL;
  821. int node = cpu_to_mem(cpu);
  822. const struct cpumask *mask = cpumask_of_node(node);
  823. list_for_each_entry(cachep, &slab_caches, list) {
  824. struct array_cache *nc;
  825. struct array_cache *shared;
  826. struct alien_cache **alien;
  827. LIST_HEAD(list);
  828. n = get_node(cachep, node);
  829. if (!n)
  830. continue;
  831. spin_lock_irq(&n->list_lock);
  832. /* Free limit for this kmem_cache_node */
  833. n->free_limit -= cachep->batchcount;
  834. /* cpu is dead; no one can alloc from it. */
  835. nc = per_cpu_ptr(cachep->cpu_cache, cpu);
  836. free_block(cachep, nc->entry, nc->avail, node, &list);
  837. nc->avail = 0;
  838. if (!cpumask_empty(mask)) {
  839. spin_unlock_irq(&n->list_lock);
  840. goto free_slab;
  841. }
  842. shared = n->shared;
  843. if (shared) {
  844. free_block(cachep, shared->entry,
  845. shared->avail, node, &list);
  846. n->shared = NULL;
  847. }
  848. alien = n->alien;
  849. n->alien = NULL;
  850. spin_unlock_irq(&n->list_lock);
  851. kfree(shared);
  852. if (alien) {
  853. drain_alien_cache(cachep, alien);
  854. free_alien_cache(alien);
  855. }
  856. free_slab:
  857. slabs_destroy(cachep, &list);
  858. }
  859. /*
  860. * In the previous loop, all the objects were freed to
  861. * the respective cache's slabs, now we can go ahead and
  862. * shrink each nodelist to its limit.
  863. */
  864. list_for_each_entry(cachep, &slab_caches, list) {
  865. n = get_node(cachep, node);
  866. if (!n)
  867. continue;
  868. drain_freelist(cachep, n, INT_MAX);
  869. }
  870. }
  871. static int cpuup_prepare(long cpu)
  872. {
  873. struct kmem_cache *cachep;
  874. int node = cpu_to_mem(cpu);
  875. int err;
  876. /*
  877. * We need to do this right in the beginning since
  878. * alloc_arraycache's are going to use this list.
  879. * kmalloc_node allows us to add the slab to the right
  880. * kmem_cache_node and not this cpu's kmem_cache_node
  881. */
  882. err = init_cache_node_node(node);
  883. if (err < 0)
  884. goto bad;
  885. /*
  886. * Now we can go ahead with allocating the shared arrays and
  887. * array caches
  888. */
  889. list_for_each_entry(cachep, &slab_caches, list) {
  890. err = setup_kmem_cache_node(cachep, node, GFP_KERNEL, false);
  891. if (err)
  892. goto bad;
  893. }
  894. return 0;
  895. bad:
  896. cpuup_canceled(cpu);
  897. return -ENOMEM;
  898. }
  899. int slab_prepare_cpu(unsigned int cpu)
  900. {
  901. int err;
  902. mutex_lock(&slab_mutex);
  903. err = cpuup_prepare(cpu);
  904. mutex_unlock(&slab_mutex);
  905. return err;
  906. }
  907. /*
  908. * This is called for a failed online attempt and for a successful
  909. * offline.
  910. *
  911. * Even if all the cpus of a node are down, we don't free the
  912. * kmem_cache_node of any cache. This is to avoid a race between cpu_down, and
  913. * a kmalloc allocation from another cpu for memory from the node of
  914. * the cpu going down. The kmem_cache_node structure is usually allocated from
  915. * kmem_cache_create() and gets destroyed at kmem_cache_destroy().
  916. */
  917. int slab_dead_cpu(unsigned int cpu)
  918. {
  919. mutex_lock(&slab_mutex);
  920. cpuup_canceled(cpu);
  921. mutex_unlock(&slab_mutex);
  922. return 0;
  923. }
  924. #endif
  925. static int slab_online_cpu(unsigned int cpu)
  926. {
  927. start_cpu_timer(cpu);
  928. return 0;
  929. }
  930. static int slab_offline_cpu(unsigned int cpu)
  931. {
  932. /*
  933. * Shutdown cache reaper. Note that the slab_mutex is held so
  934. * that if cache_reap() is invoked it cannot do anything
  935. * expensive but will only modify reap_work and reschedule the
  936. * timer.
  937. */
  938. cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
  939. /* Now the cache_reaper is guaranteed to be not running. */
  940. per_cpu(slab_reap_work, cpu).work.func = NULL;
  941. return 0;
  942. }
  943. #if defined(CONFIG_NUMA)
  944. /*
  945. * Drains freelist for a node on each slab cache, used for memory hot-remove.
  946. * Returns -EBUSY if all objects cannot be drained so that the node is not
  947. * removed.
  948. *
  949. * Must hold slab_mutex.
  950. */
  951. static int __meminit drain_cache_node_node(int node)
  952. {
  953. struct kmem_cache *cachep;
  954. int ret = 0;
  955. list_for_each_entry(cachep, &slab_caches, list) {
  956. struct kmem_cache_node *n;
  957. n = get_node(cachep, node);
  958. if (!n)
  959. continue;
  960. drain_freelist(cachep, n, INT_MAX);
  961. if (!list_empty(&n->slabs_full) ||
  962. !list_empty(&n->slabs_partial)) {
  963. ret = -EBUSY;
  964. break;
  965. }
  966. }
  967. return ret;
  968. }
  969. static int __meminit slab_memory_callback(struct notifier_block *self,
  970. unsigned long action, void *arg)
  971. {
  972. struct memory_notify *mnb = arg;
  973. int ret = 0;
  974. int nid;
  975. nid = mnb->status_change_nid;
  976. if (nid < 0)
  977. goto out;
  978. switch (action) {
  979. case MEM_GOING_ONLINE:
  980. mutex_lock(&slab_mutex);
  981. ret = init_cache_node_node(nid);
  982. mutex_unlock(&slab_mutex);
  983. break;
  984. case MEM_GOING_OFFLINE:
  985. mutex_lock(&slab_mutex);
  986. ret = drain_cache_node_node(nid);
  987. mutex_unlock(&slab_mutex);
  988. break;
  989. case MEM_ONLINE:
  990. case MEM_OFFLINE:
  991. case MEM_CANCEL_ONLINE:
  992. case MEM_CANCEL_OFFLINE:
  993. break;
  994. }
  995. out:
  996. return notifier_from_errno(ret);
  997. }
  998. #endif /* CONFIG_NUMA */
  999. /*
  1000. * swap the static kmem_cache_node with kmalloced memory
  1001. */
  1002. static void __init init_list(struct kmem_cache *cachep, struct kmem_cache_node *list,
  1003. int nodeid)
  1004. {
  1005. struct kmem_cache_node *ptr;
  1006. ptr = kmalloc_node(sizeof(struct kmem_cache_node), GFP_NOWAIT, nodeid);
  1007. BUG_ON(!ptr);
  1008. memcpy(ptr, list, sizeof(struct kmem_cache_node));
  1009. /*
  1010. * Do not assume that spinlocks can be initialized via memcpy:
  1011. */
  1012. spin_lock_init(&ptr->list_lock);
  1013. MAKE_ALL_LISTS(cachep, ptr, nodeid);
  1014. cachep->node[nodeid] = ptr;
  1015. }
  1016. /*
  1017. * For setting up all the kmem_cache_node for cache whose buffer_size is same as
  1018. * size of kmem_cache_node.
  1019. */
  1020. static void __init set_up_node(struct kmem_cache *cachep, int index)
  1021. {
  1022. int node;
  1023. for_each_online_node(node) {
  1024. cachep->node[node] = &init_kmem_cache_node[index + node];
  1025. cachep->node[node]->next_reap = jiffies +
  1026. REAPTIMEOUT_NODE +
  1027. ((unsigned long)cachep) % REAPTIMEOUT_NODE;
  1028. }
  1029. }
  1030. /*
  1031. * Initialisation. Called after the page allocator have been initialised and
  1032. * before smp_init().
  1033. */
  1034. void __init kmem_cache_init(void)
  1035. {
  1036. int i;
  1037. kmem_cache = &kmem_cache_boot;
  1038. if (!IS_ENABLED(CONFIG_NUMA) || num_possible_nodes() == 1)
  1039. use_alien_caches = 0;
  1040. for (i = 0; i < NUM_INIT_LISTS; i++)
  1041. kmem_cache_node_init(&init_kmem_cache_node[i]);
  1042. /*
  1043. * Fragmentation resistance on low memory - only use bigger
  1044. * page orders on machines with more than 32MB of memory if
  1045. * not overridden on the command line.
  1046. */
  1047. if (!slab_max_order_set && totalram_pages() > (32 << 20) >> PAGE_SHIFT)
  1048. slab_max_order = SLAB_MAX_ORDER_HI;
  1049. /* Bootstrap is tricky, because several objects are allocated
  1050. * from caches that do not exist yet:
  1051. * 1) initialize the kmem_cache cache: it contains the struct
  1052. * kmem_cache structures of all caches, except kmem_cache itself:
  1053. * kmem_cache is statically allocated.
  1054. * Initially an __init data area is used for the head array and the
  1055. * kmem_cache_node structures, it's replaced with a kmalloc allocated
  1056. * array at the end of the bootstrap.
  1057. * 2) Create the first kmalloc cache.
  1058. * The struct kmem_cache for the new cache is allocated normally.
  1059. * An __init data area is used for the head array.
  1060. * 3) Create the remaining kmalloc caches, with minimally sized
  1061. * head arrays.
  1062. * 4) Replace the __init data head arrays for kmem_cache and the first
  1063. * kmalloc cache with kmalloc allocated arrays.
  1064. * 5) Replace the __init data for kmem_cache_node for kmem_cache and
  1065. * the other cache's with kmalloc allocated memory.
  1066. * 6) Resize the head arrays of the kmalloc caches to their final sizes.
  1067. */
  1068. /* 1) create the kmem_cache */
  1069. /*
  1070. * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
  1071. */
  1072. create_boot_cache(kmem_cache, "kmem_cache",
  1073. offsetof(struct kmem_cache, node) +
  1074. nr_node_ids * sizeof(struct kmem_cache_node *),
  1075. SLAB_HWCACHE_ALIGN, 0, 0);
  1076. list_add(&kmem_cache->list, &slab_caches);
  1077. slab_state = PARTIAL;
  1078. /*
  1079. * Initialize the caches that provide memory for the kmem_cache_node
  1080. * structures first. Without this, further allocations will bug.
  1081. */
  1082. kmalloc_caches[KMALLOC_NORMAL][INDEX_NODE] = create_kmalloc_cache(
  1083. kmalloc_info[INDEX_NODE].name[KMALLOC_NORMAL],
  1084. kmalloc_info[INDEX_NODE].size,
  1085. ARCH_KMALLOC_FLAGS, 0,
  1086. kmalloc_info[INDEX_NODE].size);
  1087. slab_state = PARTIAL_NODE;
  1088. setup_kmalloc_cache_index_table();
  1089. slab_early_init = 0;
  1090. /* 5) Replace the bootstrap kmem_cache_node */
  1091. {
  1092. int nid;
  1093. for_each_online_node(nid) {
  1094. init_list(kmem_cache, &init_kmem_cache_node[CACHE_CACHE + nid], nid);
  1095. init_list(kmalloc_caches[KMALLOC_NORMAL][INDEX_NODE],
  1096. &init_kmem_cache_node[SIZE_NODE + nid], nid);
  1097. }
  1098. }
  1099. create_kmalloc_caches(ARCH_KMALLOC_FLAGS);
  1100. }
  1101. void __init kmem_cache_init_late(void)
  1102. {
  1103. struct kmem_cache *cachep;
  1104. /* 6) resize the head arrays to their final sizes */
  1105. mutex_lock(&slab_mutex);
  1106. list_for_each_entry(cachep, &slab_caches, list)
  1107. if (enable_cpucache(cachep, GFP_NOWAIT))
  1108. BUG();
  1109. mutex_unlock(&slab_mutex);
  1110. /* Done! */
  1111. slab_state = FULL;
  1112. #ifdef CONFIG_NUMA
  1113. /*
  1114. * Register a memory hotplug callback that initializes and frees
  1115. * node.
  1116. */
  1117. hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
  1118. #endif
  1119. /*
  1120. * The reap timers are started later, with a module init call: That part
  1121. * of the kernel is not yet operational.
  1122. */
  1123. }
  1124. static int __init cpucache_init(void)
  1125. {
  1126. int ret;
  1127. /*
  1128. * Register the timers that return unneeded pages to the page allocator
  1129. */
  1130. ret = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "SLAB online",
  1131. slab_online_cpu, slab_offline_cpu);
  1132. WARN_ON(ret < 0);
  1133. return 0;
  1134. }
  1135. __initcall(cpucache_init);
  1136. static noinline void
  1137. slab_out_of_memory(struct kmem_cache *cachep, gfp_t gfpflags, int nodeid)
  1138. {
  1139. #if DEBUG
  1140. struct kmem_cache_node *n;
  1141. unsigned long flags;
  1142. int node;
  1143. static DEFINE_RATELIMIT_STATE(slab_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
  1144. DEFAULT_RATELIMIT_BURST);
  1145. if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slab_oom_rs))
  1146. return;
  1147. pr_warn("SLAB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
  1148. nodeid, gfpflags, &gfpflags);
  1149. pr_warn(" cache: %s, object size: %d, order: %d\n",
  1150. cachep->name, cachep->size, cachep->gfporder);
  1151. for_each_kmem_cache_node(cachep, node, n) {
  1152. unsigned long total_slabs, free_slabs, free_objs;
  1153. spin_lock_irqsave(&n->list_lock, flags);
  1154. total_slabs = n->total_slabs;
  1155. free_slabs = n->free_slabs;
  1156. free_objs = n->free_objects;
  1157. spin_unlock_irqrestore(&n->list_lock, flags);
  1158. pr_warn(" node %d: slabs: %ld/%ld, objs: %ld/%ld\n",
  1159. node, total_slabs - free_slabs, total_slabs,
  1160. (total_slabs * cachep->num) - free_objs,
  1161. total_slabs * cachep->num);
  1162. }
  1163. #endif
  1164. }
  1165. /*
  1166. * Interface to system's page allocator. No need to hold the
  1167. * kmem_cache_node ->list_lock.
  1168. *
  1169. * If we requested dmaable memory, we will get it. Even if we
  1170. * did not request dmaable memory, we might get it, but that
  1171. * would be relatively rare and ignorable.
  1172. */
  1173. static struct slab *kmem_getpages(struct kmem_cache *cachep, gfp_t flags,
  1174. int nodeid)
  1175. {
  1176. struct folio *folio;
  1177. struct slab *slab;
  1178. flags |= cachep->allocflags;
  1179. folio = (struct folio *) __alloc_pages_node(nodeid, flags, cachep->gfporder);
  1180. if (!folio) {
  1181. slab_out_of_memory(cachep, flags, nodeid);
  1182. return NULL;
  1183. }
  1184. slab = folio_slab(folio);
  1185. account_slab(slab, cachep->gfporder, cachep, flags);
  1186. __folio_set_slab(folio);
  1187. /* Record if ALLOC_NO_WATERMARKS was set when allocating the slab */
  1188. if (sk_memalloc_socks() && page_is_pfmemalloc(folio_page(folio, 0)))
  1189. slab_set_pfmemalloc(slab);
  1190. return slab;
  1191. }
  1192. /*
  1193. * Interface to system's page release.
  1194. */
  1195. static void kmem_freepages(struct kmem_cache *cachep, struct slab *slab)
  1196. {
  1197. int order = cachep->gfporder;
  1198. struct folio *folio = slab_folio(slab);
  1199. BUG_ON(!folio_test_slab(folio));
  1200. __slab_clear_pfmemalloc(slab);
  1201. __folio_clear_slab(folio);
  1202. page_mapcount_reset(folio_page(folio, 0));
  1203. folio->mapping = NULL;
  1204. if (current->reclaim_state)
  1205. current->reclaim_state->reclaimed_slab += 1 << order;
  1206. unaccount_slab(slab, order, cachep);
  1207. __free_pages(folio_page(folio, 0), order);
  1208. }
  1209. static void kmem_rcu_free(struct rcu_head *head)
  1210. {
  1211. struct kmem_cache *cachep;
  1212. struct slab *slab;
  1213. slab = container_of(head, struct slab, rcu_head);
  1214. cachep = slab->slab_cache;
  1215. kmem_freepages(cachep, slab);
  1216. }
  1217. #if DEBUG
  1218. static bool is_debug_pagealloc_cache(struct kmem_cache *cachep)
  1219. {
  1220. if (debug_pagealloc_enabled_static() && OFF_SLAB(cachep) &&
  1221. (cachep->size % PAGE_SIZE) == 0)
  1222. return true;
  1223. return false;
  1224. }
  1225. #ifdef CONFIG_DEBUG_PAGEALLOC
  1226. static void slab_kernel_map(struct kmem_cache *cachep, void *objp, int map)
  1227. {
  1228. if (!is_debug_pagealloc_cache(cachep))
  1229. return;
  1230. __kernel_map_pages(virt_to_page(objp), cachep->size / PAGE_SIZE, map);
  1231. }
  1232. #else
  1233. static inline void slab_kernel_map(struct kmem_cache *cachep, void *objp,
  1234. int map) {}
  1235. #endif
  1236. static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
  1237. {
  1238. int size = cachep->object_size;
  1239. addr = &((char *)addr)[obj_offset(cachep)];
  1240. memset(addr, val, size);
  1241. *(unsigned char *)(addr + size - 1) = POISON_END;
  1242. }
  1243. static void dump_line(char *data, int offset, int limit)
  1244. {
  1245. int i;
  1246. unsigned char error = 0;
  1247. int bad_count = 0;
  1248. pr_err("%03x: ", offset);
  1249. for (i = 0; i < limit; i++) {
  1250. if (data[offset + i] != POISON_FREE) {
  1251. error = data[offset + i];
  1252. bad_count++;
  1253. }
  1254. }
  1255. print_hex_dump(KERN_CONT, "", 0, 16, 1,
  1256. &data[offset], limit, 1);
  1257. if (bad_count == 1) {
  1258. error ^= POISON_FREE;
  1259. if (!(error & (error - 1))) {
  1260. pr_err("Single bit error detected. Probably bad RAM.\n");
  1261. #ifdef CONFIG_X86
  1262. pr_err("Run memtest86+ or a similar memory test tool.\n");
  1263. #else
  1264. pr_err("Run a memory test tool.\n");
  1265. #endif
  1266. }
  1267. }
  1268. }
  1269. #endif
  1270. #if DEBUG
  1271. static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
  1272. {
  1273. int i, size;
  1274. char *realobj;
  1275. if (cachep->flags & SLAB_RED_ZONE) {
  1276. pr_err("Redzone: 0x%llx/0x%llx\n",
  1277. *dbg_redzone1(cachep, objp),
  1278. *dbg_redzone2(cachep, objp));
  1279. }
  1280. if (cachep->flags & SLAB_STORE_USER)
  1281. pr_err("Last user: (%pSR)\n", *dbg_userword(cachep, objp));
  1282. realobj = (char *)objp + obj_offset(cachep);
  1283. size = cachep->object_size;
  1284. for (i = 0; i < size && lines; i += 16, lines--) {
  1285. int limit;
  1286. limit = 16;
  1287. if (i + limit > size)
  1288. limit = size - i;
  1289. dump_line(realobj, i, limit);
  1290. }
  1291. }
  1292. static void check_poison_obj(struct kmem_cache *cachep, void *objp)
  1293. {
  1294. char *realobj;
  1295. int size, i;
  1296. int lines = 0;
  1297. if (is_debug_pagealloc_cache(cachep))
  1298. return;
  1299. realobj = (char *)objp + obj_offset(cachep);
  1300. size = cachep->object_size;
  1301. for (i = 0; i < size; i++) {
  1302. char exp = POISON_FREE;
  1303. if (i == size - 1)
  1304. exp = POISON_END;
  1305. if (realobj[i] != exp) {
  1306. int limit;
  1307. /* Mismatch ! */
  1308. /* Print header */
  1309. if (lines == 0) {
  1310. pr_err("Slab corruption (%s): %s start=%px, len=%d\n",
  1311. print_tainted(), cachep->name,
  1312. realobj, size);
  1313. print_objinfo(cachep, objp, 0);
  1314. }
  1315. /* Hexdump the affected line */
  1316. i = (i / 16) * 16;
  1317. limit = 16;
  1318. if (i + limit > size)
  1319. limit = size - i;
  1320. dump_line(realobj, i, limit);
  1321. i += 16;
  1322. lines++;
  1323. /* Limit to 5 lines */
  1324. if (lines > 5)
  1325. break;
  1326. }
  1327. }
  1328. if (lines != 0) {
  1329. /* Print some data about the neighboring objects, if they
  1330. * exist:
  1331. */
  1332. struct slab *slab = virt_to_slab(objp);
  1333. unsigned int objnr;
  1334. objnr = obj_to_index(cachep, slab, objp);
  1335. if (objnr) {
  1336. objp = index_to_obj(cachep, slab, objnr - 1);
  1337. realobj = (char *)objp + obj_offset(cachep);
  1338. pr_err("Prev obj: start=%px, len=%d\n", realobj, size);
  1339. print_objinfo(cachep, objp, 2);
  1340. }
  1341. if (objnr + 1 < cachep->num) {
  1342. objp = index_to_obj(cachep, slab, objnr + 1);
  1343. realobj = (char *)objp + obj_offset(cachep);
  1344. pr_err("Next obj: start=%px, len=%d\n", realobj, size);
  1345. print_objinfo(cachep, objp, 2);
  1346. }
  1347. }
  1348. }
  1349. #endif
  1350. #if DEBUG
  1351. static void slab_destroy_debugcheck(struct kmem_cache *cachep,
  1352. struct slab *slab)
  1353. {
  1354. int i;
  1355. if (OBJFREELIST_SLAB(cachep) && cachep->flags & SLAB_POISON) {
  1356. poison_obj(cachep, slab->freelist - obj_offset(cachep),
  1357. POISON_FREE);
  1358. }
  1359. for (i = 0; i < cachep->num; i++) {
  1360. void *objp = index_to_obj(cachep, slab, i);
  1361. if (cachep->flags & SLAB_POISON) {
  1362. check_poison_obj(cachep, objp);
  1363. slab_kernel_map(cachep, objp, 1);
  1364. }
  1365. if (cachep->flags & SLAB_RED_ZONE) {
  1366. if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
  1367. slab_error(cachep, "start of a freed object was overwritten");
  1368. if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
  1369. slab_error(cachep, "end of a freed object was overwritten");
  1370. }
  1371. }
  1372. }
  1373. #else
  1374. static void slab_destroy_debugcheck(struct kmem_cache *cachep,
  1375. struct slab *slab)
  1376. {
  1377. }
  1378. #endif
  1379. /**
  1380. * slab_destroy - destroy and release all objects in a slab
  1381. * @cachep: cache pointer being destroyed
  1382. * @slab: slab being destroyed
  1383. *
  1384. * Destroy all the objs in a slab, and release the mem back to the system.
  1385. * Before calling the slab must have been unlinked from the cache. The
  1386. * kmem_cache_node ->list_lock is not held/needed.
  1387. */
  1388. static void slab_destroy(struct kmem_cache *cachep, struct slab *slab)
  1389. {
  1390. void *freelist;
  1391. freelist = slab->freelist;
  1392. slab_destroy_debugcheck(cachep, slab);
  1393. if (unlikely(cachep->flags & SLAB_TYPESAFE_BY_RCU))
  1394. call_rcu(&slab->rcu_head, kmem_rcu_free);
  1395. else
  1396. kmem_freepages(cachep, slab);
  1397. /*
  1398. * From now on, we don't use freelist
  1399. * although actual page can be freed in rcu context
  1400. */
  1401. if (OFF_SLAB(cachep))
  1402. kfree(freelist);
  1403. }
  1404. /*
  1405. * Update the size of the caches before calling slabs_destroy as it may
  1406. * recursively call kfree.
  1407. */
  1408. static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list)
  1409. {
  1410. struct slab *slab, *n;
  1411. list_for_each_entry_safe(slab, n, list, slab_list) {
  1412. list_del(&slab->slab_list);
  1413. slab_destroy(cachep, slab);
  1414. }
  1415. }
  1416. /**
  1417. * calculate_slab_order - calculate size (page order) of slabs
  1418. * @cachep: pointer to the cache that is being created
  1419. * @size: size of objects to be created in this cache.
  1420. * @flags: slab allocation flags
  1421. *
  1422. * Also calculates the number of objects per slab.
  1423. *
  1424. * This could be made much more intelligent. For now, try to avoid using
  1425. * high order pages for slabs. When the gfp() functions are more friendly
  1426. * towards high-order requests, this should be changed.
  1427. *
  1428. * Return: number of left-over bytes in a slab
  1429. */
  1430. static size_t calculate_slab_order(struct kmem_cache *cachep,
  1431. size_t size, slab_flags_t flags)
  1432. {
  1433. size_t left_over = 0;
  1434. int gfporder;
  1435. for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
  1436. unsigned int num;
  1437. size_t remainder;
  1438. num = cache_estimate(gfporder, size, flags, &remainder);
  1439. if (!num)
  1440. continue;
  1441. /* Can't handle number of objects more than SLAB_OBJ_MAX_NUM */
  1442. if (num > SLAB_OBJ_MAX_NUM)
  1443. break;
  1444. if (flags & CFLGS_OFF_SLAB) {
  1445. struct kmem_cache *freelist_cache;
  1446. size_t freelist_size;
  1447. size_t freelist_cache_size;
  1448. freelist_size = num * sizeof(freelist_idx_t);
  1449. if (freelist_size > KMALLOC_MAX_CACHE_SIZE) {
  1450. freelist_cache_size = PAGE_SIZE << get_order(freelist_size);
  1451. } else {
  1452. freelist_cache = kmalloc_slab(freelist_size, 0u);
  1453. if (!freelist_cache)
  1454. continue;
  1455. freelist_cache_size = freelist_cache->size;
  1456. /*
  1457. * Needed to avoid possible looping condition
  1458. * in cache_grow_begin()
  1459. */
  1460. if (OFF_SLAB(freelist_cache))
  1461. continue;
  1462. }
  1463. /* check if off slab has enough benefit */
  1464. if (freelist_cache_size > cachep->size / 2)
  1465. continue;
  1466. }
  1467. /* Found something acceptable - save it away */
  1468. cachep->num = num;
  1469. cachep->gfporder = gfporder;
  1470. left_over = remainder;
  1471. /*
  1472. * A VFS-reclaimable slab tends to have most allocations
  1473. * as GFP_NOFS and we really don't want to have to be allocating
  1474. * higher-order pages when we are unable to shrink dcache.
  1475. */
  1476. if (flags & SLAB_RECLAIM_ACCOUNT)
  1477. break;
  1478. /*
  1479. * Large number of objects is good, but very large slabs are
  1480. * currently bad for the gfp()s.
  1481. */
  1482. if (gfporder >= slab_max_order)
  1483. break;
  1484. /*
  1485. * Acceptable internal fragmentation?
  1486. */
  1487. if (left_over * 8 <= (PAGE_SIZE << gfporder))
  1488. break;
  1489. }
  1490. return left_over;
  1491. }
  1492. static struct array_cache __percpu *alloc_kmem_cache_cpus(
  1493. struct kmem_cache *cachep, int entries, int batchcount)
  1494. {
  1495. int cpu;
  1496. size_t size;
  1497. struct array_cache __percpu *cpu_cache;
  1498. size = sizeof(void *) * entries + sizeof(struct array_cache);
  1499. cpu_cache = __alloc_percpu(size, sizeof(void *));
  1500. if (!cpu_cache)
  1501. return NULL;
  1502. for_each_possible_cpu(cpu) {
  1503. init_arraycache(per_cpu_ptr(cpu_cache, cpu),
  1504. entries, batchcount);
  1505. }
  1506. return cpu_cache;
  1507. }
  1508. static int __ref setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
  1509. {
  1510. if (slab_state >= FULL)
  1511. return enable_cpucache(cachep, gfp);
  1512. cachep->cpu_cache = alloc_kmem_cache_cpus(cachep, 1, 1);
  1513. if (!cachep->cpu_cache)
  1514. return 1;
  1515. if (slab_state == DOWN) {
  1516. /* Creation of first cache (kmem_cache). */
  1517. set_up_node(kmem_cache, CACHE_CACHE);
  1518. } else if (slab_state == PARTIAL) {
  1519. /* For kmem_cache_node */
  1520. set_up_node(cachep, SIZE_NODE);
  1521. } else {
  1522. int node;
  1523. for_each_online_node(node) {
  1524. cachep->node[node] = kmalloc_node(
  1525. sizeof(struct kmem_cache_node), gfp, node);
  1526. BUG_ON(!cachep->node[node]);
  1527. kmem_cache_node_init(cachep->node[node]);
  1528. }
  1529. }
  1530. cachep->node[numa_mem_id()]->next_reap =
  1531. jiffies + REAPTIMEOUT_NODE +
  1532. ((unsigned long)cachep) % REAPTIMEOUT_NODE;
  1533. cpu_cache_get(cachep)->avail = 0;
  1534. cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
  1535. cpu_cache_get(cachep)->batchcount = 1;
  1536. cpu_cache_get(cachep)->touched = 0;
  1537. cachep->batchcount = 1;
  1538. cachep->limit = BOOT_CPUCACHE_ENTRIES;
  1539. return 0;
  1540. }
  1541. slab_flags_t kmem_cache_flags(unsigned int object_size,
  1542. slab_flags_t flags, const char *name)
  1543. {
  1544. return flags;
  1545. }
  1546. struct kmem_cache *
  1547. __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
  1548. slab_flags_t flags, void (*ctor)(void *))
  1549. {
  1550. struct kmem_cache *cachep;
  1551. cachep = find_mergeable(size, align, flags, name, ctor);
  1552. if (cachep) {
  1553. cachep->refcount++;
  1554. /*
  1555. * Adjust the object sizes so that we clear
  1556. * the complete object on kzalloc.
  1557. */
  1558. cachep->object_size = max_t(int, cachep->object_size, size);
  1559. }
  1560. return cachep;
  1561. }
  1562. static bool set_objfreelist_slab_cache(struct kmem_cache *cachep,
  1563. size_t size, slab_flags_t flags)
  1564. {
  1565. size_t left;
  1566. cachep->num = 0;
  1567. /*
  1568. * If slab auto-initialization on free is enabled, store the freelist
  1569. * off-slab, so that its contents don't end up in one of the allocated
  1570. * objects.
  1571. */
  1572. if (unlikely(slab_want_init_on_free(cachep)))
  1573. return false;
  1574. if (cachep->ctor || flags & SLAB_TYPESAFE_BY_RCU)
  1575. return false;
  1576. left = calculate_slab_order(cachep, size,
  1577. flags | CFLGS_OBJFREELIST_SLAB);
  1578. if (!cachep->num)
  1579. return false;
  1580. if (cachep->num * sizeof(freelist_idx_t) > cachep->object_size)
  1581. return false;
  1582. cachep->colour = left / cachep->colour_off;
  1583. return true;
  1584. }
  1585. static bool set_off_slab_cache(struct kmem_cache *cachep,
  1586. size_t size, slab_flags_t flags)
  1587. {
  1588. size_t left;
  1589. cachep->num = 0;
  1590. /*
  1591. * Always use on-slab management when SLAB_NOLEAKTRACE
  1592. * to avoid recursive calls into kmemleak.
  1593. */
  1594. if (flags & SLAB_NOLEAKTRACE)
  1595. return false;
  1596. /*
  1597. * Size is large, assume best to place the slab management obj
  1598. * off-slab (should allow better packing of objs).
  1599. */
  1600. left = calculate_slab_order(cachep, size, flags | CFLGS_OFF_SLAB);
  1601. if (!cachep->num)
  1602. return false;
  1603. /*
  1604. * If the slab has been placed off-slab, and we have enough space then
  1605. * move it on-slab. This is at the expense of any extra colouring.
  1606. */
  1607. if (left >= cachep->num * sizeof(freelist_idx_t))
  1608. return false;
  1609. cachep->colour = left / cachep->colour_off;
  1610. return true;
  1611. }
  1612. static bool set_on_slab_cache(struct kmem_cache *cachep,
  1613. size_t size, slab_flags_t flags)
  1614. {
  1615. size_t left;
  1616. cachep->num = 0;
  1617. left = calculate_slab_order(cachep, size, flags);
  1618. if (!cachep->num)
  1619. return false;
  1620. cachep->colour = left / cachep->colour_off;
  1621. return true;
  1622. }
  1623. /**
  1624. * __kmem_cache_create - Create a cache.
  1625. * @cachep: cache management descriptor
  1626. * @flags: SLAB flags
  1627. *
  1628. * Returns a ptr to the cache on success, NULL on failure.
  1629. * Cannot be called within an int, but can be interrupted.
  1630. * The @ctor is run when new pages are allocated by the cache.
  1631. *
  1632. * The flags are
  1633. *
  1634. * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
  1635. * to catch references to uninitialised memory.
  1636. *
  1637. * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
  1638. * for buffer overruns.
  1639. *
  1640. * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
  1641. * cacheline. This can be beneficial if you're counting cycles as closely
  1642. * as davem.
  1643. *
  1644. * Return: a pointer to the created cache or %NULL in case of error
  1645. */
  1646. int __kmem_cache_create(struct kmem_cache *cachep, slab_flags_t flags)
  1647. {
  1648. size_t ralign = BYTES_PER_WORD;
  1649. gfp_t gfp;
  1650. int err;
  1651. unsigned int size = cachep->size;
  1652. #if DEBUG
  1653. #if FORCED_DEBUG
  1654. /*
  1655. * Enable redzoning and last user accounting, except for caches with
  1656. * large objects, if the increased size would increase the object size
  1657. * above the next power of two: caches with object sizes just above a
  1658. * power of two have a significant amount of internal fragmentation.
  1659. */
  1660. if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
  1661. 2 * sizeof(unsigned long long)))
  1662. flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
  1663. if (!(flags & SLAB_TYPESAFE_BY_RCU))
  1664. flags |= SLAB_POISON;
  1665. #endif
  1666. #endif
  1667. /*
  1668. * Check that size is in terms of words. This is needed to avoid
  1669. * unaligned accesses for some archs when redzoning is used, and makes
  1670. * sure any on-slab bufctl's are also correctly aligned.
  1671. */
  1672. size = ALIGN(size, BYTES_PER_WORD);
  1673. if (flags & SLAB_RED_ZONE) {
  1674. ralign = REDZONE_ALIGN;
  1675. /* If redzoning, ensure that the second redzone is suitably
  1676. * aligned, by adjusting the object size accordingly. */
  1677. size = ALIGN(size, REDZONE_ALIGN);
  1678. }
  1679. /* 3) caller mandated alignment */
  1680. if (ralign < cachep->align) {
  1681. ralign = cachep->align;
  1682. }
  1683. /* disable debug if necessary */
  1684. if (ralign > __alignof__(unsigned long long))
  1685. flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
  1686. /*
  1687. * 4) Store it.
  1688. */
  1689. cachep->align = ralign;
  1690. cachep->colour_off = cache_line_size();
  1691. /* Offset must be a multiple of the alignment. */
  1692. if (cachep->colour_off < cachep->align)
  1693. cachep->colour_off = cachep->align;
  1694. if (slab_is_available())
  1695. gfp = GFP_KERNEL;
  1696. else
  1697. gfp = GFP_NOWAIT;
  1698. #if DEBUG
  1699. /*
  1700. * Both debugging options require word-alignment which is calculated
  1701. * into align above.
  1702. */
  1703. if (flags & SLAB_RED_ZONE) {
  1704. /* add space for red zone words */
  1705. cachep->obj_offset += sizeof(unsigned long long);
  1706. size += 2 * sizeof(unsigned long long);
  1707. }
  1708. if (flags & SLAB_STORE_USER) {
  1709. /* user store requires one word storage behind the end of
  1710. * the real object. But if the second red zone needs to be
  1711. * aligned to 64 bits, we must allow that much space.
  1712. */
  1713. if (flags & SLAB_RED_ZONE)
  1714. size += REDZONE_ALIGN;
  1715. else
  1716. size += BYTES_PER_WORD;
  1717. }
  1718. #endif
  1719. kasan_cache_create(cachep, &size, &flags);
  1720. size = ALIGN(size, cachep->align);
  1721. /*
  1722. * We should restrict the number of objects in a slab to implement
  1723. * byte sized index. Refer comment on SLAB_OBJ_MIN_SIZE definition.
  1724. */
  1725. if (FREELIST_BYTE_INDEX && size < SLAB_OBJ_MIN_SIZE)
  1726. size = ALIGN(SLAB_OBJ_MIN_SIZE, cachep->align);
  1727. #if DEBUG
  1728. /*
  1729. * To activate debug pagealloc, off-slab management is necessary
  1730. * requirement. In early phase of initialization, small sized slab
  1731. * doesn't get initialized so it would not be possible. So, we need
  1732. * to check size >= 256. It guarantees that all necessary small
  1733. * sized slab is initialized in current slab initialization sequence.
  1734. */
  1735. if (debug_pagealloc_enabled_static() && (flags & SLAB_POISON) &&
  1736. size >= 256 && cachep->object_size > cache_line_size()) {
  1737. if (size < PAGE_SIZE || size % PAGE_SIZE == 0) {
  1738. size_t tmp_size = ALIGN(size, PAGE_SIZE);
  1739. if (set_off_slab_cache(cachep, tmp_size, flags)) {
  1740. flags |= CFLGS_OFF_SLAB;
  1741. cachep->obj_offset += tmp_size - size;
  1742. size = tmp_size;
  1743. goto done;
  1744. }
  1745. }
  1746. }
  1747. #endif
  1748. if (set_objfreelist_slab_cache(cachep, size, flags)) {
  1749. flags |= CFLGS_OBJFREELIST_SLAB;
  1750. goto done;
  1751. }
  1752. if (set_off_slab_cache(cachep, size, flags)) {
  1753. flags |= CFLGS_OFF_SLAB;
  1754. goto done;
  1755. }
  1756. if (set_on_slab_cache(cachep, size, flags))
  1757. goto done;
  1758. return -E2BIG;
  1759. done:
  1760. cachep->freelist_size = cachep->num * sizeof(freelist_idx_t);
  1761. cachep->flags = flags;
  1762. cachep->allocflags = __GFP_COMP;
  1763. if (flags & SLAB_CACHE_DMA)
  1764. cachep->allocflags |= GFP_DMA;
  1765. if (flags & SLAB_CACHE_DMA32)
  1766. cachep->allocflags |= GFP_DMA32;
  1767. if (flags & SLAB_RECLAIM_ACCOUNT)
  1768. cachep->allocflags |= __GFP_RECLAIMABLE;
  1769. cachep->size = size;
  1770. cachep->reciprocal_buffer_size = reciprocal_value(size);
  1771. #if DEBUG
  1772. /*
  1773. * If we're going to use the generic kernel_map_pages()
  1774. * poisoning, then it's going to smash the contents of
  1775. * the redzone and userword anyhow, so switch them off.
  1776. */
  1777. if (IS_ENABLED(CONFIG_PAGE_POISONING) &&
  1778. (cachep->flags & SLAB_POISON) &&
  1779. is_debug_pagealloc_cache(cachep))
  1780. cachep->flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
  1781. #endif
  1782. err = setup_cpu_cache(cachep, gfp);
  1783. if (err) {
  1784. __kmem_cache_release(cachep);
  1785. return err;
  1786. }
  1787. return 0;
  1788. }
  1789. #if DEBUG
  1790. static void check_irq_off(void)
  1791. {
  1792. BUG_ON(!irqs_disabled());
  1793. }
  1794. static void check_irq_on(void)
  1795. {
  1796. BUG_ON(irqs_disabled());
  1797. }
  1798. static void check_mutex_acquired(void)
  1799. {
  1800. BUG_ON(!mutex_is_locked(&slab_mutex));
  1801. }
  1802. static void check_spinlock_acquired(struct kmem_cache *cachep)
  1803. {
  1804. #ifdef CONFIG_SMP
  1805. check_irq_off();
  1806. assert_spin_locked(&get_node(cachep, numa_mem_id())->list_lock);
  1807. #endif
  1808. }
  1809. static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
  1810. {
  1811. #ifdef CONFIG_SMP
  1812. check_irq_off();
  1813. assert_spin_locked(&get_node(cachep, node)->list_lock);
  1814. #endif
  1815. }
  1816. #else
  1817. #define check_irq_off() do { } while(0)
  1818. #define check_irq_on() do { } while(0)
  1819. #define check_mutex_acquired() do { } while(0)
  1820. #define check_spinlock_acquired(x) do { } while(0)
  1821. #define check_spinlock_acquired_node(x, y) do { } while(0)
  1822. #endif
  1823. static void drain_array_locked(struct kmem_cache *cachep, struct array_cache *ac,
  1824. int node, bool free_all, struct list_head *list)
  1825. {
  1826. int tofree;
  1827. if (!ac || !ac->avail)
  1828. return;
  1829. tofree = free_all ? ac->avail : (ac->limit + 4) / 5;
  1830. if (tofree > ac->avail)
  1831. tofree = (ac->avail + 1) / 2;
  1832. free_block(cachep, ac->entry, tofree, node, list);
  1833. ac->avail -= tofree;
  1834. memmove(ac->entry, &(ac->entry[tofree]), sizeof(void *) * ac->avail);
  1835. }
  1836. static void do_drain(void *arg)
  1837. {
  1838. struct kmem_cache *cachep = arg;
  1839. struct array_cache *ac;
  1840. int node = numa_mem_id();
  1841. struct kmem_cache_node *n;
  1842. LIST_HEAD(list);
  1843. check_irq_off();
  1844. ac = cpu_cache_get(cachep);
  1845. n = get_node(cachep, node);
  1846. spin_lock(&n->list_lock);
  1847. free_block(cachep, ac->entry, ac->avail, node, &list);
  1848. spin_unlock(&n->list_lock);
  1849. ac->avail = 0;
  1850. slabs_destroy(cachep, &list);
  1851. }
  1852. static void drain_cpu_caches(struct kmem_cache *cachep)
  1853. {
  1854. struct kmem_cache_node *n;
  1855. int node;
  1856. LIST_HEAD(list);
  1857. on_each_cpu(do_drain, cachep, 1);
  1858. check_irq_on();
  1859. for_each_kmem_cache_node(cachep, node, n)
  1860. if (n->alien)
  1861. drain_alien_cache(cachep, n->alien);
  1862. for_each_kmem_cache_node(cachep, node, n) {
  1863. spin_lock_irq(&n->list_lock);
  1864. drain_array_locked(cachep, n->shared, node, true, &list);
  1865. spin_unlock_irq(&n->list_lock);
  1866. slabs_destroy(cachep, &list);
  1867. }
  1868. }
  1869. /*
  1870. * Remove slabs from the list of free slabs.
  1871. * Specify the number of slabs to drain in tofree.
  1872. *
  1873. * Returns the actual number of slabs released.
  1874. */
  1875. static int drain_freelist(struct kmem_cache *cache,
  1876. struct kmem_cache_node *n, int tofree)
  1877. {
  1878. struct list_head *p;
  1879. int nr_freed;
  1880. struct slab *slab;
  1881. nr_freed = 0;
  1882. while (nr_freed < tofree && !list_empty(&n->slabs_free)) {
  1883. spin_lock_irq(&n->list_lock);
  1884. p = n->slabs_free.prev;
  1885. if (p == &n->slabs_free) {
  1886. spin_unlock_irq(&n->list_lock);
  1887. goto out;
  1888. }
  1889. slab = list_entry(p, struct slab, slab_list);
  1890. list_del(&slab->slab_list);
  1891. n->free_slabs--;
  1892. n->total_slabs--;
  1893. /*
  1894. * Safe to drop the lock. The slab is no longer linked
  1895. * to the cache.
  1896. */
  1897. n->free_objects -= cache->num;
  1898. spin_unlock_irq(&n->list_lock);
  1899. slab_destroy(cache, slab);
  1900. nr_freed++;
  1901. }
  1902. out:
  1903. return nr_freed;
  1904. }
  1905. bool __kmem_cache_empty(struct kmem_cache *s)
  1906. {
  1907. int node;
  1908. struct kmem_cache_node *n;
  1909. for_each_kmem_cache_node(s, node, n)
  1910. if (!list_empty(&n->slabs_full) ||
  1911. !list_empty(&n->slabs_partial))
  1912. return false;
  1913. return true;
  1914. }
  1915. int __kmem_cache_shrink(struct kmem_cache *cachep)
  1916. {
  1917. int ret = 0;
  1918. int node;
  1919. struct kmem_cache_node *n;
  1920. drain_cpu_caches(cachep);
  1921. check_irq_on();
  1922. for_each_kmem_cache_node(cachep, node, n) {
  1923. drain_freelist(cachep, n, INT_MAX);
  1924. ret += !list_empty(&n->slabs_full) ||
  1925. !list_empty(&n->slabs_partial);
  1926. }
  1927. return (ret ? 1 : 0);
  1928. }
  1929. int __kmem_cache_shutdown(struct kmem_cache *cachep)
  1930. {
  1931. return __kmem_cache_shrink(cachep);
  1932. }
  1933. void __kmem_cache_release(struct kmem_cache *cachep)
  1934. {
  1935. int i;
  1936. struct kmem_cache_node *n;
  1937. cache_random_seq_destroy(cachep);
  1938. free_percpu(cachep->cpu_cache);
  1939. /* NUMA: free the node structures */
  1940. for_each_kmem_cache_node(cachep, i, n) {
  1941. kfree(n->shared);
  1942. free_alien_cache(n->alien);
  1943. kfree(n);
  1944. cachep->node[i] = NULL;
  1945. }
  1946. }
  1947. /*
  1948. * Get the memory for a slab management obj.
  1949. *
  1950. * For a slab cache when the slab descriptor is off-slab, the
  1951. * slab descriptor can't come from the same cache which is being created,
  1952. * Because if it is the case, that means we defer the creation of
  1953. * the kmalloc_{dma,}_cache of size sizeof(slab descriptor) to this point.
  1954. * And we eventually call down to __kmem_cache_create(), which
  1955. * in turn looks up in the kmalloc_{dma,}_caches for the desired-size one.
  1956. * This is a "chicken-and-egg" problem.
  1957. *
  1958. * So the off-slab slab descriptor shall come from the kmalloc_{dma,}_caches,
  1959. * which are all initialized during kmem_cache_init().
  1960. */
  1961. static void *alloc_slabmgmt(struct kmem_cache *cachep,
  1962. struct slab *slab, int colour_off,
  1963. gfp_t local_flags, int nodeid)
  1964. {
  1965. void *freelist;
  1966. void *addr = slab_address(slab);
  1967. slab->s_mem = addr + colour_off;
  1968. slab->active = 0;
  1969. if (OBJFREELIST_SLAB(cachep))
  1970. freelist = NULL;
  1971. else if (OFF_SLAB(cachep)) {
  1972. /* Slab management obj is off-slab. */
  1973. freelist = kmalloc_node(cachep->freelist_size,
  1974. local_flags, nodeid);
  1975. } else {
  1976. /* We will use last bytes at the slab for freelist */
  1977. freelist = addr + (PAGE_SIZE << cachep->gfporder) -
  1978. cachep->freelist_size;
  1979. }
  1980. return freelist;
  1981. }
  1982. static inline freelist_idx_t get_free_obj(struct slab *slab, unsigned int idx)
  1983. {
  1984. return ((freelist_idx_t *) slab->freelist)[idx];
  1985. }
  1986. static inline void set_free_obj(struct slab *slab,
  1987. unsigned int idx, freelist_idx_t val)
  1988. {
  1989. ((freelist_idx_t *)(slab->freelist))[idx] = val;
  1990. }
  1991. static void cache_init_objs_debug(struct kmem_cache *cachep, struct slab *slab)
  1992. {
  1993. #if DEBUG
  1994. int i;
  1995. for (i = 0; i < cachep->num; i++) {
  1996. void *objp = index_to_obj(cachep, slab, i);
  1997. if (cachep->flags & SLAB_STORE_USER)
  1998. *dbg_userword(cachep, objp) = NULL;
  1999. if (cachep->flags & SLAB_RED_ZONE) {
  2000. *dbg_redzone1(cachep, objp) = RED_INACTIVE;
  2001. *dbg_redzone2(cachep, objp) = RED_INACTIVE;
  2002. }
  2003. /*
  2004. * Constructors are not allowed to allocate memory from the same
  2005. * cache which they are a constructor for. Otherwise, deadlock.
  2006. * They must also be threaded.
  2007. */
  2008. if (cachep->ctor && !(cachep->flags & SLAB_POISON)) {
  2009. kasan_unpoison_object_data(cachep,
  2010. objp + obj_offset(cachep));
  2011. cachep->ctor(objp + obj_offset(cachep));
  2012. kasan_poison_object_data(
  2013. cachep, objp + obj_offset(cachep));
  2014. }
  2015. if (cachep->flags & SLAB_RED_ZONE) {
  2016. if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
  2017. slab_error(cachep, "constructor overwrote the end of an object");
  2018. if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
  2019. slab_error(cachep, "constructor overwrote the start of an object");
  2020. }
  2021. /* need to poison the objs? */
  2022. if (cachep->flags & SLAB_POISON) {
  2023. poison_obj(cachep, objp, POISON_FREE);
  2024. slab_kernel_map(cachep, objp, 0);
  2025. }
  2026. }
  2027. #endif
  2028. }
  2029. #ifdef CONFIG_SLAB_FREELIST_RANDOM
  2030. /* Hold information during a freelist initialization */
  2031. union freelist_init_state {
  2032. struct {
  2033. unsigned int pos;
  2034. unsigned int *list;
  2035. unsigned int count;
  2036. };
  2037. struct rnd_state rnd_state;
  2038. };
  2039. /*
  2040. * Initialize the state based on the randomization method available.
  2041. * return true if the pre-computed list is available, false otherwise.
  2042. */
  2043. static bool freelist_state_initialize(union freelist_init_state *state,
  2044. struct kmem_cache *cachep,
  2045. unsigned int count)
  2046. {
  2047. bool ret;
  2048. unsigned int rand;
  2049. /* Use best entropy available to define a random shift */
  2050. rand = get_random_u32();
  2051. /* Use a random state if the pre-computed list is not available */
  2052. if (!cachep->random_seq) {
  2053. prandom_seed_state(&state->rnd_state, rand);
  2054. ret = false;
  2055. } else {
  2056. state->list = cachep->random_seq;
  2057. state->count = count;
  2058. state->pos = rand % count;
  2059. ret = true;
  2060. }
  2061. return ret;
  2062. }
  2063. /* Get the next entry on the list and randomize it using a random shift */
  2064. static freelist_idx_t next_random_slot(union freelist_init_state *state)
  2065. {
  2066. if (state->pos >= state->count)
  2067. state->pos = 0;
  2068. return state->list[state->pos++];
  2069. }
  2070. /* Swap two freelist entries */
  2071. static void swap_free_obj(struct slab *slab, unsigned int a, unsigned int b)
  2072. {
  2073. swap(((freelist_idx_t *) slab->freelist)[a],
  2074. ((freelist_idx_t *) slab->freelist)[b]);
  2075. }
  2076. /*
  2077. * Shuffle the freelist initialization state based on pre-computed lists.
  2078. * return true if the list was successfully shuffled, false otherwise.
  2079. */
  2080. static bool shuffle_freelist(struct kmem_cache *cachep, struct slab *slab)
  2081. {
  2082. unsigned int objfreelist = 0, i, rand, count = cachep->num;
  2083. union freelist_init_state state;
  2084. bool precomputed;
  2085. if (count < 2)
  2086. return false;
  2087. precomputed = freelist_state_initialize(&state, cachep, count);
  2088. /* Take a random entry as the objfreelist */
  2089. if (OBJFREELIST_SLAB(cachep)) {
  2090. if (!precomputed)
  2091. objfreelist = count - 1;
  2092. else
  2093. objfreelist = next_random_slot(&state);
  2094. slab->freelist = index_to_obj(cachep, slab, objfreelist) +
  2095. obj_offset(cachep);
  2096. count--;
  2097. }
  2098. /*
  2099. * On early boot, generate the list dynamically.
  2100. * Later use a pre-computed list for speed.
  2101. */
  2102. if (!precomputed) {
  2103. for (i = 0; i < count; i++)
  2104. set_free_obj(slab, i, i);
  2105. /* Fisher-Yates shuffle */
  2106. for (i = count - 1; i > 0; i--) {
  2107. rand = prandom_u32_state(&state.rnd_state);
  2108. rand %= (i + 1);
  2109. swap_free_obj(slab, i, rand);
  2110. }
  2111. } else {
  2112. for (i = 0; i < count; i++)
  2113. set_free_obj(slab, i, next_random_slot(&state));
  2114. }
  2115. if (OBJFREELIST_SLAB(cachep))
  2116. set_free_obj(slab, cachep->num - 1, objfreelist);
  2117. return true;
  2118. }
  2119. #else
  2120. static inline bool shuffle_freelist(struct kmem_cache *cachep,
  2121. struct slab *slab)
  2122. {
  2123. return false;
  2124. }
  2125. #endif /* CONFIG_SLAB_FREELIST_RANDOM */
  2126. static void cache_init_objs(struct kmem_cache *cachep,
  2127. struct slab *slab)
  2128. {
  2129. int i;
  2130. void *objp;
  2131. bool shuffled;
  2132. cache_init_objs_debug(cachep, slab);
  2133. /* Try to randomize the freelist if enabled */
  2134. shuffled = shuffle_freelist(cachep, slab);
  2135. if (!shuffled && OBJFREELIST_SLAB(cachep)) {
  2136. slab->freelist = index_to_obj(cachep, slab, cachep->num - 1) +
  2137. obj_offset(cachep);
  2138. }
  2139. for (i = 0; i < cachep->num; i++) {
  2140. objp = index_to_obj(cachep, slab, i);
  2141. objp = kasan_init_slab_obj(cachep, objp);
  2142. /* constructor could break poison info */
  2143. if (DEBUG == 0 && cachep->ctor) {
  2144. kasan_unpoison_object_data(cachep, objp);
  2145. cachep->ctor(objp);
  2146. kasan_poison_object_data(cachep, objp);
  2147. }
  2148. if (!shuffled)
  2149. set_free_obj(slab, i, i);
  2150. }
  2151. }
  2152. static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slab)
  2153. {
  2154. void *objp;
  2155. objp = index_to_obj(cachep, slab, get_free_obj(slab, slab->active));
  2156. slab->active++;
  2157. return objp;
  2158. }
  2159. static void slab_put_obj(struct kmem_cache *cachep,
  2160. struct slab *slab, void *objp)
  2161. {
  2162. unsigned int objnr = obj_to_index(cachep, slab, objp);
  2163. #if DEBUG
  2164. unsigned int i;
  2165. /* Verify double free bug */
  2166. for (i = slab->active; i < cachep->num; i++) {
  2167. if (get_free_obj(slab, i) == objnr) {
  2168. pr_err("slab: double free detected in cache '%s', objp %px\n",
  2169. cachep->name, objp);
  2170. BUG();
  2171. }
  2172. }
  2173. #endif
  2174. slab->active--;
  2175. if (!slab->freelist)
  2176. slab->freelist = objp + obj_offset(cachep);
  2177. set_free_obj(slab, slab->active, objnr);
  2178. }
  2179. /*
  2180. * Grow (by 1) the number of slabs within a cache. This is called by
  2181. * kmem_cache_alloc() when there are no active objs left in a cache.
  2182. */
  2183. static struct slab *cache_grow_begin(struct kmem_cache *cachep,
  2184. gfp_t flags, int nodeid)
  2185. {
  2186. void *freelist;
  2187. size_t offset;
  2188. gfp_t local_flags;
  2189. int slab_node;
  2190. struct kmem_cache_node *n;
  2191. struct slab *slab;
  2192. /*
  2193. * Be lazy and only check for valid flags here, keeping it out of the
  2194. * critical path in kmem_cache_alloc().
  2195. */
  2196. if (unlikely(flags & GFP_SLAB_BUG_MASK))
  2197. flags = kmalloc_fix_flags(flags);
  2198. WARN_ON_ONCE(cachep->ctor && (flags & __GFP_ZERO));
  2199. local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
  2200. check_irq_off();
  2201. if (gfpflags_allow_blocking(local_flags))
  2202. local_irq_enable();
  2203. /*
  2204. * Get mem for the objs. Attempt to allocate a physical page from
  2205. * 'nodeid'.
  2206. */
  2207. slab = kmem_getpages(cachep, local_flags, nodeid);
  2208. if (!slab)
  2209. goto failed;
  2210. slab_node = slab_nid(slab);
  2211. n = get_node(cachep, slab_node);
  2212. /* Get colour for the slab, and cal the next value. */
  2213. n->colour_next++;
  2214. if (n->colour_next >= cachep->colour)
  2215. n->colour_next = 0;
  2216. offset = n->colour_next;
  2217. if (offset >= cachep->colour)
  2218. offset = 0;
  2219. offset *= cachep->colour_off;
  2220. /*
  2221. * Call kasan_poison_slab() before calling alloc_slabmgmt(), so
  2222. * page_address() in the latter returns a non-tagged pointer,
  2223. * as it should be for slab pages.
  2224. */
  2225. kasan_poison_slab(slab);
  2226. /* Get slab management. */
  2227. freelist = alloc_slabmgmt(cachep, slab, offset,
  2228. local_flags & ~GFP_CONSTRAINT_MASK, slab_node);
  2229. if (OFF_SLAB(cachep) && !freelist)
  2230. goto opps1;
  2231. slab->slab_cache = cachep;
  2232. slab->freelist = freelist;
  2233. cache_init_objs(cachep, slab);
  2234. if (gfpflags_allow_blocking(local_flags))
  2235. local_irq_disable();
  2236. return slab;
  2237. opps1:
  2238. kmem_freepages(cachep, slab);
  2239. failed:
  2240. if (gfpflags_allow_blocking(local_flags))
  2241. local_irq_disable();
  2242. return NULL;
  2243. }
  2244. static void cache_grow_end(struct kmem_cache *cachep, struct slab *slab)
  2245. {
  2246. struct kmem_cache_node *n;
  2247. void *list = NULL;
  2248. check_irq_off();
  2249. if (!slab)
  2250. return;
  2251. INIT_LIST_HEAD(&slab->slab_list);
  2252. n = get_node(cachep, slab_nid(slab));
  2253. spin_lock(&n->list_lock);
  2254. n->total_slabs++;
  2255. if (!slab->active) {
  2256. list_add_tail(&slab->slab_list, &n->slabs_free);
  2257. n->free_slabs++;
  2258. } else
  2259. fixup_slab_list(cachep, n, slab, &list);
  2260. STATS_INC_GROWN(cachep);
  2261. n->free_objects += cachep->num - slab->active;
  2262. spin_unlock(&n->list_lock);
  2263. fixup_objfreelist_debug(cachep, &list);
  2264. }
  2265. #if DEBUG
  2266. /*
  2267. * Perform extra freeing checks:
  2268. * - detect bad pointers.
  2269. * - POISON/RED_ZONE checking
  2270. */
  2271. static void kfree_debugcheck(const void *objp)
  2272. {
  2273. if (!virt_addr_valid(objp)) {
  2274. pr_err("kfree_debugcheck: out of range ptr %lxh\n",
  2275. (unsigned long)objp);
  2276. BUG();
  2277. }
  2278. }
  2279. static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
  2280. {
  2281. unsigned long long redzone1, redzone2;
  2282. redzone1 = *dbg_redzone1(cache, obj);
  2283. redzone2 = *dbg_redzone2(cache, obj);
  2284. /*
  2285. * Redzone is ok.
  2286. */
  2287. if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
  2288. return;
  2289. if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
  2290. slab_error(cache, "double free detected");
  2291. else
  2292. slab_error(cache, "memory outside object was overwritten");
  2293. pr_err("%px: redzone 1:0x%llx, redzone 2:0x%llx\n",
  2294. obj, redzone1, redzone2);
  2295. }
  2296. static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
  2297. unsigned long caller)
  2298. {
  2299. unsigned int objnr;
  2300. struct slab *slab;
  2301. BUG_ON(virt_to_cache(objp) != cachep);
  2302. objp -= obj_offset(cachep);
  2303. kfree_debugcheck(objp);
  2304. slab = virt_to_slab(objp);
  2305. if (cachep->flags & SLAB_RED_ZONE) {
  2306. verify_redzone_free(cachep, objp);
  2307. *dbg_redzone1(cachep, objp) = RED_INACTIVE;
  2308. *dbg_redzone2(cachep, objp) = RED_INACTIVE;
  2309. }
  2310. if (cachep->flags & SLAB_STORE_USER)
  2311. *dbg_userword(cachep, objp) = (void *)caller;
  2312. objnr = obj_to_index(cachep, slab, objp);
  2313. BUG_ON(objnr >= cachep->num);
  2314. BUG_ON(objp != index_to_obj(cachep, slab, objnr));
  2315. if (cachep->flags & SLAB_POISON) {
  2316. poison_obj(cachep, objp, POISON_FREE);
  2317. slab_kernel_map(cachep, objp, 0);
  2318. }
  2319. return objp;
  2320. }
  2321. #else
  2322. #define kfree_debugcheck(x) do { } while(0)
  2323. #define cache_free_debugcheck(x, objp, z) (objp)
  2324. #endif
  2325. static inline void fixup_objfreelist_debug(struct kmem_cache *cachep,
  2326. void **list)
  2327. {
  2328. #if DEBUG
  2329. void *next = *list;
  2330. void *objp;
  2331. while (next) {
  2332. objp = next - obj_offset(cachep);
  2333. next = *(void **)next;
  2334. poison_obj(cachep, objp, POISON_FREE);
  2335. }
  2336. #endif
  2337. }
  2338. static inline void fixup_slab_list(struct kmem_cache *cachep,
  2339. struct kmem_cache_node *n, struct slab *slab,
  2340. void **list)
  2341. {
  2342. /* move slabp to correct slabp list: */
  2343. list_del(&slab->slab_list);
  2344. if (slab->active == cachep->num) {
  2345. list_add(&slab->slab_list, &n->slabs_full);
  2346. if (OBJFREELIST_SLAB(cachep)) {
  2347. #if DEBUG
  2348. /* Poisoning will be done without holding the lock */
  2349. if (cachep->flags & SLAB_POISON) {
  2350. void **objp = slab->freelist;
  2351. *objp = *list;
  2352. *list = objp;
  2353. }
  2354. #endif
  2355. slab->freelist = NULL;
  2356. }
  2357. } else
  2358. list_add(&slab->slab_list, &n->slabs_partial);
  2359. }
  2360. /* Try to find non-pfmemalloc slab if needed */
  2361. static noinline struct slab *get_valid_first_slab(struct kmem_cache_node *n,
  2362. struct slab *slab, bool pfmemalloc)
  2363. {
  2364. if (!slab)
  2365. return NULL;
  2366. if (pfmemalloc)
  2367. return slab;
  2368. if (!slab_test_pfmemalloc(slab))
  2369. return slab;
  2370. /* No need to keep pfmemalloc slab if we have enough free objects */
  2371. if (n->free_objects > n->free_limit) {
  2372. slab_clear_pfmemalloc(slab);
  2373. return slab;
  2374. }
  2375. /* Move pfmemalloc slab to the end of list to speed up next search */
  2376. list_del(&slab->slab_list);
  2377. if (!slab->active) {
  2378. list_add_tail(&slab->slab_list, &n->slabs_free);
  2379. n->free_slabs++;
  2380. } else
  2381. list_add_tail(&slab->slab_list, &n->slabs_partial);
  2382. list_for_each_entry(slab, &n->slabs_partial, slab_list) {
  2383. if (!slab_test_pfmemalloc(slab))
  2384. return slab;
  2385. }
  2386. n->free_touched = 1;
  2387. list_for_each_entry(slab, &n->slabs_free, slab_list) {
  2388. if (!slab_test_pfmemalloc(slab)) {
  2389. n->free_slabs--;
  2390. return slab;
  2391. }
  2392. }
  2393. return NULL;
  2394. }
  2395. static struct slab *get_first_slab(struct kmem_cache_node *n, bool pfmemalloc)
  2396. {
  2397. struct slab *slab;
  2398. assert_spin_locked(&n->list_lock);
  2399. slab = list_first_entry_or_null(&n->slabs_partial, struct slab,
  2400. slab_list);
  2401. if (!slab) {
  2402. n->free_touched = 1;
  2403. slab = list_first_entry_or_null(&n->slabs_free, struct slab,
  2404. slab_list);
  2405. if (slab)
  2406. n->free_slabs--;
  2407. }
  2408. if (sk_memalloc_socks())
  2409. slab = get_valid_first_slab(n, slab, pfmemalloc);
  2410. return slab;
  2411. }
  2412. static noinline void *cache_alloc_pfmemalloc(struct kmem_cache *cachep,
  2413. struct kmem_cache_node *n, gfp_t flags)
  2414. {
  2415. struct slab *slab;
  2416. void *obj;
  2417. void *list = NULL;
  2418. if (!gfp_pfmemalloc_allowed(flags))
  2419. return NULL;
  2420. spin_lock(&n->list_lock);
  2421. slab = get_first_slab(n, true);
  2422. if (!slab) {
  2423. spin_unlock(&n->list_lock);
  2424. return NULL;
  2425. }
  2426. obj = slab_get_obj(cachep, slab);
  2427. n->free_objects--;
  2428. fixup_slab_list(cachep, n, slab, &list);
  2429. spin_unlock(&n->list_lock);
  2430. fixup_objfreelist_debug(cachep, &list);
  2431. return obj;
  2432. }
  2433. /*
  2434. * Slab list should be fixed up by fixup_slab_list() for existing slab
  2435. * or cache_grow_end() for new slab
  2436. */
  2437. static __always_inline int alloc_block(struct kmem_cache *cachep,
  2438. struct array_cache *ac, struct slab *slab, int batchcount)
  2439. {
  2440. /*
  2441. * There must be at least one object available for
  2442. * allocation.
  2443. */
  2444. BUG_ON(slab->active >= cachep->num);
  2445. while (slab->active < cachep->num && batchcount--) {
  2446. STATS_INC_ALLOCED(cachep);
  2447. STATS_INC_ACTIVE(cachep);
  2448. STATS_SET_HIGH(cachep);
  2449. ac->entry[ac->avail++] = slab_get_obj(cachep, slab);
  2450. }
  2451. return batchcount;
  2452. }
  2453. static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)
  2454. {
  2455. int batchcount;
  2456. struct kmem_cache_node *n;
  2457. struct array_cache *ac, *shared;
  2458. int node;
  2459. void *list = NULL;
  2460. struct slab *slab;
  2461. check_irq_off();
  2462. node = numa_mem_id();
  2463. ac = cpu_cache_get(cachep);
  2464. batchcount = ac->batchcount;
  2465. if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
  2466. /*
  2467. * If there was little recent activity on this cache, then
  2468. * perform only a partial refill. Otherwise we could generate
  2469. * refill bouncing.
  2470. */
  2471. batchcount = BATCHREFILL_LIMIT;
  2472. }
  2473. n = get_node(cachep, node);
  2474. BUG_ON(ac->avail > 0 || !n);
  2475. shared = READ_ONCE(n->shared);
  2476. if (!n->free_objects && (!shared || !shared->avail))
  2477. goto direct_grow;
  2478. spin_lock(&n->list_lock);
  2479. shared = READ_ONCE(n->shared);
  2480. /* See if we can refill from the shared array */
  2481. if (shared && transfer_objects(ac, shared, batchcount)) {
  2482. shared->touched = 1;
  2483. goto alloc_done;
  2484. }
  2485. while (batchcount > 0) {
  2486. /* Get slab alloc is to come from. */
  2487. slab = get_first_slab(n, false);
  2488. if (!slab)
  2489. goto must_grow;
  2490. check_spinlock_acquired(cachep);
  2491. batchcount = alloc_block(cachep, ac, slab, batchcount);
  2492. fixup_slab_list(cachep, n, slab, &list);
  2493. }
  2494. must_grow:
  2495. n->free_objects -= ac->avail;
  2496. alloc_done:
  2497. spin_unlock(&n->list_lock);
  2498. fixup_objfreelist_debug(cachep, &list);
  2499. direct_grow:
  2500. if (unlikely(!ac->avail)) {
  2501. /* Check if we can use obj in pfmemalloc slab */
  2502. if (sk_memalloc_socks()) {
  2503. void *obj = cache_alloc_pfmemalloc(cachep, n, flags);
  2504. if (obj)
  2505. return obj;
  2506. }
  2507. slab = cache_grow_begin(cachep, gfp_exact_node(flags), node);
  2508. /*
  2509. * cache_grow_begin() can reenable interrupts,
  2510. * then ac could change.
  2511. */
  2512. ac = cpu_cache_get(cachep);
  2513. if (!ac->avail && slab)
  2514. alloc_block(cachep, ac, slab, batchcount);
  2515. cache_grow_end(cachep, slab);
  2516. if (!ac->avail)
  2517. return NULL;
  2518. }
  2519. ac->touched = 1;
  2520. return ac->entry[--ac->avail];
  2521. }
  2522. #if DEBUG
  2523. static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
  2524. gfp_t flags, void *objp, unsigned long caller)
  2525. {
  2526. WARN_ON_ONCE(cachep->ctor && (flags & __GFP_ZERO));
  2527. if (!objp || is_kfence_address(objp))
  2528. return objp;
  2529. if (cachep->flags & SLAB_POISON) {
  2530. check_poison_obj(cachep, objp);
  2531. slab_kernel_map(cachep, objp, 1);
  2532. poison_obj(cachep, objp, POISON_INUSE);
  2533. }
  2534. if (cachep->flags & SLAB_STORE_USER)
  2535. *dbg_userword(cachep, objp) = (void *)caller;
  2536. if (cachep->flags & SLAB_RED_ZONE) {
  2537. if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
  2538. *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
  2539. slab_error(cachep, "double free, or memory outside object was overwritten");
  2540. pr_err("%px: redzone 1:0x%llx, redzone 2:0x%llx\n",
  2541. objp, *dbg_redzone1(cachep, objp),
  2542. *dbg_redzone2(cachep, objp));
  2543. }
  2544. *dbg_redzone1(cachep, objp) = RED_ACTIVE;
  2545. *dbg_redzone2(cachep, objp) = RED_ACTIVE;
  2546. }
  2547. objp += obj_offset(cachep);
  2548. if (cachep->ctor && cachep->flags & SLAB_POISON)
  2549. cachep->ctor(objp);
  2550. if ((unsigned long)objp & (arch_slab_minalign() - 1)) {
  2551. pr_err("0x%px: not aligned to arch_slab_minalign()=%u\n", objp,
  2552. arch_slab_minalign());
  2553. }
  2554. return objp;
  2555. }
  2556. #else
  2557. #define cache_alloc_debugcheck_after(a, b, objp, d) (objp)
  2558. #endif
  2559. static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
  2560. {
  2561. void *objp;
  2562. struct array_cache *ac;
  2563. check_irq_off();
  2564. ac = cpu_cache_get(cachep);
  2565. if (likely(ac->avail)) {
  2566. ac->touched = 1;
  2567. objp = ac->entry[--ac->avail];
  2568. STATS_INC_ALLOCHIT(cachep);
  2569. goto out;
  2570. }
  2571. STATS_INC_ALLOCMISS(cachep);
  2572. objp = cache_alloc_refill(cachep, flags);
  2573. /*
  2574. * the 'ac' may be updated by cache_alloc_refill(),
  2575. * and kmemleak_erase() requires its correct value.
  2576. */
  2577. ac = cpu_cache_get(cachep);
  2578. out:
  2579. /*
  2580. * To avoid a false negative, if an object that is in one of the
  2581. * per-CPU caches is leaked, we need to make sure kmemleak doesn't
  2582. * treat the array pointers as a reference to the object.
  2583. */
  2584. if (objp)
  2585. kmemleak_erase(&ac->entry[ac->avail]);
  2586. return objp;
  2587. }
  2588. #ifdef CONFIG_NUMA
  2589. static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
  2590. /*
  2591. * Try allocating on another node if PFA_SPREAD_SLAB is a mempolicy is set.
  2592. *
  2593. * If we are in_interrupt, then process context, including cpusets and
  2594. * mempolicy, may not apply and should not be used for allocation policy.
  2595. */
  2596. static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
  2597. {
  2598. int nid_alloc, nid_here;
  2599. if (in_interrupt() || (flags & __GFP_THISNODE))
  2600. return NULL;
  2601. nid_alloc = nid_here = numa_mem_id();
  2602. if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
  2603. nid_alloc = cpuset_slab_spread_node();
  2604. else if (current->mempolicy)
  2605. nid_alloc = mempolicy_slab_node();
  2606. if (nid_alloc != nid_here)
  2607. return ____cache_alloc_node(cachep, flags, nid_alloc);
  2608. return NULL;
  2609. }
  2610. /*
  2611. * Fallback function if there was no memory available and no objects on a
  2612. * certain node and fall back is permitted. First we scan all the
  2613. * available node for available objects. If that fails then we
  2614. * perform an allocation without specifying a node. This allows the page
  2615. * allocator to do its reclaim / fallback magic. We then insert the
  2616. * slab into the proper nodelist and then allocate from it.
  2617. */
  2618. static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
  2619. {
  2620. struct zonelist *zonelist;
  2621. struct zoneref *z;
  2622. struct zone *zone;
  2623. enum zone_type highest_zoneidx = gfp_zone(flags);
  2624. void *obj = NULL;
  2625. struct slab *slab;
  2626. int nid;
  2627. unsigned int cpuset_mems_cookie;
  2628. if (flags & __GFP_THISNODE)
  2629. return NULL;
  2630. retry_cpuset:
  2631. cpuset_mems_cookie = read_mems_allowed_begin();
  2632. zonelist = node_zonelist(mempolicy_slab_node(), flags);
  2633. retry:
  2634. /*
  2635. * Look through allowed nodes for objects available
  2636. * from existing per node queues.
  2637. */
  2638. for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
  2639. nid = zone_to_nid(zone);
  2640. if (cpuset_zone_allowed(zone, flags) &&
  2641. get_node(cache, nid) &&
  2642. get_node(cache, nid)->free_objects) {
  2643. obj = ____cache_alloc_node(cache,
  2644. gfp_exact_node(flags), nid);
  2645. if (obj)
  2646. break;
  2647. }
  2648. }
  2649. if (!obj) {
  2650. /*
  2651. * This allocation will be performed within the constraints
  2652. * of the current cpuset / memory policy requirements.
  2653. * We may trigger various forms of reclaim on the allowed
  2654. * set and go into memory reserves if necessary.
  2655. */
  2656. slab = cache_grow_begin(cache, flags, numa_mem_id());
  2657. cache_grow_end(cache, slab);
  2658. if (slab) {
  2659. nid = slab_nid(slab);
  2660. obj = ____cache_alloc_node(cache,
  2661. gfp_exact_node(flags), nid);
  2662. /*
  2663. * Another processor may allocate the objects in
  2664. * the slab since we are not holding any locks.
  2665. */
  2666. if (!obj)
  2667. goto retry;
  2668. }
  2669. }
  2670. if (unlikely(!obj && read_mems_allowed_retry(cpuset_mems_cookie)))
  2671. goto retry_cpuset;
  2672. return obj;
  2673. }
  2674. /*
  2675. * An interface to enable slab creation on nodeid
  2676. */
  2677. static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
  2678. int nodeid)
  2679. {
  2680. struct slab *slab;
  2681. struct kmem_cache_node *n;
  2682. void *obj = NULL;
  2683. void *list = NULL;
  2684. VM_BUG_ON(nodeid < 0 || nodeid >= MAX_NUMNODES);
  2685. n = get_node(cachep, nodeid);
  2686. BUG_ON(!n);
  2687. check_irq_off();
  2688. spin_lock(&n->list_lock);
  2689. slab = get_first_slab(n, false);
  2690. if (!slab)
  2691. goto must_grow;
  2692. check_spinlock_acquired_node(cachep, nodeid);
  2693. STATS_INC_NODEALLOCS(cachep);
  2694. STATS_INC_ACTIVE(cachep);
  2695. STATS_SET_HIGH(cachep);
  2696. BUG_ON(slab->active == cachep->num);
  2697. obj = slab_get_obj(cachep, slab);
  2698. n->free_objects--;
  2699. fixup_slab_list(cachep, n, slab, &list);
  2700. spin_unlock(&n->list_lock);
  2701. fixup_objfreelist_debug(cachep, &list);
  2702. return obj;
  2703. must_grow:
  2704. spin_unlock(&n->list_lock);
  2705. slab = cache_grow_begin(cachep, gfp_exact_node(flags), nodeid);
  2706. if (slab) {
  2707. /* This slab isn't counted yet so don't update free_objects */
  2708. obj = slab_get_obj(cachep, slab);
  2709. }
  2710. cache_grow_end(cachep, slab);
  2711. return obj ? obj : fallback_alloc(cachep, flags);
  2712. }
  2713. static __always_inline void *
  2714. __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags, int nodeid)
  2715. {
  2716. void *objp = NULL;
  2717. int slab_node = numa_mem_id();
  2718. if (nodeid == NUMA_NO_NODE) {
  2719. if (current->mempolicy || cpuset_do_slab_mem_spread()) {
  2720. objp = alternate_node_alloc(cachep, flags);
  2721. if (objp)
  2722. goto out;
  2723. }
  2724. /*
  2725. * Use the locally cached objects if possible.
  2726. * However ____cache_alloc does not allow fallback
  2727. * to other nodes. It may fail while we still have
  2728. * objects on other nodes available.
  2729. */
  2730. objp = ____cache_alloc(cachep, flags);
  2731. nodeid = slab_node;
  2732. } else if (nodeid == slab_node) {
  2733. objp = ____cache_alloc(cachep, flags);
  2734. } else if (!get_node(cachep, nodeid)) {
  2735. /* Node not bootstrapped yet */
  2736. objp = fallback_alloc(cachep, flags);
  2737. goto out;
  2738. }
  2739. /*
  2740. * We may just have run out of memory on the local node.
  2741. * ____cache_alloc_node() knows how to locate memory on other nodes
  2742. */
  2743. if (!objp)
  2744. objp = ____cache_alloc_node(cachep, flags, nodeid);
  2745. out:
  2746. return objp;
  2747. }
  2748. #else
  2749. static __always_inline void *
  2750. __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags, int nodeid __maybe_unused)
  2751. {
  2752. return ____cache_alloc(cachep, flags);
  2753. }
  2754. #endif /* CONFIG_NUMA */
  2755. static __always_inline void *
  2756. slab_alloc_node(struct kmem_cache *cachep, struct list_lru *lru, gfp_t flags,
  2757. int nodeid, size_t orig_size, unsigned long caller)
  2758. {
  2759. unsigned long save_flags;
  2760. void *objp;
  2761. struct obj_cgroup *objcg = NULL;
  2762. bool init = false;
  2763. flags &= gfp_allowed_mask;
  2764. cachep = slab_pre_alloc_hook(cachep, lru, &objcg, 1, flags);
  2765. if (unlikely(!cachep))
  2766. return NULL;
  2767. objp = kfence_alloc(cachep, orig_size, flags);
  2768. if (unlikely(objp))
  2769. goto out;
  2770. local_irq_save(save_flags);
  2771. objp = __do_cache_alloc(cachep, flags, nodeid);
  2772. local_irq_restore(save_flags);
  2773. objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
  2774. prefetchw(objp);
  2775. init = slab_want_init_on_alloc(flags, cachep);
  2776. out:
  2777. slab_post_alloc_hook(cachep, objcg, flags, 1, &objp, init);
  2778. return objp;
  2779. }
  2780. static __always_inline void *
  2781. slab_alloc(struct kmem_cache *cachep, struct list_lru *lru, gfp_t flags,
  2782. size_t orig_size, unsigned long caller)
  2783. {
  2784. return slab_alloc_node(cachep, lru, flags, NUMA_NO_NODE, orig_size,
  2785. caller);
  2786. }
  2787. /*
  2788. * Caller needs to acquire correct kmem_cache_node's list_lock
  2789. * @list: List of detached free slabs should be freed by caller
  2790. */
  2791. static void free_block(struct kmem_cache *cachep, void **objpp,
  2792. int nr_objects, int node, struct list_head *list)
  2793. {
  2794. int i;
  2795. struct kmem_cache_node *n = get_node(cachep, node);
  2796. struct slab *slab;
  2797. n->free_objects += nr_objects;
  2798. for (i = 0; i < nr_objects; i++) {
  2799. void *objp;
  2800. struct slab *slab;
  2801. objp = objpp[i];
  2802. slab = virt_to_slab(objp);
  2803. list_del(&slab->slab_list);
  2804. check_spinlock_acquired_node(cachep, node);
  2805. slab_put_obj(cachep, slab, objp);
  2806. STATS_DEC_ACTIVE(cachep);
  2807. /* fixup slab chains */
  2808. if (slab->active == 0) {
  2809. list_add(&slab->slab_list, &n->slabs_free);
  2810. n->free_slabs++;
  2811. } else {
  2812. /* Unconditionally move a slab to the end of the
  2813. * partial list on free - maximum time for the
  2814. * other objects to be freed, too.
  2815. */
  2816. list_add_tail(&slab->slab_list, &n->slabs_partial);
  2817. }
  2818. }
  2819. while (n->free_objects > n->free_limit && !list_empty(&n->slabs_free)) {
  2820. n->free_objects -= cachep->num;
  2821. slab = list_last_entry(&n->slabs_free, struct slab, slab_list);
  2822. list_move(&slab->slab_list, list);
  2823. n->free_slabs--;
  2824. n->total_slabs--;
  2825. }
  2826. }
  2827. static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
  2828. {
  2829. int batchcount;
  2830. struct kmem_cache_node *n;
  2831. int node = numa_mem_id();
  2832. LIST_HEAD(list);
  2833. batchcount = ac->batchcount;
  2834. check_irq_off();
  2835. n = get_node(cachep, node);
  2836. spin_lock(&n->list_lock);
  2837. if (n->shared) {
  2838. struct array_cache *shared_array = n->shared;
  2839. int max = shared_array->limit - shared_array->avail;
  2840. if (max) {
  2841. if (batchcount > max)
  2842. batchcount = max;
  2843. memcpy(&(shared_array->entry[shared_array->avail]),
  2844. ac->entry, sizeof(void *) * batchcount);
  2845. shared_array->avail += batchcount;
  2846. goto free_done;
  2847. }
  2848. }
  2849. free_block(cachep, ac->entry, batchcount, node, &list);
  2850. free_done:
  2851. #if STATS
  2852. {
  2853. int i = 0;
  2854. struct slab *slab;
  2855. list_for_each_entry(slab, &n->slabs_free, slab_list) {
  2856. BUG_ON(slab->active);
  2857. i++;
  2858. }
  2859. STATS_SET_FREEABLE(cachep, i);
  2860. }
  2861. #endif
  2862. spin_unlock(&n->list_lock);
  2863. ac->avail -= batchcount;
  2864. memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
  2865. slabs_destroy(cachep, &list);
  2866. }
  2867. /*
  2868. * Release an obj back to its cache. If the obj has a constructed state, it must
  2869. * be in this state _before_ it is released. Called with disabled ints.
  2870. */
  2871. static __always_inline void __cache_free(struct kmem_cache *cachep, void *objp,
  2872. unsigned long caller)
  2873. {
  2874. bool init;
  2875. memcg_slab_free_hook(cachep, virt_to_slab(objp), &objp, 1);
  2876. if (is_kfence_address(objp)) {
  2877. kmemleak_free_recursive(objp, cachep->flags);
  2878. __kfence_free(objp);
  2879. return;
  2880. }
  2881. /*
  2882. * As memory initialization might be integrated into KASAN,
  2883. * kasan_slab_free and initialization memset must be
  2884. * kept together to avoid discrepancies in behavior.
  2885. */
  2886. init = slab_want_init_on_free(cachep);
  2887. if (init && !kasan_has_integrated_init())
  2888. memset(objp, 0, cachep->object_size);
  2889. /* KASAN might put objp into memory quarantine, delaying its reuse. */
  2890. if (kasan_slab_free(cachep, objp, init))
  2891. return;
  2892. /* Use KCSAN to help debug racy use-after-free. */
  2893. if (!(cachep->flags & SLAB_TYPESAFE_BY_RCU))
  2894. __kcsan_check_access(objp, cachep->object_size,
  2895. KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
  2896. ___cache_free(cachep, objp, caller);
  2897. }
  2898. void ___cache_free(struct kmem_cache *cachep, void *objp,
  2899. unsigned long caller)
  2900. {
  2901. struct array_cache *ac = cpu_cache_get(cachep);
  2902. check_irq_off();
  2903. kmemleak_free_recursive(objp, cachep->flags);
  2904. objp = cache_free_debugcheck(cachep, objp, caller);
  2905. /*
  2906. * Skip calling cache_free_alien() when the platform is not numa.
  2907. * This will avoid cache misses that happen while accessing slabp (which
  2908. * is per page memory reference) to get nodeid. Instead use a global
  2909. * variable to skip the call, which is mostly likely to be present in
  2910. * the cache.
  2911. */
  2912. if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
  2913. return;
  2914. if (ac->avail < ac->limit) {
  2915. STATS_INC_FREEHIT(cachep);
  2916. } else {
  2917. STATS_INC_FREEMISS(cachep);
  2918. cache_flusharray(cachep, ac);
  2919. }
  2920. if (sk_memalloc_socks()) {
  2921. struct slab *slab = virt_to_slab(objp);
  2922. if (unlikely(slab_test_pfmemalloc(slab))) {
  2923. cache_free_pfmemalloc(cachep, slab, objp);
  2924. return;
  2925. }
  2926. }
  2927. __free_one(ac, objp);
  2928. }
  2929. static __always_inline
  2930. void *__kmem_cache_alloc_lru(struct kmem_cache *cachep, struct list_lru *lru,
  2931. gfp_t flags)
  2932. {
  2933. void *ret = slab_alloc(cachep, lru, flags, cachep->object_size, _RET_IP_);
  2934. trace_kmem_cache_alloc(_RET_IP_, ret, cachep, flags, NUMA_NO_NODE);
  2935. return ret;
  2936. }
  2937. /**
  2938. * kmem_cache_alloc - Allocate an object
  2939. * @cachep: The cache to allocate from.
  2940. * @flags: See kmalloc().
  2941. *
  2942. * Allocate an object from this cache. The flags are only relevant
  2943. * if the cache has no available objects.
  2944. *
  2945. * Return: pointer to the new object or %NULL in case of error
  2946. */
  2947. void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
  2948. {
  2949. return __kmem_cache_alloc_lru(cachep, NULL, flags);
  2950. }
  2951. EXPORT_SYMBOL(kmem_cache_alloc);
  2952. void *kmem_cache_alloc_lru(struct kmem_cache *cachep, struct list_lru *lru,
  2953. gfp_t flags)
  2954. {
  2955. return __kmem_cache_alloc_lru(cachep, lru, flags);
  2956. }
  2957. EXPORT_SYMBOL(kmem_cache_alloc_lru);
  2958. static __always_inline void
  2959. cache_alloc_debugcheck_after_bulk(struct kmem_cache *s, gfp_t flags,
  2960. size_t size, void **p, unsigned long caller)
  2961. {
  2962. size_t i;
  2963. for (i = 0; i < size; i++)
  2964. p[i] = cache_alloc_debugcheck_after(s, flags, p[i], caller);
  2965. }
  2966. int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
  2967. void **p)
  2968. {
  2969. size_t i;
  2970. struct obj_cgroup *objcg = NULL;
  2971. s = slab_pre_alloc_hook(s, NULL, &objcg, size, flags);
  2972. if (!s)
  2973. return 0;
  2974. local_irq_disable();
  2975. for (i = 0; i < size; i++) {
  2976. void *objp = kfence_alloc(s, s->object_size, flags) ?:
  2977. __do_cache_alloc(s, flags, NUMA_NO_NODE);
  2978. if (unlikely(!objp))
  2979. goto error;
  2980. p[i] = objp;
  2981. }
  2982. local_irq_enable();
  2983. cache_alloc_debugcheck_after_bulk(s, flags, size, p, _RET_IP_);
  2984. /*
  2985. * memcg and kmem_cache debug support and memory initialization.
  2986. * Done outside of the IRQ disabled section.
  2987. */
  2988. slab_post_alloc_hook(s, objcg, flags, size, p,
  2989. slab_want_init_on_alloc(flags, s));
  2990. /* FIXME: Trace call missing. Christoph would like a bulk variant */
  2991. return size;
  2992. error:
  2993. local_irq_enable();
  2994. cache_alloc_debugcheck_after_bulk(s, flags, i, p, _RET_IP_);
  2995. slab_post_alloc_hook(s, objcg, flags, i, p, false);
  2996. kmem_cache_free_bulk(s, i, p);
  2997. return 0;
  2998. }
  2999. EXPORT_SYMBOL(kmem_cache_alloc_bulk);
  3000. /**
  3001. * kmem_cache_alloc_node - Allocate an object on the specified node
  3002. * @cachep: The cache to allocate from.
  3003. * @flags: See kmalloc().
  3004. * @nodeid: node number of the target node.
  3005. *
  3006. * Identical to kmem_cache_alloc but it will allocate memory on the given
  3007. * node, which can improve the performance for cpu bound structures.
  3008. *
  3009. * Fallback to other node is possible if __GFP_THISNODE is not set.
  3010. *
  3011. * Return: pointer to the new object or %NULL in case of error
  3012. */
  3013. void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
  3014. {
  3015. void *ret = slab_alloc_node(cachep, NULL, flags, nodeid, cachep->object_size, _RET_IP_);
  3016. trace_kmem_cache_alloc(_RET_IP_, ret, cachep, flags, nodeid);
  3017. return ret;
  3018. }
  3019. EXPORT_SYMBOL(kmem_cache_alloc_node);
  3020. void *__kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
  3021. int nodeid, size_t orig_size,
  3022. unsigned long caller)
  3023. {
  3024. return slab_alloc_node(cachep, NULL, flags, nodeid,
  3025. orig_size, caller);
  3026. }
  3027. #ifdef CONFIG_PRINTK
  3028. void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
  3029. {
  3030. struct kmem_cache *cachep;
  3031. unsigned int objnr;
  3032. void *objp;
  3033. kpp->kp_ptr = object;
  3034. kpp->kp_slab = slab;
  3035. cachep = slab->slab_cache;
  3036. kpp->kp_slab_cache = cachep;
  3037. objp = object - obj_offset(cachep);
  3038. kpp->kp_data_offset = obj_offset(cachep);
  3039. slab = virt_to_slab(objp);
  3040. objnr = obj_to_index(cachep, slab, objp);
  3041. objp = index_to_obj(cachep, slab, objnr);
  3042. kpp->kp_objp = objp;
  3043. if (DEBUG && cachep->flags & SLAB_STORE_USER)
  3044. kpp->kp_ret = *dbg_userword(cachep, objp);
  3045. }
  3046. #endif
  3047. static __always_inline
  3048. void __do_kmem_cache_free(struct kmem_cache *cachep, void *objp,
  3049. unsigned long caller)
  3050. {
  3051. unsigned long flags;
  3052. local_irq_save(flags);
  3053. debug_check_no_locks_freed(objp, cachep->object_size);
  3054. if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
  3055. debug_check_no_obj_freed(objp, cachep->object_size);
  3056. __cache_free(cachep, objp, caller);
  3057. local_irq_restore(flags);
  3058. }
  3059. void __kmem_cache_free(struct kmem_cache *cachep, void *objp,
  3060. unsigned long caller)
  3061. {
  3062. __do_kmem_cache_free(cachep, objp, caller);
  3063. }
  3064. /**
  3065. * kmem_cache_free - Deallocate an object
  3066. * @cachep: The cache the allocation was from.
  3067. * @objp: The previously allocated object.
  3068. *
  3069. * Free an object which was previously allocated from this
  3070. * cache.
  3071. */
  3072. void kmem_cache_free(struct kmem_cache *cachep, void *objp)
  3073. {
  3074. cachep = cache_from_obj(cachep, objp);
  3075. if (!cachep)
  3076. return;
  3077. trace_kmem_cache_free(_RET_IP_, objp, cachep);
  3078. __do_kmem_cache_free(cachep, objp, _RET_IP_);
  3079. }
  3080. EXPORT_SYMBOL(kmem_cache_free);
  3081. void kmem_cache_free_bulk(struct kmem_cache *orig_s, size_t size, void **p)
  3082. {
  3083. local_irq_disable();
  3084. for (int i = 0; i < size; i++) {
  3085. void *objp = p[i];
  3086. struct kmem_cache *s;
  3087. if (!orig_s) {
  3088. struct folio *folio = virt_to_folio(objp);
  3089. /* called via kfree_bulk */
  3090. if (!folio_test_slab(folio)) {
  3091. local_irq_enable();
  3092. free_large_kmalloc(folio, objp);
  3093. local_irq_disable();
  3094. continue;
  3095. }
  3096. s = folio_slab(folio)->slab_cache;
  3097. } else {
  3098. s = cache_from_obj(orig_s, objp);
  3099. }
  3100. if (!s)
  3101. continue;
  3102. debug_check_no_locks_freed(objp, s->object_size);
  3103. if (!(s->flags & SLAB_DEBUG_OBJECTS))
  3104. debug_check_no_obj_freed(objp, s->object_size);
  3105. __cache_free(s, objp, _RET_IP_);
  3106. }
  3107. local_irq_enable();
  3108. /* FIXME: add tracing */
  3109. }
  3110. EXPORT_SYMBOL(kmem_cache_free_bulk);
  3111. /*
  3112. * This initializes kmem_cache_node or resizes various caches for all nodes.
  3113. */
  3114. static int setup_kmem_cache_nodes(struct kmem_cache *cachep, gfp_t gfp)
  3115. {
  3116. int ret;
  3117. int node;
  3118. struct kmem_cache_node *n;
  3119. for_each_online_node(node) {
  3120. ret = setup_kmem_cache_node(cachep, node, gfp, true);
  3121. if (ret)
  3122. goto fail;
  3123. }
  3124. return 0;
  3125. fail:
  3126. if (!cachep->list.next) {
  3127. /* Cache is not active yet. Roll back what we did */
  3128. node--;
  3129. while (node >= 0) {
  3130. n = get_node(cachep, node);
  3131. if (n) {
  3132. kfree(n->shared);
  3133. free_alien_cache(n->alien);
  3134. kfree(n);
  3135. cachep->node[node] = NULL;
  3136. }
  3137. node--;
  3138. }
  3139. }
  3140. return -ENOMEM;
  3141. }
  3142. /* Always called with the slab_mutex held */
  3143. static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
  3144. int batchcount, int shared, gfp_t gfp)
  3145. {
  3146. struct array_cache __percpu *cpu_cache, *prev;
  3147. int cpu;
  3148. cpu_cache = alloc_kmem_cache_cpus(cachep, limit, batchcount);
  3149. if (!cpu_cache)
  3150. return -ENOMEM;
  3151. prev = cachep->cpu_cache;
  3152. cachep->cpu_cache = cpu_cache;
  3153. /*
  3154. * Without a previous cpu_cache there's no need to synchronize remote
  3155. * cpus, so skip the IPIs.
  3156. */
  3157. if (prev)
  3158. kick_all_cpus_sync();
  3159. check_irq_on();
  3160. cachep->batchcount = batchcount;
  3161. cachep->limit = limit;
  3162. cachep->shared = shared;
  3163. if (!prev)
  3164. goto setup_node;
  3165. for_each_online_cpu(cpu) {
  3166. LIST_HEAD(list);
  3167. int node;
  3168. struct kmem_cache_node *n;
  3169. struct array_cache *ac = per_cpu_ptr(prev, cpu);
  3170. node = cpu_to_mem(cpu);
  3171. n = get_node(cachep, node);
  3172. spin_lock_irq(&n->list_lock);
  3173. free_block(cachep, ac->entry, ac->avail, node, &list);
  3174. spin_unlock_irq(&n->list_lock);
  3175. slabs_destroy(cachep, &list);
  3176. }
  3177. free_percpu(prev);
  3178. setup_node:
  3179. return setup_kmem_cache_nodes(cachep, gfp);
  3180. }
  3181. /* Called with slab_mutex held always */
  3182. static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
  3183. {
  3184. int err;
  3185. int limit = 0;
  3186. int shared = 0;
  3187. int batchcount = 0;
  3188. err = cache_random_seq_create(cachep, cachep->num, gfp);
  3189. if (err)
  3190. goto end;
  3191. /*
  3192. * The head array serves three purposes:
  3193. * - create a LIFO ordering, i.e. return objects that are cache-warm
  3194. * - reduce the number of spinlock operations.
  3195. * - reduce the number of linked list operations on the slab and
  3196. * bufctl chains: array operations are cheaper.
  3197. * The numbers are guessed, we should auto-tune as described by
  3198. * Bonwick.
  3199. */
  3200. if (cachep->size > 131072)
  3201. limit = 1;
  3202. else if (cachep->size > PAGE_SIZE)
  3203. limit = 8;
  3204. else if (cachep->size > 1024)
  3205. limit = 24;
  3206. else if (cachep->size > 256)
  3207. limit = 54;
  3208. else
  3209. limit = 120;
  3210. /*
  3211. * CPU bound tasks (e.g. network routing) can exhibit cpu bound
  3212. * allocation behaviour: Most allocs on one cpu, most free operations
  3213. * on another cpu. For these cases, an efficient object passing between
  3214. * cpus is necessary. This is provided by a shared array. The array
  3215. * replaces Bonwick's magazine layer.
  3216. * On uniprocessor, it's functionally equivalent (but less efficient)
  3217. * to a larger limit. Thus disabled by default.
  3218. */
  3219. shared = 0;
  3220. if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
  3221. shared = 8;
  3222. #if DEBUG
  3223. /*
  3224. * With debugging enabled, large batchcount lead to excessively long
  3225. * periods with disabled local interrupts. Limit the batchcount
  3226. */
  3227. if (limit > 32)
  3228. limit = 32;
  3229. #endif
  3230. batchcount = (limit + 1) / 2;
  3231. err = do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
  3232. end:
  3233. if (err)
  3234. pr_err("enable_cpucache failed for %s, error %d\n",
  3235. cachep->name, -err);
  3236. return err;
  3237. }
  3238. /*
  3239. * Drain an array if it contains any elements taking the node lock only if
  3240. * necessary. Note that the node listlock also protects the array_cache
  3241. * if drain_array() is used on the shared array.
  3242. */
  3243. static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
  3244. struct array_cache *ac, int node)
  3245. {
  3246. LIST_HEAD(list);
  3247. /* ac from n->shared can be freed if we don't hold the slab_mutex. */
  3248. check_mutex_acquired();
  3249. if (!ac || !ac->avail)
  3250. return;
  3251. if (ac->touched) {
  3252. ac->touched = 0;
  3253. return;
  3254. }
  3255. spin_lock_irq(&n->list_lock);
  3256. drain_array_locked(cachep, ac, node, false, &list);
  3257. spin_unlock_irq(&n->list_lock);
  3258. slabs_destroy(cachep, &list);
  3259. }
  3260. /**
  3261. * cache_reap - Reclaim memory from caches.
  3262. * @w: work descriptor
  3263. *
  3264. * Called from workqueue/eventd every few seconds.
  3265. * Purpose:
  3266. * - clear the per-cpu caches for this CPU.
  3267. * - return freeable pages to the main free memory pool.
  3268. *
  3269. * If we cannot acquire the cache chain mutex then just give up - we'll try
  3270. * again on the next iteration.
  3271. */
  3272. static void cache_reap(struct work_struct *w)
  3273. {
  3274. struct kmem_cache *searchp;
  3275. struct kmem_cache_node *n;
  3276. int node = numa_mem_id();
  3277. struct delayed_work *work = to_delayed_work(w);
  3278. if (!mutex_trylock(&slab_mutex))
  3279. /* Give up. Setup the next iteration. */
  3280. goto out;
  3281. list_for_each_entry(searchp, &slab_caches, list) {
  3282. check_irq_on();
  3283. /*
  3284. * We only take the node lock if absolutely necessary and we
  3285. * have established with reasonable certainty that
  3286. * we can do some work if the lock was obtained.
  3287. */
  3288. n = get_node(searchp, node);
  3289. reap_alien(searchp, n);
  3290. drain_array(searchp, n, cpu_cache_get(searchp), node);
  3291. /*
  3292. * These are racy checks but it does not matter
  3293. * if we skip one check or scan twice.
  3294. */
  3295. if (time_after(n->next_reap, jiffies))
  3296. goto next;
  3297. n->next_reap = jiffies + REAPTIMEOUT_NODE;
  3298. drain_array(searchp, n, n->shared, node);
  3299. if (n->free_touched)
  3300. n->free_touched = 0;
  3301. else {
  3302. int freed;
  3303. freed = drain_freelist(searchp, n, (n->free_limit +
  3304. 5 * searchp->num - 1) / (5 * searchp->num));
  3305. STATS_ADD_REAPED(searchp, freed);
  3306. }
  3307. next:
  3308. cond_resched();
  3309. }
  3310. check_irq_on();
  3311. mutex_unlock(&slab_mutex);
  3312. next_reap_node();
  3313. out:
  3314. /* Set up the next iteration */
  3315. schedule_delayed_work_on(smp_processor_id(), work,
  3316. round_jiffies_relative(REAPTIMEOUT_AC));
  3317. }
  3318. void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
  3319. {
  3320. unsigned long active_objs, num_objs, active_slabs;
  3321. unsigned long total_slabs = 0, free_objs = 0, shared_avail = 0;
  3322. unsigned long free_slabs = 0;
  3323. int node;
  3324. struct kmem_cache_node *n;
  3325. for_each_kmem_cache_node(cachep, node, n) {
  3326. check_irq_on();
  3327. spin_lock_irq(&n->list_lock);
  3328. total_slabs += n->total_slabs;
  3329. free_slabs += n->free_slabs;
  3330. free_objs += n->free_objects;
  3331. if (n->shared)
  3332. shared_avail += n->shared->avail;
  3333. spin_unlock_irq(&n->list_lock);
  3334. }
  3335. num_objs = total_slabs * cachep->num;
  3336. active_slabs = total_slabs - free_slabs;
  3337. active_objs = num_objs - free_objs;
  3338. sinfo->active_objs = active_objs;
  3339. sinfo->num_objs = num_objs;
  3340. sinfo->active_slabs = active_slabs;
  3341. sinfo->num_slabs = total_slabs;
  3342. sinfo->shared_avail = shared_avail;
  3343. sinfo->limit = cachep->limit;
  3344. sinfo->batchcount = cachep->batchcount;
  3345. sinfo->shared = cachep->shared;
  3346. sinfo->objects_per_slab = cachep->num;
  3347. sinfo->cache_order = cachep->gfporder;
  3348. }
  3349. EXPORT_SYMBOL_NS_GPL(get_slabinfo, MINIDUMP);
  3350. void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
  3351. {
  3352. #if STATS
  3353. { /* node stats */
  3354. unsigned long high = cachep->high_mark;
  3355. unsigned long allocs = cachep->num_allocations;
  3356. unsigned long grown = cachep->grown;
  3357. unsigned long reaped = cachep->reaped;
  3358. unsigned long errors = cachep->errors;
  3359. unsigned long max_freeable = cachep->max_freeable;
  3360. unsigned long node_allocs = cachep->node_allocs;
  3361. unsigned long node_frees = cachep->node_frees;
  3362. unsigned long overflows = cachep->node_overflow;
  3363. seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu %4lu %4lu %4lu %4lu %4lu",
  3364. allocs, high, grown,
  3365. reaped, errors, max_freeable, node_allocs,
  3366. node_frees, overflows);
  3367. }
  3368. /* cpu stats */
  3369. {
  3370. unsigned long allochit = atomic_read(&cachep->allochit);
  3371. unsigned long allocmiss = atomic_read(&cachep->allocmiss);
  3372. unsigned long freehit = atomic_read(&cachep->freehit);
  3373. unsigned long freemiss = atomic_read(&cachep->freemiss);
  3374. seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
  3375. allochit, allocmiss, freehit, freemiss);
  3376. }
  3377. #endif
  3378. }
  3379. #define MAX_SLABINFO_WRITE 128
  3380. /**
  3381. * slabinfo_write - Tuning for the slab allocator
  3382. * @file: unused
  3383. * @buffer: user buffer
  3384. * @count: data length
  3385. * @ppos: unused
  3386. *
  3387. * Return: %0 on success, negative error code otherwise.
  3388. */
  3389. ssize_t slabinfo_write(struct file *file, const char __user *buffer,
  3390. size_t count, loff_t *ppos)
  3391. {
  3392. char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
  3393. int limit, batchcount, shared, res;
  3394. struct kmem_cache *cachep;
  3395. if (count > MAX_SLABINFO_WRITE)
  3396. return -EINVAL;
  3397. if (copy_from_user(&kbuf, buffer, count))
  3398. return -EFAULT;
  3399. kbuf[MAX_SLABINFO_WRITE] = '\0';
  3400. tmp = strchr(kbuf, ' ');
  3401. if (!tmp)
  3402. return -EINVAL;
  3403. *tmp = '\0';
  3404. tmp++;
  3405. if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
  3406. return -EINVAL;
  3407. /* Find the cache in the chain of caches. */
  3408. mutex_lock(&slab_mutex);
  3409. res = -EINVAL;
  3410. list_for_each_entry(cachep, &slab_caches, list) {
  3411. if (!strcmp(cachep->name, kbuf)) {
  3412. if (limit < 1 || batchcount < 1 ||
  3413. batchcount > limit || shared < 0) {
  3414. res = 0;
  3415. } else {
  3416. res = do_tune_cpucache(cachep, limit,
  3417. batchcount, shared,
  3418. GFP_KERNEL);
  3419. }
  3420. break;
  3421. }
  3422. }
  3423. mutex_unlock(&slab_mutex);
  3424. if (res >= 0)
  3425. res = count;
  3426. return res;
  3427. }
  3428. #ifdef CONFIG_HARDENED_USERCOPY
  3429. /*
  3430. * Rejects incorrectly sized objects and objects that are to be copied
  3431. * to/from userspace but do not fall entirely within the containing slab
  3432. * cache's usercopy region.
  3433. *
  3434. * Returns NULL if check passes, otherwise const char * to name of cache
  3435. * to indicate an error.
  3436. */
  3437. void __check_heap_object(const void *ptr, unsigned long n,
  3438. const struct slab *slab, bool to_user)
  3439. {
  3440. struct kmem_cache *cachep;
  3441. unsigned int objnr;
  3442. unsigned long offset;
  3443. ptr = kasan_reset_tag(ptr);
  3444. /* Find and validate object. */
  3445. cachep = slab->slab_cache;
  3446. objnr = obj_to_index(cachep, slab, (void *)ptr);
  3447. BUG_ON(objnr >= cachep->num);
  3448. /* Find offset within object. */
  3449. if (is_kfence_address(ptr))
  3450. offset = ptr - kfence_object_start(ptr);
  3451. else
  3452. offset = ptr - index_to_obj(cachep, slab, objnr) - obj_offset(cachep);
  3453. /* Allow address range falling entirely within usercopy region. */
  3454. if (offset >= cachep->useroffset &&
  3455. offset - cachep->useroffset <= cachep->usersize &&
  3456. n <= cachep->useroffset - offset + cachep->usersize)
  3457. return;
  3458. usercopy_abort("SLAB object", cachep->name, to_user, offset, n);
  3459. }
  3460. #endif /* CONFIG_HARDENED_USERCOPY */