slab.c 111 KB

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