slab.c 111 KB

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