slab.c 106 KB

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