percpu.c 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * mm/percpu.c - percpu memory allocator
  4. *
  5. * Copyright (C) 2009 SUSE Linux Products GmbH
  6. * Copyright (C) 2009 Tejun Heo <[email protected]>
  7. *
  8. * Copyright (C) 2017 Facebook Inc.
  9. * Copyright (C) 2017 Dennis Zhou <[email protected]>
  10. *
  11. * The percpu allocator handles both static and dynamic areas. Percpu
  12. * areas are allocated in chunks which are divided into units. There is
  13. * a 1-to-1 mapping for units to possible cpus. These units are grouped
  14. * based on NUMA properties of the machine.
  15. *
  16. * c0 c1 c2
  17. * ------------------- ------------------- ------------
  18. * | u0 | u1 | u2 | u3 | | u0 | u1 | u2 | u3 | | u0 | u1 | u
  19. * ------------------- ...... ------------------- .... ------------
  20. *
  21. * Allocation is done by offsets into a unit's address space. Ie., an
  22. * area of 512 bytes at 6k in c1 occupies 512 bytes at 6k in c1:u0,
  23. * c1:u1, c1:u2, etc. On NUMA machines, the mapping may be non-linear
  24. * and even sparse. Access is handled by configuring percpu base
  25. * registers according to the cpu to unit mappings and offsetting the
  26. * base address using pcpu_unit_size.
  27. *
  28. * There is special consideration for the first chunk which must handle
  29. * the static percpu variables in the kernel image as allocation services
  30. * are not online yet. In short, the first chunk is structured like so:
  31. *
  32. * <Static | [Reserved] | Dynamic>
  33. *
  34. * The static data is copied from the original section managed by the
  35. * linker. The reserved section, if non-zero, primarily manages static
  36. * percpu variables from kernel modules. Finally, the dynamic section
  37. * takes care of normal allocations.
  38. *
  39. * The allocator organizes chunks into lists according to free size and
  40. * memcg-awareness. To make a percpu allocation memcg-aware the __GFP_ACCOUNT
  41. * flag should be passed. All memcg-aware allocations are sharing one set
  42. * of chunks and all unaccounted allocations and allocations performed
  43. * by processes belonging to the root memory cgroup are using the second set.
  44. *
  45. * The allocator tries to allocate from the fullest chunk first. Each chunk
  46. * is managed by a bitmap with metadata blocks. The allocation map is updated
  47. * on every allocation and free to reflect the current state while the boundary
  48. * map is only updated on allocation. Each metadata block contains
  49. * information to help mitigate the need to iterate over large portions
  50. * of the bitmap. The reverse mapping from page to chunk is stored in
  51. * the page's index. Lastly, units are lazily backed and grow in unison.
  52. *
  53. * There is a unique conversion that goes on here between bytes and bits.
  54. * Each bit represents a fragment of size PCPU_MIN_ALLOC_SIZE. The chunk
  55. * tracks the number of pages it is responsible for in nr_pages. Helper
  56. * functions are used to convert from between the bytes, bits, and blocks.
  57. * All hints are managed in bits unless explicitly stated.
  58. *
  59. * To use this allocator, arch code should do the following:
  60. *
  61. * - define __addr_to_pcpu_ptr() and __pcpu_ptr_to_addr() to translate
  62. * regular address to percpu pointer and back if they need to be
  63. * different from the default
  64. *
  65. * - use pcpu_setup_first_chunk() during percpu area initialization to
  66. * setup the first chunk containing the kernel static percpu area
  67. */
  68. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  69. #include <linux/bitmap.h>
  70. #include <linux/cpumask.h>
  71. #include <linux/memblock.h>
  72. #include <linux/err.h>
  73. #include <linux/lcm.h>
  74. #include <linux/list.h>
  75. #include <linux/log2.h>
  76. #include <linux/mm.h>
  77. #include <linux/module.h>
  78. #include <linux/mutex.h>
  79. #include <linux/percpu.h>
  80. #include <linux/pfn.h>
  81. #include <linux/slab.h>
  82. #include <linux/spinlock.h>
  83. #include <linux/vmalloc.h>
  84. #include <linux/workqueue.h>
  85. #include <linux/kmemleak.h>
  86. #include <linux/sched.h>
  87. #include <linux/sched/mm.h>
  88. #include <linux/memcontrol.h>
  89. #include <asm/cacheflush.h>
  90. #include <asm/sections.h>
  91. #include <asm/tlbflush.h>
  92. #include <asm/io.h>
  93. #define CREATE_TRACE_POINTS
  94. #include <trace/events/percpu.h>
  95. #include "percpu-internal.h"
  96. /*
  97. * The slots are sorted by the size of the biggest continuous free area.
  98. * 1-31 bytes share the same slot.
  99. */
  100. #define PCPU_SLOT_BASE_SHIFT 5
  101. /* chunks in slots below this are subject to being sidelined on failed alloc */
  102. #define PCPU_SLOT_FAIL_THRESHOLD 3
  103. #define PCPU_EMPTY_POP_PAGES_LOW 2
  104. #define PCPU_EMPTY_POP_PAGES_HIGH 4
  105. #ifdef CONFIG_SMP
  106. /* default addr <-> pcpu_ptr mapping, override in asm/percpu.h if necessary */
  107. #ifndef __addr_to_pcpu_ptr
  108. #define __addr_to_pcpu_ptr(addr) \
  109. (void __percpu *)((unsigned long)(addr) - \
  110. (unsigned long)pcpu_base_addr + \
  111. (unsigned long)__per_cpu_start)
  112. #endif
  113. #ifndef __pcpu_ptr_to_addr
  114. #define __pcpu_ptr_to_addr(ptr) \
  115. (void __force *)((unsigned long)(ptr) + \
  116. (unsigned long)pcpu_base_addr - \
  117. (unsigned long)__per_cpu_start)
  118. #endif
  119. #else /* CONFIG_SMP */
  120. /* on UP, it's always identity mapped */
  121. #define __addr_to_pcpu_ptr(addr) (void __percpu *)(addr)
  122. #define __pcpu_ptr_to_addr(ptr) (void __force *)(ptr)
  123. #endif /* CONFIG_SMP */
  124. static int pcpu_unit_pages __ro_after_init;
  125. static int pcpu_unit_size __ro_after_init;
  126. static int pcpu_nr_units __ro_after_init;
  127. static int pcpu_atom_size __ro_after_init;
  128. int pcpu_nr_slots __ro_after_init;
  129. static int pcpu_free_slot __ro_after_init;
  130. int pcpu_sidelined_slot __ro_after_init;
  131. int pcpu_to_depopulate_slot __ro_after_init;
  132. static size_t pcpu_chunk_struct_size __ro_after_init;
  133. /* cpus with the lowest and highest unit addresses */
  134. static unsigned int pcpu_low_unit_cpu __ro_after_init;
  135. static unsigned int pcpu_high_unit_cpu __ro_after_init;
  136. /* the address of the first chunk which starts with the kernel static area */
  137. void *pcpu_base_addr __ro_after_init;
  138. static const int *pcpu_unit_map __ro_after_init; /* cpu -> unit */
  139. const unsigned long *pcpu_unit_offsets __ro_after_init; /* cpu -> unit offset */
  140. /* group information, used for vm allocation */
  141. static int pcpu_nr_groups __ro_after_init;
  142. static const unsigned long *pcpu_group_offsets __ro_after_init;
  143. static const size_t *pcpu_group_sizes __ro_after_init;
  144. /*
  145. * The first chunk which always exists. Note that unlike other
  146. * chunks, this one can be allocated and mapped in several different
  147. * ways and thus often doesn't live in the vmalloc area.
  148. */
  149. struct pcpu_chunk *pcpu_first_chunk __ro_after_init;
  150. /*
  151. * Optional reserved chunk. This chunk reserves part of the first
  152. * chunk and serves it for reserved allocations. When the reserved
  153. * region doesn't exist, the following variable is NULL.
  154. */
  155. struct pcpu_chunk *pcpu_reserved_chunk __ro_after_init;
  156. DEFINE_SPINLOCK(pcpu_lock); /* all internal data structures */
  157. static DEFINE_MUTEX(pcpu_alloc_mutex); /* chunk create/destroy, [de]pop, map ext */
  158. struct list_head *pcpu_chunk_lists __ro_after_init; /* chunk list slots */
  159. /* chunks which need their map areas extended, protected by pcpu_lock */
  160. static LIST_HEAD(pcpu_map_extend_chunks);
  161. /*
  162. * The number of empty populated pages, protected by pcpu_lock.
  163. * The reserved chunk doesn't contribute to the count.
  164. */
  165. int pcpu_nr_empty_pop_pages;
  166. /*
  167. * The number of populated pages in use by the allocator, protected by
  168. * pcpu_lock. This number is kept per a unit per chunk (i.e. when a page gets
  169. * allocated/deallocated, it is allocated/deallocated in all units of a chunk
  170. * and increments/decrements this count by 1).
  171. */
  172. static unsigned long pcpu_nr_populated;
  173. /*
  174. * Balance work is used to populate or destroy chunks asynchronously. We
  175. * try to keep the number of populated free pages between
  176. * PCPU_EMPTY_POP_PAGES_LOW and HIGH for atomic allocations and at most one
  177. * empty chunk.
  178. */
  179. static void pcpu_balance_workfn(struct work_struct *work);
  180. static DECLARE_WORK(pcpu_balance_work, pcpu_balance_workfn);
  181. static bool pcpu_async_enabled __read_mostly;
  182. static bool pcpu_atomic_alloc_failed;
  183. static void pcpu_schedule_balance_work(void)
  184. {
  185. if (pcpu_async_enabled)
  186. schedule_work(&pcpu_balance_work);
  187. }
  188. /**
  189. * pcpu_addr_in_chunk - check if the address is served from this chunk
  190. * @chunk: chunk of interest
  191. * @addr: percpu address
  192. *
  193. * RETURNS:
  194. * True if the address is served from this chunk.
  195. */
  196. static bool pcpu_addr_in_chunk(struct pcpu_chunk *chunk, void *addr)
  197. {
  198. void *start_addr, *end_addr;
  199. if (!chunk)
  200. return false;
  201. start_addr = chunk->base_addr + chunk->start_offset;
  202. end_addr = chunk->base_addr + chunk->nr_pages * PAGE_SIZE -
  203. chunk->end_offset;
  204. return addr >= start_addr && addr < end_addr;
  205. }
  206. static int __pcpu_size_to_slot(int size)
  207. {
  208. int highbit = fls(size); /* size is in bytes */
  209. return max(highbit - PCPU_SLOT_BASE_SHIFT + 2, 1);
  210. }
  211. static int pcpu_size_to_slot(int size)
  212. {
  213. if (size == pcpu_unit_size)
  214. return pcpu_free_slot;
  215. return __pcpu_size_to_slot(size);
  216. }
  217. static int pcpu_chunk_slot(const struct pcpu_chunk *chunk)
  218. {
  219. const struct pcpu_block_md *chunk_md = &chunk->chunk_md;
  220. if (chunk->free_bytes < PCPU_MIN_ALLOC_SIZE ||
  221. chunk_md->contig_hint == 0)
  222. return 0;
  223. return pcpu_size_to_slot(chunk_md->contig_hint * PCPU_MIN_ALLOC_SIZE);
  224. }
  225. /* set the pointer to a chunk in a page struct */
  226. static void pcpu_set_page_chunk(struct page *page, struct pcpu_chunk *pcpu)
  227. {
  228. page->index = (unsigned long)pcpu;
  229. }
  230. /* obtain pointer to a chunk from a page struct */
  231. static struct pcpu_chunk *pcpu_get_page_chunk(struct page *page)
  232. {
  233. return (struct pcpu_chunk *)page->index;
  234. }
  235. static int __maybe_unused pcpu_page_idx(unsigned int cpu, int page_idx)
  236. {
  237. return pcpu_unit_map[cpu] * pcpu_unit_pages + page_idx;
  238. }
  239. static unsigned long pcpu_unit_page_offset(unsigned int cpu, int page_idx)
  240. {
  241. return pcpu_unit_offsets[cpu] + (page_idx << PAGE_SHIFT);
  242. }
  243. static unsigned long pcpu_chunk_addr(struct pcpu_chunk *chunk,
  244. unsigned int cpu, int page_idx)
  245. {
  246. return (unsigned long)chunk->base_addr +
  247. pcpu_unit_page_offset(cpu, page_idx);
  248. }
  249. /*
  250. * The following are helper functions to help access bitmaps and convert
  251. * between bitmap offsets to address offsets.
  252. */
  253. static unsigned long *pcpu_index_alloc_map(struct pcpu_chunk *chunk, int index)
  254. {
  255. return chunk->alloc_map +
  256. (index * PCPU_BITMAP_BLOCK_BITS / BITS_PER_LONG);
  257. }
  258. static unsigned long pcpu_off_to_block_index(int off)
  259. {
  260. return off / PCPU_BITMAP_BLOCK_BITS;
  261. }
  262. static unsigned long pcpu_off_to_block_off(int off)
  263. {
  264. return off & (PCPU_BITMAP_BLOCK_BITS - 1);
  265. }
  266. static unsigned long pcpu_block_off_to_off(int index, int off)
  267. {
  268. return index * PCPU_BITMAP_BLOCK_BITS + off;
  269. }
  270. /**
  271. * pcpu_check_block_hint - check against the contig hint
  272. * @block: block of interest
  273. * @bits: size of allocation
  274. * @align: alignment of area (max PAGE_SIZE)
  275. *
  276. * Check to see if the allocation can fit in the block's contig hint.
  277. * Note, a chunk uses the same hints as a block so this can also check against
  278. * the chunk's contig hint.
  279. */
  280. static bool pcpu_check_block_hint(struct pcpu_block_md *block, int bits,
  281. size_t align)
  282. {
  283. int bit_off = ALIGN(block->contig_hint_start, align) -
  284. block->contig_hint_start;
  285. return bit_off + bits <= block->contig_hint;
  286. }
  287. /*
  288. * pcpu_next_hint - determine which hint to use
  289. * @block: block of interest
  290. * @alloc_bits: size of allocation
  291. *
  292. * This determines if we should scan based on the scan_hint or first_free.
  293. * In general, we want to scan from first_free to fulfill allocations by
  294. * first fit. However, if we know a scan_hint at position scan_hint_start
  295. * cannot fulfill an allocation, we can begin scanning from there knowing
  296. * the contig_hint will be our fallback.
  297. */
  298. static int pcpu_next_hint(struct pcpu_block_md *block, int alloc_bits)
  299. {
  300. /*
  301. * The three conditions below determine if we can skip past the
  302. * scan_hint. First, does the scan hint exist. Second, is the
  303. * contig_hint after the scan_hint (possibly not true iff
  304. * contig_hint == scan_hint). Third, is the allocation request
  305. * larger than the scan_hint.
  306. */
  307. if (block->scan_hint &&
  308. block->contig_hint_start > block->scan_hint_start &&
  309. alloc_bits > block->scan_hint)
  310. return block->scan_hint_start + block->scan_hint;
  311. return block->first_free;
  312. }
  313. /**
  314. * pcpu_next_md_free_region - finds the next hint free area
  315. * @chunk: chunk of interest
  316. * @bit_off: chunk offset
  317. * @bits: size of free area
  318. *
  319. * Helper function for pcpu_for_each_md_free_region. It checks
  320. * block->contig_hint and performs aggregation across blocks to find the
  321. * next hint. It modifies bit_off and bits in-place to be consumed in the
  322. * loop.
  323. */
  324. static void pcpu_next_md_free_region(struct pcpu_chunk *chunk, int *bit_off,
  325. int *bits)
  326. {
  327. int i = pcpu_off_to_block_index(*bit_off);
  328. int block_off = pcpu_off_to_block_off(*bit_off);
  329. struct pcpu_block_md *block;
  330. *bits = 0;
  331. for (block = chunk->md_blocks + i; i < pcpu_chunk_nr_blocks(chunk);
  332. block++, i++) {
  333. /* handles contig area across blocks */
  334. if (*bits) {
  335. *bits += block->left_free;
  336. if (block->left_free == PCPU_BITMAP_BLOCK_BITS)
  337. continue;
  338. return;
  339. }
  340. /*
  341. * This checks three things. First is there a contig_hint to
  342. * check. Second, have we checked this hint before by
  343. * comparing the block_off. Third, is this the same as the
  344. * right contig hint. In the last case, it spills over into
  345. * the next block and should be handled by the contig area
  346. * across blocks code.
  347. */
  348. *bits = block->contig_hint;
  349. if (*bits && block->contig_hint_start >= block_off &&
  350. *bits + block->contig_hint_start < PCPU_BITMAP_BLOCK_BITS) {
  351. *bit_off = pcpu_block_off_to_off(i,
  352. block->contig_hint_start);
  353. return;
  354. }
  355. /* reset to satisfy the second predicate above */
  356. block_off = 0;
  357. *bits = block->right_free;
  358. *bit_off = (i + 1) * PCPU_BITMAP_BLOCK_BITS - block->right_free;
  359. }
  360. }
  361. /**
  362. * pcpu_next_fit_region - finds fit areas for a given allocation request
  363. * @chunk: chunk of interest
  364. * @alloc_bits: size of allocation
  365. * @align: alignment of area (max PAGE_SIZE)
  366. * @bit_off: chunk offset
  367. * @bits: size of free area
  368. *
  369. * Finds the next free region that is viable for use with a given size and
  370. * alignment. This only returns if there is a valid area to be used for this
  371. * allocation. block->first_free is returned if the allocation request fits
  372. * within the block to see if the request can be fulfilled prior to the contig
  373. * hint.
  374. */
  375. static void pcpu_next_fit_region(struct pcpu_chunk *chunk, int alloc_bits,
  376. int align, int *bit_off, int *bits)
  377. {
  378. int i = pcpu_off_to_block_index(*bit_off);
  379. int block_off = pcpu_off_to_block_off(*bit_off);
  380. struct pcpu_block_md *block;
  381. *bits = 0;
  382. for (block = chunk->md_blocks + i; i < pcpu_chunk_nr_blocks(chunk);
  383. block++, i++) {
  384. /* handles contig area across blocks */
  385. if (*bits) {
  386. *bits += block->left_free;
  387. if (*bits >= alloc_bits)
  388. return;
  389. if (block->left_free == PCPU_BITMAP_BLOCK_BITS)
  390. continue;
  391. }
  392. /* check block->contig_hint */
  393. *bits = ALIGN(block->contig_hint_start, align) -
  394. block->contig_hint_start;
  395. /*
  396. * This uses the block offset to determine if this has been
  397. * checked in the prior iteration.
  398. */
  399. if (block->contig_hint &&
  400. block->contig_hint_start >= block_off &&
  401. block->contig_hint >= *bits + alloc_bits) {
  402. int start = pcpu_next_hint(block, alloc_bits);
  403. *bits += alloc_bits + block->contig_hint_start -
  404. start;
  405. *bit_off = pcpu_block_off_to_off(i, start);
  406. return;
  407. }
  408. /* reset to satisfy the second predicate above */
  409. block_off = 0;
  410. *bit_off = ALIGN(PCPU_BITMAP_BLOCK_BITS - block->right_free,
  411. align);
  412. *bits = PCPU_BITMAP_BLOCK_BITS - *bit_off;
  413. *bit_off = pcpu_block_off_to_off(i, *bit_off);
  414. if (*bits >= alloc_bits)
  415. return;
  416. }
  417. /* no valid offsets were found - fail condition */
  418. *bit_off = pcpu_chunk_map_bits(chunk);
  419. }
  420. /*
  421. * Metadata free area iterators. These perform aggregation of free areas
  422. * based on the metadata blocks and return the offset @bit_off and size in
  423. * bits of the free area @bits. pcpu_for_each_fit_region only returns when
  424. * a fit is found for the allocation request.
  425. */
  426. #define pcpu_for_each_md_free_region(chunk, bit_off, bits) \
  427. for (pcpu_next_md_free_region((chunk), &(bit_off), &(bits)); \
  428. (bit_off) < pcpu_chunk_map_bits((chunk)); \
  429. (bit_off) += (bits) + 1, \
  430. pcpu_next_md_free_region((chunk), &(bit_off), &(bits)))
  431. #define pcpu_for_each_fit_region(chunk, alloc_bits, align, bit_off, bits) \
  432. for (pcpu_next_fit_region((chunk), (alloc_bits), (align), &(bit_off), \
  433. &(bits)); \
  434. (bit_off) < pcpu_chunk_map_bits((chunk)); \
  435. (bit_off) += (bits), \
  436. pcpu_next_fit_region((chunk), (alloc_bits), (align), &(bit_off), \
  437. &(bits)))
  438. /**
  439. * pcpu_mem_zalloc - allocate memory
  440. * @size: bytes to allocate
  441. * @gfp: allocation flags
  442. *
  443. * Allocate @size bytes. If @size is smaller than PAGE_SIZE,
  444. * kzalloc() is used; otherwise, the equivalent of vzalloc() is used.
  445. * This is to facilitate passing through whitelisted flags. The
  446. * returned memory is always zeroed.
  447. *
  448. * RETURNS:
  449. * Pointer to the allocated area on success, NULL on failure.
  450. */
  451. static void *pcpu_mem_zalloc(size_t size, gfp_t gfp)
  452. {
  453. if (WARN_ON_ONCE(!slab_is_available()))
  454. return NULL;
  455. if (size <= PAGE_SIZE)
  456. return kzalloc(size, gfp);
  457. else
  458. return __vmalloc(size, gfp | __GFP_ZERO);
  459. }
  460. /**
  461. * pcpu_mem_free - free memory
  462. * @ptr: memory to free
  463. *
  464. * Free @ptr. @ptr should have been allocated using pcpu_mem_zalloc().
  465. */
  466. static void pcpu_mem_free(void *ptr)
  467. {
  468. kvfree(ptr);
  469. }
  470. static void __pcpu_chunk_move(struct pcpu_chunk *chunk, int slot,
  471. bool move_front)
  472. {
  473. if (chunk != pcpu_reserved_chunk) {
  474. if (move_front)
  475. list_move(&chunk->list, &pcpu_chunk_lists[slot]);
  476. else
  477. list_move_tail(&chunk->list, &pcpu_chunk_lists[slot]);
  478. }
  479. }
  480. static void pcpu_chunk_move(struct pcpu_chunk *chunk, int slot)
  481. {
  482. __pcpu_chunk_move(chunk, slot, true);
  483. }
  484. /**
  485. * pcpu_chunk_relocate - put chunk in the appropriate chunk slot
  486. * @chunk: chunk of interest
  487. * @oslot: the previous slot it was on
  488. *
  489. * This function is called after an allocation or free changed @chunk.
  490. * New slot according to the changed state is determined and @chunk is
  491. * moved to the slot. Note that the reserved chunk is never put on
  492. * chunk slots.
  493. *
  494. * CONTEXT:
  495. * pcpu_lock.
  496. */
  497. static void pcpu_chunk_relocate(struct pcpu_chunk *chunk, int oslot)
  498. {
  499. int nslot = pcpu_chunk_slot(chunk);
  500. /* leave isolated chunks in-place */
  501. if (chunk->isolated)
  502. return;
  503. if (oslot != nslot)
  504. __pcpu_chunk_move(chunk, nslot, oslot < nslot);
  505. }
  506. static void pcpu_isolate_chunk(struct pcpu_chunk *chunk)
  507. {
  508. lockdep_assert_held(&pcpu_lock);
  509. if (!chunk->isolated) {
  510. chunk->isolated = true;
  511. pcpu_nr_empty_pop_pages -= chunk->nr_empty_pop_pages;
  512. }
  513. list_move(&chunk->list, &pcpu_chunk_lists[pcpu_to_depopulate_slot]);
  514. }
  515. static void pcpu_reintegrate_chunk(struct pcpu_chunk *chunk)
  516. {
  517. lockdep_assert_held(&pcpu_lock);
  518. if (chunk->isolated) {
  519. chunk->isolated = false;
  520. pcpu_nr_empty_pop_pages += chunk->nr_empty_pop_pages;
  521. pcpu_chunk_relocate(chunk, -1);
  522. }
  523. }
  524. /*
  525. * pcpu_update_empty_pages - update empty page counters
  526. * @chunk: chunk of interest
  527. * @nr: nr of empty pages
  528. *
  529. * This is used to keep track of the empty pages now based on the premise
  530. * a md_block covers a page. The hint update functions recognize if a block
  531. * is made full or broken to calculate deltas for keeping track of free pages.
  532. */
  533. static inline void pcpu_update_empty_pages(struct pcpu_chunk *chunk, int nr)
  534. {
  535. chunk->nr_empty_pop_pages += nr;
  536. if (chunk != pcpu_reserved_chunk && !chunk->isolated)
  537. pcpu_nr_empty_pop_pages += nr;
  538. }
  539. /*
  540. * pcpu_region_overlap - determines if two regions overlap
  541. * @a: start of first region, inclusive
  542. * @b: end of first region, exclusive
  543. * @x: start of second region, inclusive
  544. * @y: end of second region, exclusive
  545. *
  546. * This is used to determine if the hint region [a, b) overlaps with the
  547. * allocated region [x, y).
  548. */
  549. static inline bool pcpu_region_overlap(int a, int b, int x, int y)
  550. {
  551. return (a < y) && (x < b);
  552. }
  553. /**
  554. * pcpu_block_update - updates a block given a free area
  555. * @block: block of interest
  556. * @start: start offset in block
  557. * @end: end offset in block
  558. *
  559. * Updates a block given a known free area. The region [start, end) is
  560. * expected to be the entirety of the free area within a block. Chooses
  561. * the best starting offset if the contig hints are equal.
  562. */
  563. static void pcpu_block_update(struct pcpu_block_md *block, int start, int end)
  564. {
  565. int contig = end - start;
  566. block->first_free = min(block->first_free, start);
  567. if (start == 0)
  568. block->left_free = contig;
  569. if (end == block->nr_bits)
  570. block->right_free = contig;
  571. if (contig > block->contig_hint) {
  572. /* promote the old contig_hint to be the new scan_hint */
  573. if (start > block->contig_hint_start) {
  574. if (block->contig_hint > block->scan_hint) {
  575. block->scan_hint_start =
  576. block->contig_hint_start;
  577. block->scan_hint = block->contig_hint;
  578. } else if (start < block->scan_hint_start) {
  579. /*
  580. * The old contig_hint == scan_hint. But, the
  581. * new contig is larger so hold the invariant
  582. * scan_hint_start < contig_hint_start.
  583. */
  584. block->scan_hint = 0;
  585. }
  586. } else {
  587. block->scan_hint = 0;
  588. }
  589. block->contig_hint_start = start;
  590. block->contig_hint = contig;
  591. } else if (contig == block->contig_hint) {
  592. if (block->contig_hint_start &&
  593. (!start ||
  594. __ffs(start) > __ffs(block->contig_hint_start))) {
  595. /* start has a better alignment so use it */
  596. block->contig_hint_start = start;
  597. if (start < block->scan_hint_start &&
  598. block->contig_hint > block->scan_hint)
  599. block->scan_hint = 0;
  600. } else if (start > block->scan_hint_start ||
  601. block->contig_hint > block->scan_hint) {
  602. /*
  603. * Knowing contig == contig_hint, update the scan_hint
  604. * if it is farther than or larger than the current
  605. * scan_hint.
  606. */
  607. block->scan_hint_start = start;
  608. block->scan_hint = contig;
  609. }
  610. } else {
  611. /*
  612. * The region is smaller than the contig_hint. So only update
  613. * the scan_hint if it is larger than or equal and farther than
  614. * the current scan_hint.
  615. */
  616. if ((start < block->contig_hint_start &&
  617. (contig > block->scan_hint ||
  618. (contig == block->scan_hint &&
  619. start > block->scan_hint_start)))) {
  620. block->scan_hint_start = start;
  621. block->scan_hint = contig;
  622. }
  623. }
  624. }
  625. /*
  626. * pcpu_block_update_scan - update a block given a free area from a scan
  627. * @chunk: chunk of interest
  628. * @bit_off: chunk offset
  629. * @bits: size of free area
  630. *
  631. * Finding the final allocation spot first goes through pcpu_find_block_fit()
  632. * to find a block that can hold the allocation and then pcpu_alloc_area()
  633. * where a scan is used. When allocations require specific alignments,
  634. * we can inadvertently create holes which will not be seen in the alloc
  635. * or free paths.
  636. *
  637. * This takes a given free area hole and updates a block as it may change the
  638. * scan_hint. We need to scan backwards to ensure we don't miss free bits
  639. * from alignment.
  640. */
  641. static void pcpu_block_update_scan(struct pcpu_chunk *chunk, int bit_off,
  642. int bits)
  643. {
  644. int s_off = pcpu_off_to_block_off(bit_off);
  645. int e_off = s_off + bits;
  646. int s_index, l_bit;
  647. struct pcpu_block_md *block;
  648. if (e_off > PCPU_BITMAP_BLOCK_BITS)
  649. return;
  650. s_index = pcpu_off_to_block_index(bit_off);
  651. block = chunk->md_blocks + s_index;
  652. /* scan backwards in case of alignment skipping free bits */
  653. l_bit = find_last_bit(pcpu_index_alloc_map(chunk, s_index), s_off);
  654. s_off = (s_off == l_bit) ? 0 : l_bit + 1;
  655. pcpu_block_update(block, s_off, e_off);
  656. }
  657. /**
  658. * pcpu_chunk_refresh_hint - updates metadata about a chunk
  659. * @chunk: chunk of interest
  660. * @full_scan: if we should scan from the beginning
  661. *
  662. * Iterates over the metadata blocks to find the largest contig area.
  663. * A full scan can be avoided on the allocation path as this is triggered
  664. * if we broke the contig_hint. In doing so, the scan_hint will be before
  665. * the contig_hint or after if the scan_hint == contig_hint. This cannot
  666. * be prevented on freeing as we want to find the largest area possibly
  667. * spanning blocks.
  668. */
  669. static void pcpu_chunk_refresh_hint(struct pcpu_chunk *chunk, bool full_scan)
  670. {
  671. struct pcpu_block_md *chunk_md = &chunk->chunk_md;
  672. int bit_off, bits;
  673. /* promote scan_hint to contig_hint */
  674. if (!full_scan && chunk_md->scan_hint) {
  675. bit_off = chunk_md->scan_hint_start + chunk_md->scan_hint;
  676. chunk_md->contig_hint_start = chunk_md->scan_hint_start;
  677. chunk_md->contig_hint = chunk_md->scan_hint;
  678. chunk_md->scan_hint = 0;
  679. } else {
  680. bit_off = chunk_md->first_free;
  681. chunk_md->contig_hint = 0;
  682. }
  683. bits = 0;
  684. pcpu_for_each_md_free_region(chunk, bit_off, bits)
  685. pcpu_block_update(chunk_md, bit_off, bit_off + bits);
  686. }
  687. /**
  688. * pcpu_block_refresh_hint
  689. * @chunk: chunk of interest
  690. * @index: index of the metadata block
  691. *
  692. * Scans over the block beginning at first_free and updates the block
  693. * metadata accordingly.
  694. */
  695. static void pcpu_block_refresh_hint(struct pcpu_chunk *chunk, int index)
  696. {
  697. struct pcpu_block_md *block = chunk->md_blocks + index;
  698. unsigned long *alloc_map = pcpu_index_alloc_map(chunk, index);
  699. unsigned int start, end; /* region start, region end */
  700. /* promote scan_hint to contig_hint */
  701. if (block->scan_hint) {
  702. start = block->scan_hint_start + block->scan_hint;
  703. block->contig_hint_start = block->scan_hint_start;
  704. block->contig_hint = block->scan_hint;
  705. block->scan_hint = 0;
  706. } else {
  707. start = block->first_free;
  708. block->contig_hint = 0;
  709. }
  710. block->right_free = 0;
  711. /* iterate over free areas and update the contig hints */
  712. for_each_clear_bitrange_from(start, end, alloc_map, PCPU_BITMAP_BLOCK_BITS)
  713. pcpu_block_update(block, start, end);
  714. }
  715. /**
  716. * pcpu_block_update_hint_alloc - update hint on allocation path
  717. * @chunk: chunk of interest
  718. * @bit_off: chunk offset
  719. * @bits: size of request
  720. *
  721. * Updates metadata for the allocation path. The metadata only has to be
  722. * refreshed by a full scan iff the chunk's contig hint is broken. Block level
  723. * scans are required if the block's contig hint is broken.
  724. */
  725. static void pcpu_block_update_hint_alloc(struct pcpu_chunk *chunk, int bit_off,
  726. int bits)
  727. {
  728. struct pcpu_block_md *chunk_md = &chunk->chunk_md;
  729. int nr_empty_pages = 0;
  730. struct pcpu_block_md *s_block, *e_block, *block;
  731. int s_index, e_index; /* block indexes of the freed allocation */
  732. int s_off, e_off; /* block offsets of the freed allocation */
  733. /*
  734. * Calculate per block offsets.
  735. * The calculation uses an inclusive range, but the resulting offsets
  736. * are [start, end). e_index always points to the last block in the
  737. * range.
  738. */
  739. s_index = pcpu_off_to_block_index(bit_off);
  740. e_index = pcpu_off_to_block_index(bit_off + bits - 1);
  741. s_off = pcpu_off_to_block_off(bit_off);
  742. e_off = pcpu_off_to_block_off(bit_off + bits - 1) + 1;
  743. s_block = chunk->md_blocks + s_index;
  744. e_block = chunk->md_blocks + e_index;
  745. /*
  746. * Update s_block.
  747. * block->first_free must be updated if the allocation takes its place.
  748. * If the allocation breaks the contig_hint, a scan is required to
  749. * restore this hint.
  750. */
  751. if (s_block->contig_hint == PCPU_BITMAP_BLOCK_BITS)
  752. nr_empty_pages++;
  753. if (s_off == s_block->first_free)
  754. s_block->first_free = find_next_zero_bit(
  755. pcpu_index_alloc_map(chunk, s_index),
  756. PCPU_BITMAP_BLOCK_BITS,
  757. s_off + bits);
  758. if (pcpu_region_overlap(s_block->scan_hint_start,
  759. s_block->scan_hint_start + s_block->scan_hint,
  760. s_off,
  761. s_off + bits))
  762. s_block->scan_hint = 0;
  763. if (pcpu_region_overlap(s_block->contig_hint_start,
  764. s_block->contig_hint_start +
  765. s_block->contig_hint,
  766. s_off,
  767. s_off + bits)) {
  768. /* block contig hint is broken - scan to fix it */
  769. if (!s_off)
  770. s_block->left_free = 0;
  771. pcpu_block_refresh_hint(chunk, s_index);
  772. } else {
  773. /* update left and right contig manually */
  774. s_block->left_free = min(s_block->left_free, s_off);
  775. if (s_index == e_index)
  776. s_block->right_free = min_t(int, s_block->right_free,
  777. PCPU_BITMAP_BLOCK_BITS - e_off);
  778. else
  779. s_block->right_free = 0;
  780. }
  781. /*
  782. * Update e_block.
  783. */
  784. if (s_index != e_index) {
  785. if (e_block->contig_hint == PCPU_BITMAP_BLOCK_BITS)
  786. nr_empty_pages++;
  787. /*
  788. * When the allocation is across blocks, the end is along
  789. * the left part of the e_block.
  790. */
  791. e_block->first_free = find_next_zero_bit(
  792. pcpu_index_alloc_map(chunk, e_index),
  793. PCPU_BITMAP_BLOCK_BITS, e_off);
  794. if (e_off == PCPU_BITMAP_BLOCK_BITS) {
  795. /* reset the block */
  796. e_block++;
  797. } else {
  798. if (e_off > e_block->scan_hint_start)
  799. e_block->scan_hint = 0;
  800. e_block->left_free = 0;
  801. if (e_off > e_block->contig_hint_start) {
  802. /* contig hint is broken - scan to fix it */
  803. pcpu_block_refresh_hint(chunk, e_index);
  804. } else {
  805. e_block->right_free =
  806. min_t(int, e_block->right_free,
  807. PCPU_BITMAP_BLOCK_BITS - e_off);
  808. }
  809. }
  810. /* update in-between md_blocks */
  811. nr_empty_pages += (e_index - s_index - 1);
  812. for (block = s_block + 1; block < e_block; block++) {
  813. block->scan_hint = 0;
  814. block->contig_hint = 0;
  815. block->left_free = 0;
  816. block->right_free = 0;
  817. }
  818. }
  819. if (nr_empty_pages)
  820. pcpu_update_empty_pages(chunk, -nr_empty_pages);
  821. if (pcpu_region_overlap(chunk_md->scan_hint_start,
  822. chunk_md->scan_hint_start +
  823. chunk_md->scan_hint,
  824. bit_off,
  825. bit_off + bits))
  826. chunk_md->scan_hint = 0;
  827. /*
  828. * The only time a full chunk scan is required is if the chunk
  829. * contig hint is broken. Otherwise, it means a smaller space
  830. * was used and therefore the chunk contig hint is still correct.
  831. */
  832. if (pcpu_region_overlap(chunk_md->contig_hint_start,
  833. chunk_md->contig_hint_start +
  834. chunk_md->contig_hint,
  835. bit_off,
  836. bit_off + bits))
  837. pcpu_chunk_refresh_hint(chunk, false);
  838. }
  839. /**
  840. * pcpu_block_update_hint_free - updates the block hints on the free path
  841. * @chunk: chunk of interest
  842. * @bit_off: chunk offset
  843. * @bits: size of request
  844. *
  845. * Updates metadata for the allocation path. This avoids a blind block
  846. * refresh by making use of the block contig hints. If this fails, it scans
  847. * forward and backward to determine the extent of the free area. This is
  848. * capped at the boundary of blocks.
  849. *
  850. * A chunk update is triggered if a page becomes free, a block becomes free,
  851. * or the free spans across blocks. This tradeoff is to minimize iterating
  852. * over the block metadata to update chunk_md->contig_hint.
  853. * chunk_md->contig_hint may be off by up to a page, but it will never be more
  854. * than the available space. If the contig hint is contained in one block, it
  855. * will be accurate.
  856. */
  857. static void pcpu_block_update_hint_free(struct pcpu_chunk *chunk, int bit_off,
  858. int bits)
  859. {
  860. int nr_empty_pages = 0;
  861. struct pcpu_block_md *s_block, *e_block, *block;
  862. int s_index, e_index; /* block indexes of the freed allocation */
  863. int s_off, e_off; /* block offsets of the freed allocation */
  864. int start, end; /* start and end of the whole free area */
  865. /*
  866. * Calculate per block offsets.
  867. * The calculation uses an inclusive range, but the resulting offsets
  868. * are [start, end). e_index always points to the last block in the
  869. * range.
  870. */
  871. s_index = pcpu_off_to_block_index(bit_off);
  872. e_index = pcpu_off_to_block_index(bit_off + bits - 1);
  873. s_off = pcpu_off_to_block_off(bit_off);
  874. e_off = pcpu_off_to_block_off(bit_off + bits - 1) + 1;
  875. s_block = chunk->md_blocks + s_index;
  876. e_block = chunk->md_blocks + e_index;
  877. /*
  878. * Check if the freed area aligns with the block->contig_hint.
  879. * If it does, then the scan to find the beginning/end of the
  880. * larger free area can be avoided.
  881. *
  882. * start and end refer to beginning and end of the free area
  883. * within each their respective blocks. This is not necessarily
  884. * the entire free area as it may span blocks past the beginning
  885. * or end of the block.
  886. */
  887. start = s_off;
  888. if (s_off == s_block->contig_hint + s_block->contig_hint_start) {
  889. start = s_block->contig_hint_start;
  890. } else {
  891. /*
  892. * Scan backwards to find the extent of the free area.
  893. * find_last_bit returns the starting bit, so if the start bit
  894. * is returned, that means there was no last bit and the
  895. * remainder of the chunk is free.
  896. */
  897. int l_bit = find_last_bit(pcpu_index_alloc_map(chunk, s_index),
  898. start);
  899. start = (start == l_bit) ? 0 : l_bit + 1;
  900. }
  901. end = e_off;
  902. if (e_off == e_block->contig_hint_start)
  903. end = e_block->contig_hint_start + e_block->contig_hint;
  904. else
  905. end = find_next_bit(pcpu_index_alloc_map(chunk, e_index),
  906. PCPU_BITMAP_BLOCK_BITS, end);
  907. /* update s_block */
  908. e_off = (s_index == e_index) ? end : PCPU_BITMAP_BLOCK_BITS;
  909. if (!start && e_off == PCPU_BITMAP_BLOCK_BITS)
  910. nr_empty_pages++;
  911. pcpu_block_update(s_block, start, e_off);
  912. /* freeing in the same block */
  913. if (s_index != e_index) {
  914. /* update e_block */
  915. if (end == PCPU_BITMAP_BLOCK_BITS)
  916. nr_empty_pages++;
  917. pcpu_block_update(e_block, 0, end);
  918. /* reset md_blocks in the middle */
  919. nr_empty_pages += (e_index - s_index - 1);
  920. for (block = s_block + 1; block < e_block; block++) {
  921. block->first_free = 0;
  922. block->scan_hint = 0;
  923. block->contig_hint_start = 0;
  924. block->contig_hint = PCPU_BITMAP_BLOCK_BITS;
  925. block->left_free = PCPU_BITMAP_BLOCK_BITS;
  926. block->right_free = PCPU_BITMAP_BLOCK_BITS;
  927. }
  928. }
  929. if (nr_empty_pages)
  930. pcpu_update_empty_pages(chunk, nr_empty_pages);
  931. /*
  932. * Refresh chunk metadata when the free makes a block free or spans
  933. * across blocks. The contig_hint may be off by up to a page, but if
  934. * the contig_hint is contained in a block, it will be accurate with
  935. * the else condition below.
  936. */
  937. if (((end - start) >= PCPU_BITMAP_BLOCK_BITS) || s_index != e_index)
  938. pcpu_chunk_refresh_hint(chunk, true);
  939. else
  940. pcpu_block_update(&chunk->chunk_md,
  941. pcpu_block_off_to_off(s_index, start),
  942. end);
  943. }
  944. /**
  945. * pcpu_is_populated - determines if the region is populated
  946. * @chunk: chunk of interest
  947. * @bit_off: chunk offset
  948. * @bits: size of area
  949. * @next_off: return value for the next offset to start searching
  950. *
  951. * For atomic allocations, check if the backing pages are populated.
  952. *
  953. * RETURNS:
  954. * Bool if the backing pages are populated.
  955. * next_index is to skip over unpopulated blocks in pcpu_find_block_fit.
  956. */
  957. static bool pcpu_is_populated(struct pcpu_chunk *chunk, int bit_off, int bits,
  958. int *next_off)
  959. {
  960. unsigned int start, end;
  961. start = PFN_DOWN(bit_off * PCPU_MIN_ALLOC_SIZE);
  962. end = PFN_UP((bit_off + bits) * PCPU_MIN_ALLOC_SIZE);
  963. start = find_next_zero_bit(chunk->populated, end, start);
  964. if (start >= end)
  965. return true;
  966. end = find_next_bit(chunk->populated, end, start + 1);
  967. *next_off = end * PAGE_SIZE / PCPU_MIN_ALLOC_SIZE;
  968. return false;
  969. }
  970. /**
  971. * pcpu_find_block_fit - finds the block index to start searching
  972. * @chunk: chunk of interest
  973. * @alloc_bits: size of request in allocation units
  974. * @align: alignment of area (max PAGE_SIZE bytes)
  975. * @pop_only: use populated regions only
  976. *
  977. * Given a chunk and an allocation spec, find the offset to begin searching
  978. * for a free region. This iterates over the bitmap metadata blocks to
  979. * find an offset that will be guaranteed to fit the requirements. It is
  980. * not quite first fit as if the allocation does not fit in the contig hint
  981. * of a block or chunk, it is skipped. This errs on the side of caution
  982. * to prevent excess iteration. Poor alignment can cause the allocator to
  983. * skip over blocks and chunks that have valid free areas.
  984. *
  985. * RETURNS:
  986. * The offset in the bitmap to begin searching.
  987. * -1 if no offset is found.
  988. */
  989. static int pcpu_find_block_fit(struct pcpu_chunk *chunk, int alloc_bits,
  990. size_t align, bool pop_only)
  991. {
  992. struct pcpu_block_md *chunk_md = &chunk->chunk_md;
  993. int bit_off, bits, next_off;
  994. /*
  995. * This is an optimization to prevent scanning by assuming if the
  996. * allocation cannot fit in the global hint, there is memory pressure
  997. * and creating a new chunk would happen soon.
  998. */
  999. if (!pcpu_check_block_hint(chunk_md, alloc_bits, align))
  1000. return -1;
  1001. bit_off = pcpu_next_hint(chunk_md, alloc_bits);
  1002. bits = 0;
  1003. pcpu_for_each_fit_region(chunk, alloc_bits, align, bit_off, bits) {
  1004. if (!pop_only || pcpu_is_populated(chunk, bit_off, bits,
  1005. &next_off))
  1006. break;
  1007. bit_off = next_off;
  1008. bits = 0;
  1009. }
  1010. if (bit_off == pcpu_chunk_map_bits(chunk))
  1011. return -1;
  1012. return bit_off;
  1013. }
  1014. /*
  1015. * pcpu_find_zero_area - modified from bitmap_find_next_zero_area_off()
  1016. * @map: the address to base the search on
  1017. * @size: the bitmap size in bits
  1018. * @start: the bitnumber to start searching at
  1019. * @nr: the number of zeroed bits we're looking for
  1020. * @align_mask: alignment mask for zero area
  1021. * @largest_off: offset of the largest area skipped
  1022. * @largest_bits: size of the largest area skipped
  1023. *
  1024. * The @align_mask should be one less than a power of 2.
  1025. *
  1026. * This is a modified version of bitmap_find_next_zero_area_off() to remember
  1027. * the largest area that was skipped. This is imperfect, but in general is
  1028. * good enough. The largest remembered region is the largest failed region
  1029. * seen. This does not include anything we possibly skipped due to alignment.
  1030. * pcpu_block_update_scan() does scan backwards to try and recover what was
  1031. * lost to alignment. While this can cause scanning to miss earlier possible
  1032. * free areas, smaller allocations will eventually fill those holes.
  1033. */
  1034. static unsigned long pcpu_find_zero_area(unsigned long *map,
  1035. unsigned long size,
  1036. unsigned long start,
  1037. unsigned long nr,
  1038. unsigned long align_mask,
  1039. unsigned long *largest_off,
  1040. unsigned long *largest_bits)
  1041. {
  1042. unsigned long index, end, i, area_off, area_bits;
  1043. again:
  1044. index = find_next_zero_bit(map, size, start);
  1045. /* Align allocation */
  1046. index = __ALIGN_MASK(index, align_mask);
  1047. area_off = index;
  1048. end = index + nr;
  1049. if (end > size)
  1050. return end;
  1051. i = find_next_bit(map, end, index);
  1052. if (i < end) {
  1053. area_bits = i - area_off;
  1054. /* remember largest unused area with best alignment */
  1055. if (area_bits > *largest_bits ||
  1056. (area_bits == *largest_bits && *largest_off &&
  1057. (!area_off || __ffs(area_off) > __ffs(*largest_off)))) {
  1058. *largest_off = area_off;
  1059. *largest_bits = area_bits;
  1060. }
  1061. start = i + 1;
  1062. goto again;
  1063. }
  1064. return index;
  1065. }
  1066. /**
  1067. * pcpu_alloc_area - allocates an area from a pcpu_chunk
  1068. * @chunk: chunk of interest
  1069. * @alloc_bits: size of request in allocation units
  1070. * @align: alignment of area (max PAGE_SIZE)
  1071. * @start: bit_off to start searching
  1072. *
  1073. * This function takes in a @start offset to begin searching to fit an
  1074. * allocation of @alloc_bits with alignment @align. It needs to scan
  1075. * the allocation map because if it fits within the block's contig hint,
  1076. * @start will be block->first_free. This is an attempt to fill the
  1077. * allocation prior to breaking the contig hint. The allocation and
  1078. * boundary maps are updated accordingly if it confirms a valid
  1079. * free area.
  1080. *
  1081. * RETURNS:
  1082. * Allocated addr offset in @chunk on success.
  1083. * -1 if no matching area is found.
  1084. */
  1085. static int pcpu_alloc_area(struct pcpu_chunk *chunk, int alloc_bits,
  1086. size_t align, int start)
  1087. {
  1088. struct pcpu_block_md *chunk_md = &chunk->chunk_md;
  1089. size_t align_mask = (align) ? (align - 1) : 0;
  1090. unsigned long area_off = 0, area_bits = 0;
  1091. int bit_off, end, oslot;
  1092. lockdep_assert_held(&pcpu_lock);
  1093. oslot = pcpu_chunk_slot(chunk);
  1094. /*
  1095. * Search to find a fit.
  1096. */
  1097. end = min_t(int, start + alloc_bits + PCPU_BITMAP_BLOCK_BITS,
  1098. pcpu_chunk_map_bits(chunk));
  1099. bit_off = pcpu_find_zero_area(chunk->alloc_map, end, start, alloc_bits,
  1100. align_mask, &area_off, &area_bits);
  1101. if (bit_off >= end)
  1102. return -1;
  1103. if (area_bits)
  1104. pcpu_block_update_scan(chunk, area_off, area_bits);
  1105. /* update alloc map */
  1106. bitmap_set(chunk->alloc_map, bit_off, alloc_bits);
  1107. /* update boundary map */
  1108. set_bit(bit_off, chunk->bound_map);
  1109. bitmap_clear(chunk->bound_map, bit_off + 1, alloc_bits - 1);
  1110. set_bit(bit_off + alloc_bits, chunk->bound_map);
  1111. chunk->free_bytes -= alloc_bits * PCPU_MIN_ALLOC_SIZE;
  1112. /* update first free bit */
  1113. if (bit_off == chunk_md->first_free)
  1114. chunk_md->first_free = find_next_zero_bit(
  1115. chunk->alloc_map,
  1116. pcpu_chunk_map_bits(chunk),
  1117. bit_off + alloc_bits);
  1118. pcpu_block_update_hint_alloc(chunk, bit_off, alloc_bits);
  1119. pcpu_chunk_relocate(chunk, oslot);
  1120. return bit_off * PCPU_MIN_ALLOC_SIZE;
  1121. }
  1122. /**
  1123. * pcpu_free_area - frees the corresponding offset
  1124. * @chunk: chunk of interest
  1125. * @off: addr offset into chunk
  1126. *
  1127. * This function determines the size of an allocation to free using
  1128. * the boundary bitmap and clears the allocation map.
  1129. *
  1130. * RETURNS:
  1131. * Number of freed bytes.
  1132. */
  1133. static int pcpu_free_area(struct pcpu_chunk *chunk, int off)
  1134. {
  1135. struct pcpu_block_md *chunk_md = &chunk->chunk_md;
  1136. int bit_off, bits, end, oslot, freed;
  1137. lockdep_assert_held(&pcpu_lock);
  1138. pcpu_stats_area_dealloc(chunk);
  1139. oslot = pcpu_chunk_slot(chunk);
  1140. bit_off = off / PCPU_MIN_ALLOC_SIZE;
  1141. /* find end index */
  1142. end = find_next_bit(chunk->bound_map, pcpu_chunk_map_bits(chunk),
  1143. bit_off + 1);
  1144. bits = end - bit_off;
  1145. bitmap_clear(chunk->alloc_map, bit_off, bits);
  1146. freed = bits * PCPU_MIN_ALLOC_SIZE;
  1147. /* update metadata */
  1148. chunk->free_bytes += freed;
  1149. /* update first free bit */
  1150. chunk_md->first_free = min(chunk_md->first_free, bit_off);
  1151. pcpu_block_update_hint_free(chunk, bit_off, bits);
  1152. pcpu_chunk_relocate(chunk, oslot);
  1153. return freed;
  1154. }
  1155. static void pcpu_init_md_block(struct pcpu_block_md *block, int nr_bits)
  1156. {
  1157. block->scan_hint = 0;
  1158. block->contig_hint = nr_bits;
  1159. block->left_free = nr_bits;
  1160. block->right_free = nr_bits;
  1161. block->first_free = 0;
  1162. block->nr_bits = nr_bits;
  1163. }
  1164. static void pcpu_init_md_blocks(struct pcpu_chunk *chunk)
  1165. {
  1166. struct pcpu_block_md *md_block;
  1167. /* init the chunk's block */
  1168. pcpu_init_md_block(&chunk->chunk_md, pcpu_chunk_map_bits(chunk));
  1169. for (md_block = chunk->md_blocks;
  1170. md_block != chunk->md_blocks + pcpu_chunk_nr_blocks(chunk);
  1171. md_block++)
  1172. pcpu_init_md_block(md_block, PCPU_BITMAP_BLOCK_BITS);
  1173. }
  1174. /**
  1175. * pcpu_alloc_first_chunk - creates chunks that serve the first chunk
  1176. * @tmp_addr: the start of the region served
  1177. * @map_size: size of the region served
  1178. *
  1179. * This is responsible for creating the chunks that serve the first chunk. The
  1180. * base_addr is page aligned down of @tmp_addr while the region end is page
  1181. * aligned up. Offsets are kept track of to determine the region served. All
  1182. * this is done to appease the bitmap allocator in avoiding partial blocks.
  1183. *
  1184. * RETURNS:
  1185. * Chunk serving the region at @tmp_addr of @map_size.
  1186. */
  1187. static struct pcpu_chunk * __init pcpu_alloc_first_chunk(unsigned long tmp_addr,
  1188. int map_size)
  1189. {
  1190. struct pcpu_chunk *chunk;
  1191. unsigned long aligned_addr, lcm_align;
  1192. int start_offset, offset_bits, region_size, region_bits;
  1193. size_t alloc_size;
  1194. /* region calculations */
  1195. aligned_addr = tmp_addr & PAGE_MASK;
  1196. start_offset = tmp_addr - aligned_addr;
  1197. /*
  1198. * Align the end of the region with the LCM of PAGE_SIZE and
  1199. * PCPU_BITMAP_BLOCK_SIZE. One of these constants is a multiple of
  1200. * the other.
  1201. */
  1202. lcm_align = lcm(PAGE_SIZE, PCPU_BITMAP_BLOCK_SIZE);
  1203. region_size = ALIGN(start_offset + map_size, lcm_align);
  1204. /* allocate chunk */
  1205. alloc_size = struct_size(chunk, populated,
  1206. BITS_TO_LONGS(region_size >> PAGE_SHIFT));
  1207. chunk = memblock_alloc(alloc_size, SMP_CACHE_BYTES);
  1208. if (!chunk)
  1209. panic("%s: Failed to allocate %zu bytes\n", __func__,
  1210. alloc_size);
  1211. INIT_LIST_HEAD(&chunk->list);
  1212. chunk->base_addr = (void *)aligned_addr;
  1213. chunk->start_offset = start_offset;
  1214. chunk->end_offset = region_size - chunk->start_offset - map_size;
  1215. chunk->nr_pages = region_size >> PAGE_SHIFT;
  1216. region_bits = pcpu_chunk_map_bits(chunk);
  1217. alloc_size = BITS_TO_LONGS(region_bits) * sizeof(chunk->alloc_map[0]);
  1218. chunk->alloc_map = memblock_alloc(alloc_size, SMP_CACHE_BYTES);
  1219. if (!chunk->alloc_map)
  1220. panic("%s: Failed to allocate %zu bytes\n", __func__,
  1221. alloc_size);
  1222. alloc_size =
  1223. BITS_TO_LONGS(region_bits + 1) * sizeof(chunk->bound_map[0]);
  1224. chunk->bound_map = memblock_alloc(alloc_size, SMP_CACHE_BYTES);
  1225. if (!chunk->bound_map)
  1226. panic("%s: Failed to allocate %zu bytes\n", __func__,
  1227. alloc_size);
  1228. alloc_size = pcpu_chunk_nr_blocks(chunk) * sizeof(chunk->md_blocks[0]);
  1229. chunk->md_blocks = memblock_alloc(alloc_size, SMP_CACHE_BYTES);
  1230. if (!chunk->md_blocks)
  1231. panic("%s: Failed to allocate %zu bytes\n", __func__,
  1232. alloc_size);
  1233. #ifdef CONFIG_MEMCG_KMEM
  1234. /* first chunk is free to use */
  1235. chunk->obj_cgroups = NULL;
  1236. #endif
  1237. pcpu_init_md_blocks(chunk);
  1238. /* manage populated page bitmap */
  1239. chunk->immutable = true;
  1240. bitmap_fill(chunk->populated, chunk->nr_pages);
  1241. chunk->nr_populated = chunk->nr_pages;
  1242. chunk->nr_empty_pop_pages = chunk->nr_pages;
  1243. chunk->free_bytes = map_size;
  1244. if (chunk->start_offset) {
  1245. /* hide the beginning of the bitmap */
  1246. offset_bits = chunk->start_offset / PCPU_MIN_ALLOC_SIZE;
  1247. bitmap_set(chunk->alloc_map, 0, offset_bits);
  1248. set_bit(0, chunk->bound_map);
  1249. set_bit(offset_bits, chunk->bound_map);
  1250. chunk->chunk_md.first_free = offset_bits;
  1251. pcpu_block_update_hint_alloc(chunk, 0, offset_bits);
  1252. }
  1253. if (chunk->end_offset) {
  1254. /* hide the end of the bitmap */
  1255. offset_bits = chunk->end_offset / PCPU_MIN_ALLOC_SIZE;
  1256. bitmap_set(chunk->alloc_map,
  1257. pcpu_chunk_map_bits(chunk) - offset_bits,
  1258. offset_bits);
  1259. set_bit((start_offset + map_size) / PCPU_MIN_ALLOC_SIZE,
  1260. chunk->bound_map);
  1261. set_bit(region_bits, chunk->bound_map);
  1262. pcpu_block_update_hint_alloc(chunk, pcpu_chunk_map_bits(chunk)
  1263. - offset_bits, offset_bits);
  1264. }
  1265. return chunk;
  1266. }
  1267. static struct pcpu_chunk *pcpu_alloc_chunk(gfp_t gfp)
  1268. {
  1269. struct pcpu_chunk *chunk;
  1270. int region_bits;
  1271. chunk = pcpu_mem_zalloc(pcpu_chunk_struct_size, gfp);
  1272. if (!chunk)
  1273. return NULL;
  1274. INIT_LIST_HEAD(&chunk->list);
  1275. chunk->nr_pages = pcpu_unit_pages;
  1276. region_bits = pcpu_chunk_map_bits(chunk);
  1277. chunk->alloc_map = pcpu_mem_zalloc(BITS_TO_LONGS(region_bits) *
  1278. sizeof(chunk->alloc_map[0]), gfp);
  1279. if (!chunk->alloc_map)
  1280. goto alloc_map_fail;
  1281. chunk->bound_map = pcpu_mem_zalloc(BITS_TO_LONGS(region_bits + 1) *
  1282. sizeof(chunk->bound_map[0]), gfp);
  1283. if (!chunk->bound_map)
  1284. goto bound_map_fail;
  1285. chunk->md_blocks = pcpu_mem_zalloc(pcpu_chunk_nr_blocks(chunk) *
  1286. sizeof(chunk->md_blocks[0]), gfp);
  1287. if (!chunk->md_blocks)
  1288. goto md_blocks_fail;
  1289. #ifdef CONFIG_MEMCG_KMEM
  1290. if (!mem_cgroup_kmem_disabled()) {
  1291. chunk->obj_cgroups =
  1292. pcpu_mem_zalloc(pcpu_chunk_map_bits(chunk) *
  1293. sizeof(struct obj_cgroup *), gfp);
  1294. if (!chunk->obj_cgroups)
  1295. goto objcg_fail;
  1296. }
  1297. #endif
  1298. pcpu_init_md_blocks(chunk);
  1299. /* init metadata */
  1300. chunk->free_bytes = chunk->nr_pages * PAGE_SIZE;
  1301. return chunk;
  1302. #ifdef CONFIG_MEMCG_KMEM
  1303. objcg_fail:
  1304. pcpu_mem_free(chunk->md_blocks);
  1305. #endif
  1306. md_blocks_fail:
  1307. pcpu_mem_free(chunk->bound_map);
  1308. bound_map_fail:
  1309. pcpu_mem_free(chunk->alloc_map);
  1310. alloc_map_fail:
  1311. pcpu_mem_free(chunk);
  1312. return NULL;
  1313. }
  1314. static void pcpu_free_chunk(struct pcpu_chunk *chunk)
  1315. {
  1316. if (!chunk)
  1317. return;
  1318. #ifdef CONFIG_MEMCG_KMEM
  1319. pcpu_mem_free(chunk->obj_cgroups);
  1320. #endif
  1321. pcpu_mem_free(chunk->md_blocks);
  1322. pcpu_mem_free(chunk->bound_map);
  1323. pcpu_mem_free(chunk->alloc_map);
  1324. pcpu_mem_free(chunk);
  1325. }
  1326. /**
  1327. * pcpu_chunk_populated - post-population bookkeeping
  1328. * @chunk: pcpu_chunk which got populated
  1329. * @page_start: the start page
  1330. * @page_end: the end page
  1331. *
  1332. * Pages in [@page_start,@page_end) have been populated to @chunk. Update
  1333. * the bookkeeping information accordingly. Must be called after each
  1334. * successful population.
  1335. */
  1336. static void pcpu_chunk_populated(struct pcpu_chunk *chunk, int page_start,
  1337. int page_end)
  1338. {
  1339. int nr = page_end - page_start;
  1340. lockdep_assert_held(&pcpu_lock);
  1341. bitmap_set(chunk->populated, page_start, nr);
  1342. chunk->nr_populated += nr;
  1343. pcpu_nr_populated += nr;
  1344. pcpu_update_empty_pages(chunk, nr);
  1345. }
  1346. /**
  1347. * pcpu_chunk_depopulated - post-depopulation bookkeeping
  1348. * @chunk: pcpu_chunk which got depopulated
  1349. * @page_start: the start page
  1350. * @page_end: the end page
  1351. *
  1352. * Pages in [@page_start,@page_end) have been depopulated from @chunk.
  1353. * Update the bookkeeping information accordingly. Must be called after
  1354. * each successful depopulation.
  1355. */
  1356. static void pcpu_chunk_depopulated(struct pcpu_chunk *chunk,
  1357. int page_start, int page_end)
  1358. {
  1359. int nr = page_end - page_start;
  1360. lockdep_assert_held(&pcpu_lock);
  1361. bitmap_clear(chunk->populated, page_start, nr);
  1362. chunk->nr_populated -= nr;
  1363. pcpu_nr_populated -= nr;
  1364. pcpu_update_empty_pages(chunk, -nr);
  1365. }
  1366. /*
  1367. * Chunk management implementation.
  1368. *
  1369. * To allow different implementations, chunk alloc/free and
  1370. * [de]population are implemented in a separate file which is pulled
  1371. * into this file and compiled together. The following functions
  1372. * should be implemented.
  1373. *
  1374. * pcpu_populate_chunk - populate the specified range of a chunk
  1375. * pcpu_depopulate_chunk - depopulate the specified range of a chunk
  1376. * pcpu_post_unmap_tlb_flush - flush tlb for the specified range of a chunk
  1377. * pcpu_create_chunk - create a new chunk
  1378. * pcpu_destroy_chunk - destroy a chunk, always preceded by full depop
  1379. * pcpu_addr_to_page - translate address to physical address
  1380. * pcpu_verify_alloc_info - check alloc_info is acceptable during init
  1381. */
  1382. static int pcpu_populate_chunk(struct pcpu_chunk *chunk,
  1383. int page_start, int page_end, gfp_t gfp);
  1384. static void pcpu_depopulate_chunk(struct pcpu_chunk *chunk,
  1385. int page_start, int page_end);
  1386. static void pcpu_post_unmap_tlb_flush(struct pcpu_chunk *chunk,
  1387. int page_start, int page_end);
  1388. static struct pcpu_chunk *pcpu_create_chunk(gfp_t gfp);
  1389. static void pcpu_destroy_chunk(struct pcpu_chunk *chunk);
  1390. static struct page *pcpu_addr_to_page(void *addr);
  1391. static int __init pcpu_verify_alloc_info(const struct pcpu_alloc_info *ai);
  1392. #ifdef CONFIG_NEED_PER_CPU_KM
  1393. #include "percpu-km.c"
  1394. #else
  1395. #include "percpu-vm.c"
  1396. #endif
  1397. /**
  1398. * pcpu_chunk_addr_search - determine chunk containing specified address
  1399. * @addr: address for which the chunk needs to be determined.
  1400. *
  1401. * This is an internal function that handles all but static allocations.
  1402. * Static percpu address values should never be passed into the allocator.
  1403. *
  1404. * RETURNS:
  1405. * The address of the found chunk.
  1406. */
  1407. static struct pcpu_chunk *pcpu_chunk_addr_search(void *addr)
  1408. {
  1409. /* is it in the dynamic region (first chunk)? */
  1410. if (pcpu_addr_in_chunk(pcpu_first_chunk, addr))
  1411. return pcpu_first_chunk;
  1412. /* is it in the reserved region? */
  1413. if (pcpu_addr_in_chunk(pcpu_reserved_chunk, addr))
  1414. return pcpu_reserved_chunk;
  1415. /*
  1416. * The address is relative to unit0 which might be unused and
  1417. * thus unmapped. Offset the address to the unit space of the
  1418. * current processor before looking it up in the vmalloc
  1419. * space. Note that any possible cpu id can be used here, so
  1420. * there's no need to worry about preemption or cpu hotplug.
  1421. */
  1422. addr += pcpu_unit_offsets[raw_smp_processor_id()];
  1423. return pcpu_get_page_chunk(pcpu_addr_to_page(addr));
  1424. }
  1425. #ifdef CONFIG_MEMCG_KMEM
  1426. static bool pcpu_memcg_pre_alloc_hook(size_t size, gfp_t gfp,
  1427. struct obj_cgroup **objcgp)
  1428. {
  1429. struct obj_cgroup *objcg;
  1430. if (!memcg_kmem_enabled() || !(gfp & __GFP_ACCOUNT))
  1431. return true;
  1432. objcg = get_obj_cgroup_from_current();
  1433. if (!objcg)
  1434. return true;
  1435. if (obj_cgroup_charge(objcg, gfp, pcpu_obj_full_size(size))) {
  1436. obj_cgroup_put(objcg);
  1437. return false;
  1438. }
  1439. *objcgp = objcg;
  1440. return true;
  1441. }
  1442. static void pcpu_memcg_post_alloc_hook(struct obj_cgroup *objcg,
  1443. struct pcpu_chunk *chunk, int off,
  1444. size_t size)
  1445. {
  1446. if (!objcg)
  1447. return;
  1448. if (likely(chunk && chunk->obj_cgroups)) {
  1449. chunk->obj_cgroups[off >> PCPU_MIN_ALLOC_SHIFT] = objcg;
  1450. rcu_read_lock();
  1451. mod_memcg_state(obj_cgroup_memcg(objcg), MEMCG_PERCPU_B,
  1452. pcpu_obj_full_size(size));
  1453. rcu_read_unlock();
  1454. } else {
  1455. obj_cgroup_uncharge(objcg, pcpu_obj_full_size(size));
  1456. obj_cgroup_put(objcg);
  1457. }
  1458. }
  1459. static void pcpu_memcg_free_hook(struct pcpu_chunk *chunk, int off, size_t size)
  1460. {
  1461. struct obj_cgroup *objcg;
  1462. if (unlikely(!chunk->obj_cgroups))
  1463. return;
  1464. objcg = chunk->obj_cgroups[off >> PCPU_MIN_ALLOC_SHIFT];
  1465. if (!objcg)
  1466. return;
  1467. chunk->obj_cgroups[off >> PCPU_MIN_ALLOC_SHIFT] = NULL;
  1468. obj_cgroup_uncharge(objcg, pcpu_obj_full_size(size));
  1469. rcu_read_lock();
  1470. mod_memcg_state(obj_cgroup_memcg(objcg), MEMCG_PERCPU_B,
  1471. -pcpu_obj_full_size(size));
  1472. rcu_read_unlock();
  1473. obj_cgroup_put(objcg);
  1474. }
  1475. #else /* CONFIG_MEMCG_KMEM */
  1476. static bool
  1477. pcpu_memcg_pre_alloc_hook(size_t size, gfp_t gfp, struct obj_cgroup **objcgp)
  1478. {
  1479. return true;
  1480. }
  1481. static void pcpu_memcg_post_alloc_hook(struct obj_cgroup *objcg,
  1482. struct pcpu_chunk *chunk, int off,
  1483. size_t size)
  1484. {
  1485. }
  1486. static void pcpu_memcg_free_hook(struct pcpu_chunk *chunk, int off, size_t size)
  1487. {
  1488. }
  1489. #endif /* CONFIG_MEMCG_KMEM */
  1490. /**
  1491. * pcpu_alloc - the percpu allocator
  1492. * @size: size of area to allocate in bytes
  1493. * @align: alignment of area (max PAGE_SIZE)
  1494. * @reserved: allocate from the reserved chunk if available
  1495. * @gfp: allocation flags
  1496. *
  1497. * Allocate percpu area of @size bytes aligned at @align. If @gfp doesn't
  1498. * contain %GFP_KERNEL, the allocation is atomic. If @gfp has __GFP_NOWARN
  1499. * then no warning will be triggered on invalid or failed allocation
  1500. * requests.
  1501. *
  1502. * RETURNS:
  1503. * Percpu pointer to the allocated area on success, NULL on failure.
  1504. */
  1505. static void __percpu *pcpu_alloc(size_t size, size_t align, bool reserved,
  1506. gfp_t gfp)
  1507. {
  1508. gfp_t pcpu_gfp;
  1509. bool is_atomic;
  1510. bool do_warn;
  1511. struct obj_cgroup *objcg = NULL;
  1512. static int warn_limit = 10;
  1513. struct pcpu_chunk *chunk, *next;
  1514. const char *err;
  1515. int slot, off, cpu, ret;
  1516. unsigned long flags;
  1517. void __percpu *ptr;
  1518. size_t bits, bit_align;
  1519. gfp = current_gfp_context(gfp);
  1520. /* whitelisted flags that can be passed to the backing allocators */
  1521. pcpu_gfp = gfp & (GFP_KERNEL | __GFP_NORETRY | __GFP_NOWARN);
  1522. is_atomic = (gfp & GFP_KERNEL) != GFP_KERNEL;
  1523. do_warn = !(gfp & __GFP_NOWARN);
  1524. /*
  1525. * There is now a minimum allocation size of PCPU_MIN_ALLOC_SIZE,
  1526. * therefore alignment must be a minimum of that many bytes.
  1527. * An allocation may have internal fragmentation from rounding up
  1528. * of up to PCPU_MIN_ALLOC_SIZE - 1 bytes.
  1529. */
  1530. if (unlikely(align < PCPU_MIN_ALLOC_SIZE))
  1531. align = PCPU_MIN_ALLOC_SIZE;
  1532. size = ALIGN(size, PCPU_MIN_ALLOC_SIZE);
  1533. bits = size >> PCPU_MIN_ALLOC_SHIFT;
  1534. bit_align = align >> PCPU_MIN_ALLOC_SHIFT;
  1535. if (unlikely(!size || size > PCPU_MIN_UNIT_SIZE || align > PAGE_SIZE ||
  1536. !is_power_of_2(align))) {
  1537. WARN(do_warn, "illegal size (%zu) or align (%zu) for percpu allocation\n",
  1538. size, align);
  1539. return NULL;
  1540. }
  1541. if (unlikely(!pcpu_memcg_pre_alloc_hook(size, gfp, &objcg)))
  1542. return NULL;
  1543. if (!is_atomic) {
  1544. /*
  1545. * pcpu_balance_workfn() allocates memory under this mutex,
  1546. * and it may wait for memory reclaim. Allow current task
  1547. * to become OOM victim, in case of memory pressure.
  1548. */
  1549. if (gfp & __GFP_NOFAIL) {
  1550. mutex_lock(&pcpu_alloc_mutex);
  1551. } else if (mutex_lock_killable(&pcpu_alloc_mutex)) {
  1552. pcpu_memcg_post_alloc_hook(objcg, NULL, 0, size);
  1553. return NULL;
  1554. }
  1555. }
  1556. spin_lock_irqsave(&pcpu_lock, flags);
  1557. /* serve reserved allocations from the reserved chunk if available */
  1558. if (reserved && pcpu_reserved_chunk) {
  1559. chunk = pcpu_reserved_chunk;
  1560. off = pcpu_find_block_fit(chunk, bits, bit_align, is_atomic);
  1561. if (off < 0) {
  1562. err = "alloc from reserved chunk failed";
  1563. goto fail_unlock;
  1564. }
  1565. off = pcpu_alloc_area(chunk, bits, bit_align, off);
  1566. if (off >= 0)
  1567. goto area_found;
  1568. err = "alloc from reserved chunk failed";
  1569. goto fail_unlock;
  1570. }
  1571. restart:
  1572. /* search through normal chunks */
  1573. for (slot = pcpu_size_to_slot(size); slot <= pcpu_free_slot; slot++) {
  1574. list_for_each_entry_safe(chunk, next, &pcpu_chunk_lists[slot],
  1575. list) {
  1576. off = pcpu_find_block_fit(chunk, bits, bit_align,
  1577. is_atomic);
  1578. if (off < 0) {
  1579. if (slot < PCPU_SLOT_FAIL_THRESHOLD)
  1580. pcpu_chunk_move(chunk, 0);
  1581. continue;
  1582. }
  1583. off = pcpu_alloc_area(chunk, bits, bit_align, off);
  1584. if (off >= 0) {
  1585. pcpu_reintegrate_chunk(chunk);
  1586. goto area_found;
  1587. }
  1588. }
  1589. }
  1590. spin_unlock_irqrestore(&pcpu_lock, flags);
  1591. /*
  1592. * No space left. Create a new chunk. We don't want multiple
  1593. * tasks to create chunks simultaneously. Serialize and create iff
  1594. * there's still no empty chunk after grabbing the mutex.
  1595. */
  1596. if (is_atomic) {
  1597. err = "atomic alloc failed, no space left";
  1598. goto fail;
  1599. }
  1600. if (list_empty(&pcpu_chunk_lists[pcpu_free_slot])) {
  1601. chunk = pcpu_create_chunk(pcpu_gfp);
  1602. if (!chunk) {
  1603. err = "failed to allocate new chunk";
  1604. goto fail;
  1605. }
  1606. spin_lock_irqsave(&pcpu_lock, flags);
  1607. pcpu_chunk_relocate(chunk, -1);
  1608. } else {
  1609. spin_lock_irqsave(&pcpu_lock, flags);
  1610. }
  1611. goto restart;
  1612. area_found:
  1613. pcpu_stats_area_alloc(chunk, size);
  1614. spin_unlock_irqrestore(&pcpu_lock, flags);
  1615. /* populate if not all pages are already there */
  1616. if (!is_atomic) {
  1617. unsigned int page_end, rs, re;
  1618. rs = PFN_DOWN(off);
  1619. page_end = PFN_UP(off + size);
  1620. for_each_clear_bitrange_from(rs, re, chunk->populated, page_end) {
  1621. WARN_ON(chunk->immutable);
  1622. ret = pcpu_populate_chunk(chunk, rs, re, pcpu_gfp);
  1623. spin_lock_irqsave(&pcpu_lock, flags);
  1624. if (ret) {
  1625. pcpu_free_area(chunk, off);
  1626. err = "failed to populate";
  1627. goto fail_unlock;
  1628. }
  1629. pcpu_chunk_populated(chunk, rs, re);
  1630. spin_unlock_irqrestore(&pcpu_lock, flags);
  1631. }
  1632. mutex_unlock(&pcpu_alloc_mutex);
  1633. }
  1634. if (pcpu_nr_empty_pop_pages < PCPU_EMPTY_POP_PAGES_LOW)
  1635. pcpu_schedule_balance_work();
  1636. /* clear the areas and return address relative to base address */
  1637. for_each_possible_cpu(cpu)
  1638. memset((void *)pcpu_chunk_addr(chunk, cpu, 0) + off, 0, size);
  1639. ptr = __addr_to_pcpu_ptr(chunk->base_addr + off);
  1640. kmemleak_alloc_percpu(ptr, size, gfp);
  1641. trace_percpu_alloc_percpu(_RET_IP_, reserved, is_atomic, size, align,
  1642. chunk->base_addr, off, ptr,
  1643. pcpu_obj_full_size(size), gfp);
  1644. pcpu_memcg_post_alloc_hook(objcg, chunk, off, size);
  1645. return ptr;
  1646. fail_unlock:
  1647. spin_unlock_irqrestore(&pcpu_lock, flags);
  1648. fail:
  1649. trace_percpu_alloc_percpu_fail(reserved, is_atomic, size, align);
  1650. if (!is_atomic && do_warn && warn_limit) {
  1651. pr_warn("allocation failed, size=%zu align=%zu atomic=%d, %s\n",
  1652. size, align, is_atomic, err);
  1653. dump_stack();
  1654. if (!--warn_limit)
  1655. pr_info("limit reached, disable warning\n");
  1656. }
  1657. if (is_atomic) {
  1658. /* see the flag handling in pcpu_balance_workfn() */
  1659. pcpu_atomic_alloc_failed = true;
  1660. pcpu_schedule_balance_work();
  1661. } else {
  1662. mutex_unlock(&pcpu_alloc_mutex);
  1663. }
  1664. pcpu_memcg_post_alloc_hook(objcg, NULL, 0, size);
  1665. return NULL;
  1666. }
  1667. /**
  1668. * __alloc_percpu_gfp - allocate dynamic percpu area
  1669. * @size: size of area to allocate in bytes
  1670. * @align: alignment of area (max PAGE_SIZE)
  1671. * @gfp: allocation flags
  1672. *
  1673. * Allocate zero-filled percpu area of @size bytes aligned at @align. If
  1674. * @gfp doesn't contain %GFP_KERNEL, the allocation doesn't block and can
  1675. * be called from any context but is a lot more likely to fail. If @gfp
  1676. * has __GFP_NOWARN then no warning will be triggered on invalid or failed
  1677. * allocation requests.
  1678. *
  1679. * RETURNS:
  1680. * Percpu pointer to the allocated area on success, NULL on failure.
  1681. */
  1682. void __percpu *__alloc_percpu_gfp(size_t size, size_t align, gfp_t gfp)
  1683. {
  1684. return pcpu_alloc(size, align, false, gfp);
  1685. }
  1686. EXPORT_SYMBOL_GPL(__alloc_percpu_gfp);
  1687. /**
  1688. * __alloc_percpu - allocate dynamic percpu area
  1689. * @size: size of area to allocate in bytes
  1690. * @align: alignment of area (max PAGE_SIZE)
  1691. *
  1692. * Equivalent to __alloc_percpu_gfp(size, align, %GFP_KERNEL).
  1693. */
  1694. void __percpu *__alloc_percpu(size_t size, size_t align)
  1695. {
  1696. return pcpu_alloc(size, align, false, GFP_KERNEL);
  1697. }
  1698. EXPORT_SYMBOL_GPL(__alloc_percpu);
  1699. /**
  1700. * __alloc_reserved_percpu - allocate reserved percpu area
  1701. * @size: size of area to allocate in bytes
  1702. * @align: alignment of area (max PAGE_SIZE)
  1703. *
  1704. * Allocate zero-filled percpu area of @size bytes aligned at @align
  1705. * from reserved percpu area if arch has set it up; otherwise,
  1706. * allocation is served from the same dynamic area. Might sleep.
  1707. * Might trigger writeouts.
  1708. *
  1709. * CONTEXT:
  1710. * Does GFP_KERNEL allocation.
  1711. *
  1712. * RETURNS:
  1713. * Percpu pointer to the allocated area on success, NULL on failure.
  1714. */
  1715. void __percpu *__alloc_reserved_percpu(size_t size, size_t align)
  1716. {
  1717. return pcpu_alloc(size, align, true, GFP_KERNEL);
  1718. }
  1719. /**
  1720. * pcpu_balance_free - manage the amount of free chunks
  1721. * @empty_only: free chunks only if there are no populated pages
  1722. *
  1723. * If empty_only is %false, reclaim all fully free chunks regardless of the
  1724. * number of populated pages. Otherwise, only reclaim chunks that have no
  1725. * populated pages.
  1726. *
  1727. * CONTEXT:
  1728. * pcpu_lock (can be dropped temporarily)
  1729. */
  1730. static void pcpu_balance_free(bool empty_only)
  1731. {
  1732. LIST_HEAD(to_free);
  1733. struct list_head *free_head = &pcpu_chunk_lists[pcpu_free_slot];
  1734. struct pcpu_chunk *chunk, *next;
  1735. lockdep_assert_held(&pcpu_lock);
  1736. /*
  1737. * There's no reason to keep around multiple unused chunks and VM
  1738. * areas can be scarce. Destroy all free chunks except for one.
  1739. */
  1740. list_for_each_entry_safe(chunk, next, free_head, list) {
  1741. WARN_ON(chunk->immutable);
  1742. /* spare the first one */
  1743. if (chunk == list_first_entry(free_head, struct pcpu_chunk, list))
  1744. continue;
  1745. if (!empty_only || chunk->nr_empty_pop_pages == 0)
  1746. list_move(&chunk->list, &to_free);
  1747. }
  1748. if (list_empty(&to_free))
  1749. return;
  1750. spin_unlock_irq(&pcpu_lock);
  1751. list_for_each_entry_safe(chunk, next, &to_free, list) {
  1752. unsigned int rs, re;
  1753. for_each_set_bitrange(rs, re, chunk->populated, chunk->nr_pages) {
  1754. pcpu_depopulate_chunk(chunk, rs, re);
  1755. spin_lock_irq(&pcpu_lock);
  1756. pcpu_chunk_depopulated(chunk, rs, re);
  1757. spin_unlock_irq(&pcpu_lock);
  1758. }
  1759. pcpu_destroy_chunk(chunk);
  1760. cond_resched();
  1761. }
  1762. spin_lock_irq(&pcpu_lock);
  1763. }
  1764. /**
  1765. * pcpu_balance_populated - manage the amount of populated pages
  1766. *
  1767. * Maintain a certain amount of populated pages to satisfy atomic allocations.
  1768. * It is possible that this is called when physical memory is scarce causing
  1769. * OOM killer to be triggered. We should avoid doing so until an actual
  1770. * allocation causes the failure as it is possible that requests can be
  1771. * serviced from already backed regions.
  1772. *
  1773. * CONTEXT:
  1774. * pcpu_lock (can be dropped temporarily)
  1775. */
  1776. static void pcpu_balance_populated(void)
  1777. {
  1778. /* gfp flags passed to underlying allocators */
  1779. const gfp_t gfp = GFP_KERNEL | __GFP_NORETRY | __GFP_NOWARN;
  1780. struct pcpu_chunk *chunk;
  1781. int slot, nr_to_pop, ret;
  1782. lockdep_assert_held(&pcpu_lock);
  1783. /*
  1784. * Ensure there are certain number of free populated pages for
  1785. * atomic allocs. Fill up from the most packed so that atomic
  1786. * allocs don't increase fragmentation. If atomic allocation
  1787. * failed previously, always populate the maximum amount. This
  1788. * should prevent atomic allocs larger than PAGE_SIZE from keeping
  1789. * failing indefinitely; however, large atomic allocs are not
  1790. * something we support properly and can be highly unreliable and
  1791. * inefficient.
  1792. */
  1793. retry_pop:
  1794. if (pcpu_atomic_alloc_failed) {
  1795. nr_to_pop = PCPU_EMPTY_POP_PAGES_HIGH;
  1796. /* best effort anyway, don't worry about synchronization */
  1797. pcpu_atomic_alloc_failed = false;
  1798. } else {
  1799. nr_to_pop = clamp(PCPU_EMPTY_POP_PAGES_HIGH -
  1800. pcpu_nr_empty_pop_pages,
  1801. 0, PCPU_EMPTY_POP_PAGES_HIGH);
  1802. }
  1803. for (slot = pcpu_size_to_slot(PAGE_SIZE); slot <= pcpu_free_slot; slot++) {
  1804. unsigned int nr_unpop = 0, rs, re;
  1805. if (!nr_to_pop)
  1806. break;
  1807. list_for_each_entry(chunk, &pcpu_chunk_lists[slot], list) {
  1808. nr_unpop = chunk->nr_pages - chunk->nr_populated;
  1809. if (nr_unpop)
  1810. break;
  1811. }
  1812. if (!nr_unpop)
  1813. continue;
  1814. /* @chunk can't go away while pcpu_alloc_mutex is held */
  1815. for_each_clear_bitrange(rs, re, chunk->populated, chunk->nr_pages) {
  1816. int nr = min_t(int, re - rs, nr_to_pop);
  1817. spin_unlock_irq(&pcpu_lock);
  1818. ret = pcpu_populate_chunk(chunk, rs, rs + nr, gfp);
  1819. cond_resched();
  1820. spin_lock_irq(&pcpu_lock);
  1821. if (!ret) {
  1822. nr_to_pop -= nr;
  1823. pcpu_chunk_populated(chunk, rs, rs + nr);
  1824. } else {
  1825. nr_to_pop = 0;
  1826. }
  1827. if (!nr_to_pop)
  1828. break;
  1829. }
  1830. }
  1831. if (nr_to_pop) {
  1832. /* ran out of chunks to populate, create a new one and retry */
  1833. spin_unlock_irq(&pcpu_lock);
  1834. chunk = pcpu_create_chunk(gfp);
  1835. cond_resched();
  1836. spin_lock_irq(&pcpu_lock);
  1837. if (chunk) {
  1838. pcpu_chunk_relocate(chunk, -1);
  1839. goto retry_pop;
  1840. }
  1841. }
  1842. }
  1843. /**
  1844. * pcpu_reclaim_populated - scan over to_depopulate chunks and free empty pages
  1845. *
  1846. * Scan over chunks in the depopulate list and try to release unused populated
  1847. * pages back to the system. Depopulated chunks are sidelined to prevent
  1848. * repopulating these pages unless required. Fully free chunks are reintegrated
  1849. * and freed accordingly (1 is kept around). If we drop below the empty
  1850. * populated pages threshold, reintegrate the chunk if it has empty free pages.
  1851. * Each chunk is scanned in the reverse order to keep populated pages close to
  1852. * the beginning of the chunk.
  1853. *
  1854. * CONTEXT:
  1855. * pcpu_lock (can be dropped temporarily)
  1856. *
  1857. */
  1858. static void pcpu_reclaim_populated(void)
  1859. {
  1860. struct pcpu_chunk *chunk;
  1861. struct pcpu_block_md *block;
  1862. int freed_page_start, freed_page_end;
  1863. int i, end;
  1864. bool reintegrate;
  1865. lockdep_assert_held(&pcpu_lock);
  1866. /*
  1867. * Once a chunk is isolated to the to_depopulate list, the chunk is no
  1868. * longer discoverable to allocations whom may populate pages. The only
  1869. * other accessor is the free path which only returns area back to the
  1870. * allocator not touching the populated bitmap.
  1871. */
  1872. while (!list_empty(&pcpu_chunk_lists[pcpu_to_depopulate_slot])) {
  1873. chunk = list_first_entry(&pcpu_chunk_lists[pcpu_to_depopulate_slot],
  1874. struct pcpu_chunk, list);
  1875. WARN_ON(chunk->immutable);
  1876. /*
  1877. * Scan chunk's pages in the reverse order to keep populated
  1878. * pages close to the beginning of the chunk.
  1879. */
  1880. freed_page_start = chunk->nr_pages;
  1881. freed_page_end = 0;
  1882. reintegrate = false;
  1883. for (i = chunk->nr_pages - 1, end = -1; i >= 0; i--) {
  1884. /* no more work to do */
  1885. if (chunk->nr_empty_pop_pages == 0)
  1886. break;
  1887. /* reintegrate chunk to prevent atomic alloc failures */
  1888. if (pcpu_nr_empty_pop_pages < PCPU_EMPTY_POP_PAGES_HIGH) {
  1889. reintegrate = true;
  1890. goto end_chunk;
  1891. }
  1892. /*
  1893. * If the page is empty and populated, start or
  1894. * extend the (i, end) range. If i == 0, decrease
  1895. * i and perform the depopulation to cover the last
  1896. * (first) page in the chunk.
  1897. */
  1898. block = chunk->md_blocks + i;
  1899. if (block->contig_hint == PCPU_BITMAP_BLOCK_BITS &&
  1900. test_bit(i, chunk->populated)) {
  1901. if (end == -1)
  1902. end = i;
  1903. if (i > 0)
  1904. continue;
  1905. i--;
  1906. }
  1907. /* depopulate if there is an active range */
  1908. if (end == -1)
  1909. continue;
  1910. spin_unlock_irq(&pcpu_lock);
  1911. pcpu_depopulate_chunk(chunk, i + 1, end + 1);
  1912. cond_resched();
  1913. spin_lock_irq(&pcpu_lock);
  1914. pcpu_chunk_depopulated(chunk, i + 1, end + 1);
  1915. freed_page_start = min(freed_page_start, i + 1);
  1916. freed_page_end = max(freed_page_end, end + 1);
  1917. /* reset the range and continue */
  1918. end = -1;
  1919. }
  1920. end_chunk:
  1921. /* batch tlb flush per chunk to amortize cost */
  1922. if (freed_page_start < freed_page_end) {
  1923. spin_unlock_irq(&pcpu_lock);
  1924. pcpu_post_unmap_tlb_flush(chunk,
  1925. freed_page_start,
  1926. freed_page_end);
  1927. cond_resched();
  1928. spin_lock_irq(&pcpu_lock);
  1929. }
  1930. if (reintegrate || chunk->free_bytes == pcpu_unit_size)
  1931. pcpu_reintegrate_chunk(chunk);
  1932. else
  1933. list_move_tail(&chunk->list,
  1934. &pcpu_chunk_lists[pcpu_sidelined_slot]);
  1935. }
  1936. }
  1937. /**
  1938. * pcpu_balance_workfn - manage the amount of free chunks and populated pages
  1939. * @work: unused
  1940. *
  1941. * For each chunk type, manage the number of fully free chunks and the number of
  1942. * populated pages. An important thing to consider is when pages are freed and
  1943. * how they contribute to the global counts.
  1944. */
  1945. static void pcpu_balance_workfn(struct work_struct *work)
  1946. {
  1947. /*
  1948. * pcpu_balance_free() is called twice because the first time we may
  1949. * trim pages in the active pcpu_nr_empty_pop_pages which may cause us
  1950. * to grow other chunks. This then gives pcpu_reclaim_populated() time
  1951. * to move fully free chunks to the active list to be freed if
  1952. * appropriate.
  1953. */
  1954. mutex_lock(&pcpu_alloc_mutex);
  1955. spin_lock_irq(&pcpu_lock);
  1956. pcpu_balance_free(false);
  1957. pcpu_reclaim_populated();
  1958. pcpu_balance_populated();
  1959. pcpu_balance_free(true);
  1960. spin_unlock_irq(&pcpu_lock);
  1961. mutex_unlock(&pcpu_alloc_mutex);
  1962. }
  1963. /**
  1964. * free_percpu - free percpu area
  1965. * @ptr: pointer to area to free
  1966. *
  1967. * Free percpu area @ptr.
  1968. *
  1969. * CONTEXT:
  1970. * Can be called from atomic context.
  1971. */
  1972. void free_percpu(void __percpu *ptr)
  1973. {
  1974. void *addr;
  1975. struct pcpu_chunk *chunk;
  1976. unsigned long flags;
  1977. int size, off;
  1978. bool need_balance = false;
  1979. if (!ptr)
  1980. return;
  1981. kmemleak_free_percpu(ptr);
  1982. addr = __pcpu_ptr_to_addr(ptr);
  1983. spin_lock_irqsave(&pcpu_lock, flags);
  1984. chunk = pcpu_chunk_addr_search(addr);
  1985. off = addr - chunk->base_addr;
  1986. size = pcpu_free_area(chunk, off);
  1987. pcpu_memcg_free_hook(chunk, off, size);
  1988. /*
  1989. * If there are more than one fully free chunks, wake up grim reaper.
  1990. * If the chunk is isolated, it may be in the process of being
  1991. * reclaimed. Let reclaim manage cleaning up of that chunk.
  1992. */
  1993. if (!chunk->isolated && chunk->free_bytes == pcpu_unit_size) {
  1994. struct pcpu_chunk *pos;
  1995. list_for_each_entry(pos, &pcpu_chunk_lists[pcpu_free_slot], list)
  1996. if (pos != chunk) {
  1997. need_balance = true;
  1998. break;
  1999. }
  2000. } else if (pcpu_should_reclaim_chunk(chunk)) {
  2001. pcpu_isolate_chunk(chunk);
  2002. need_balance = true;
  2003. }
  2004. trace_percpu_free_percpu(chunk->base_addr, off, ptr);
  2005. spin_unlock_irqrestore(&pcpu_lock, flags);
  2006. if (need_balance)
  2007. pcpu_schedule_balance_work();
  2008. }
  2009. EXPORT_SYMBOL_GPL(free_percpu);
  2010. bool __is_kernel_percpu_address(unsigned long addr, unsigned long *can_addr)
  2011. {
  2012. #ifdef CONFIG_SMP
  2013. const size_t static_size = __per_cpu_end - __per_cpu_start;
  2014. void __percpu *base = __addr_to_pcpu_ptr(pcpu_base_addr);
  2015. unsigned int cpu;
  2016. for_each_possible_cpu(cpu) {
  2017. void *start = per_cpu_ptr(base, cpu);
  2018. void *va = (void *)addr;
  2019. if (va >= start && va < start + static_size) {
  2020. if (can_addr) {
  2021. *can_addr = (unsigned long) (va - start);
  2022. *can_addr += (unsigned long)
  2023. per_cpu_ptr(base, get_boot_cpu_id());
  2024. }
  2025. return true;
  2026. }
  2027. }
  2028. #endif
  2029. /* on UP, can't distinguish from other static vars, always false */
  2030. return false;
  2031. }
  2032. /**
  2033. * is_kernel_percpu_address - test whether address is from static percpu area
  2034. * @addr: address to test
  2035. *
  2036. * Test whether @addr belongs to in-kernel static percpu area. Module
  2037. * static percpu areas are not considered. For those, use
  2038. * is_module_percpu_address().
  2039. *
  2040. * RETURNS:
  2041. * %true if @addr is from in-kernel static percpu area, %false otherwise.
  2042. */
  2043. bool is_kernel_percpu_address(unsigned long addr)
  2044. {
  2045. return __is_kernel_percpu_address(addr, NULL);
  2046. }
  2047. /**
  2048. * per_cpu_ptr_to_phys - convert translated percpu address to physical address
  2049. * @addr: the address to be converted to physical address
  2050. *
  2051. * Given @addr which is dereferenceable address obtained via one of
  2052. * percpu access macros, this function translates it into its physical
  2053. * address. The caller is responsible for ensuring @addr stays valid
  2054. * until this function finishes.
  2055. *
  2056. * percpu allocator has special setup for the first chunk, which currently
  2057. * supports either embedding in linear address space or vmalloc mapping,
  2058. * and, from the second one, the backing allocator (currently either vm or
  2059. * km) provides translation.
  2060. *
  2061. * The addr can be translated simply without checking if it falls into the
  2062. * first chunk. But the current code reflects better how percpu allocator
  2063. * actually works, and the verification can discover both bugs in percpu
  2064. * allocator itself and per_cpu_ptr_to_phys() callers. So we keep current
  2065. * code.
  2066. *
  2067. * RETURNS:
  2068. * The physical address for @addr.
  2069. */
  2070. phys_addr_t per_cpu_ptr_to_phys(void *addr)
  2071. {
  2072. void __percpu *base = __addr_to_pcpu_ptr(pcpu_base_addr);
  2073. bool in_first_chunk = false;
  2074. unsigned long first_low, first_high;
  2075. unsigned int cpu;
  2076. /*
  2077. * The following test on unit_low/high isn't strictly
  2078. * necessary but will speed up lookups of addresses which
  2079. * aren't in the first chunk.
  2080. *
  2081. * The address check is against full chunk sizes. pcpu_base_addr
  2082. * points to the beginning of the first chunk including the
  2083. * static region. Assumes good intent as the first chunk may
  2084. * not be full (ie. < pcpu_unit_pages in size).
  2085. */
  2086. first_low = (unsigned long)pcpu_base_addr +
  2087. pcpu_unit_page_offset(pcpu_low_unit_cpu, 0);
  2088. first_high = (unsigned long)pcpu_base_addr +
  2089. pcpu_unit_page_offset(pcpu_high_unit_cpu, pcpu_unit_pages);
  2090. if ((unsigned long)addr >= first_low &&
  2091. (unsigned long)addr < first_high) {
  2092. for_each_possible_cpu(cpu) {
  2093. void *start = per_cpu_ptr(base, cpu);
  2094. if (addr >= start && addr < start + pcpu_unit_size) {
  2095. in_first_chunk = true;
  2096. break;
  2097. }
  2098. }
  2099. }
  2100. if (in_first_chunk) {
  2101. if (!is_vmalloc_addr(addr))
  2102. return __pa(addr);
  2103. else
  2104. return page_to_phys(vmalloc_to_page(addr)) +
  2105. offset_in_page(addr);
  2106. } else
  2107. return page_to_phys(pcpu_addr_to_page(addr)) +
  2108. offset_in_page(addr);
  2109. }
  2110. EXPORT_SYMBOL_GPL(per_cpu_ptr_to_phys);
  2111. /**
  2112. * pcpu_alloc_alloc_info - allocate percpu allocation info
  2113. * @nr_groups: the number of groups
  2114. * @nr_units: the number of units
  2115. *
  2116. * Allocate ai which is large enough for @nr_groups groups containing
  2117. * @nr_units units. The returned ai's groups[0].cpu_map points to the
  2118. * cpu_map array which is long enough for @nr_units and filled with
  2119. * NR_CPUS. It's the caller's responsibility to initialize cpu_map
  2120. * pointer of other groups.
  2121. *
  2122. * RETURNS:
  2123. * Pointer to the allocated pcpu_alloc_info on success, NULL on
  2124. * failure.
  2125. */
  2126. struct pcpu_alloc_info * __init pcpu_alloc_alloc_info(int nr_groups,
  2127. int nr_units)
  2128. {
  2129. struct pcpu_alloc_info *ai;
  2130. size_t base_size, ai_size;
  2131. void *ptr;
  2132. int unit;
  2133. base_size = ALIGN(struct_size(ai, groups, nr_groups),
  2134. __alignof__(ai->groups[0].cpu_map[0]));
  2135. ai_size = base_size + nr_units * sizeof(ai->groups[0].cpu_map[0]);
  2136. ptr = memblock_alloc(PFN_ALIGN(ai_size), PAGE_SIZE);
  2137. if (!ptr)
  2138. return NULL;
  2139. ai = ptr;
  2140. ptr += base_size;
  2141. ai->groups[0].cpu_map = ptr;
  2142. for (unit = 0; unit < nr_units; unit++)
  2143. ai->groups[0].cpu_map[unit] = NR_CPUS;
  2144. ai->nr_groups = nr_groups;
  2145. ai->__ai_size = PFN_ALIGN(ai_size);
  2146. return ai;
  2147. }
  2148. /**
  2149. * pcpu_free_alloc_info - free percpu allocation info
  2150. * @ai: pcpu_alloc_info to free
  2151. *
  2152. * Free @ai which was allocated by pcpu_alloc_alloc_info().
  2153. */
  2154. void __init pcpu_free_alloc_info(struct pcpu_alloc_info *ai)
  2155. {
  2156. memblock_free(ai, ai->__ai_size);
  2157. }
  2158. /**
  2159. * pcpu_dump_alloc_info - print out information about pcpu_alloc_info
  2160. * @lvl: loglevel
  2161. * @ai: allocation info to dump
  2162. *
  2163. * Print out information about @ai using loglevel @lvl.
  2164. */
  2165. static void pcpu_dump_alloc_info(const char *lvl,
  2166. const struct pcpu_alloc_info *ai)
  2167. {
  2168. int group_width = 1, cpu_width = 1, width;
  2169. char empty_str[] = "--------";
  2170. int alloc = 0, alloc_end = 0;
  2171. int group, v;
  2172. int upa, apl; /* units per alloc, allocs per line */
  2173. v = ai->nr_groups;
  2174. while (v /= 10)
  2175. group_width++;
  2176. v = num_possible_cpus();
  2177. while (v /= 10)
  2178. cpu_width++;
  2179. empty_str[min_t(int, cpu_width, sizeof(empty_str) - 1)] = '\0';
  2180. upa = ai->alloc_size / ai->unit_size;
  2181. width = upa * (cpu_width + 1) + group_width + 3;
  2182. apl = rounddown_pow_of_two(max(60 / width, 1));
  2183. printk("%spcpu-alloc: s%zu r%zu d%zu u%zu alloc=%zu*%zu",
  2184. lvl, ai->static_size, ai->reserved_size, ai->dyn_size,
  2185. ai->unit_size, ai->alloc_size / ai->atom_size, ai->atom_size);
  2186. for (group = 0; group < ai->nr_groups; group++) {
  2187. const struct pcpu_group_info *gi = &ai->groups[group];
  2188. int unit = 0, unit_end = 0;
  2189. BUG_ON(gi->nr_units % upa);
  2190. for (alloc_end += gi->nr_units / upa;
  2191. alloc < alloc_end; alloc++) {
  2192. if (!(alloc % apl)) {
  2193. pr_cont("\n");
  2194. printk("%spcpu-alloc: ", lvl);
  2195. }
  2196. pr_cont("[%0*d] ", group_width, group);
  2197. for (unit_end += upa; unit < unit_end; unit++)
  2198. if (gi->cpu_map[unit] != NR_CPUS)
  2199. pr_cont("%0*d ",
  2200. cpu_width, gi->cpu_map[unit]);
  2201. else
  2202. pr_cont("%s ", empty_str);
  2203. }
  2204. }
  2205. pr_cont("\n");
  2206. }
  2207. /**
  2208. * pcpu_setup_first_chunk - initialize the first percpu chunk
  2209. * @ai: pcpu_alloc_info describing how to percpu area is shaped
  2210. * @base_addr: mapped address
  2211. *
  2212. * Initialize the first percpu chunk which contains the kernel static
  2213. * percpu area. This function is to be called from arch percpu area
  2214. * setup path.
  2215. *
  2216. * @ai contains all information necessary to initialize the first
  2217. * chunk and prime the dynamic percpu allocator.
  2218. *
  2219. * @ai->static_size is the size of static percpu area.
  2220. *
  2221. * @ai->reserved_size, if non-zero, specifies the amount of bytes to
  2222. * reserve after the static area in the first chunk. This reserves
  2223. * the first chunk such that it's available only through reserved
  2224. * percpu allocation. This is primarily used to serve module percpu
  2225. * static areas on architectures where the addressing model has
  2226. * limited offset range for symbol relocations to guarantee module
  2227. * percpu symbols fall inside the relocatable range.
  2228. *
  2229. * @ai->dyn_size determines the number of bytes available for dynamic
  2230. * allocation in the first chunk. The area between @ai->static_size +
  2231. * @ai->reserved_size + @ai->dyn_size and @ai->unit_size is unused.
  2232. *
  2233. * @ai->unit_size specifies unit size and must be aligned to PAGE_SIZE
  2234. * and equal to or larger than @ai->static_size + @ai->reserved_size +
  2235. * @ai->dyn_size.
  2236. *
  2237. * @ai->atom_size is the allocation atom size and used as alignment
  2238. * for vm areas.
  2239. *
  2240. * @ai->alloc_size is the allocation size and always multiple of
  2241. * @ai->atom_size. This is larger than @ai->atom_size if
  2242. * @ai->unit_size is larger than @ai->atom_size.
  2243. *
  2244. * @ai->nr_groups and @ai->groups describe virtual memory layout of
  2245. * percpu areas. Units which should be colocated are put into the
  2246. * same group. Dynamic VM areas will be allocated according to these
  2247. * groupings. If @ai->nr_groups is zero, a single group containing
  2248. * all units is assumed.
  2249. *
  2250. * The caller should have mapped the first chunk at @base_addr and
  2251. * copied static data to each unit.
  2252. *
  2253. * The first chunk will always contain a static and a dynamic region.
  2254. * However, the static region is not managed by any chunk. If the first
  2255. * chunk also contains a reserved region, it is served by two chunks -
  2256. * one for the reserved region and one for the dynamic region. They
  2257. * share the same vm, but use offset regions in the area allocation map.
  2258. * The chunk serving the dynamic region is circulated in the chunk slots
  2259. * and available for dynamic allocation like any other chunk.
  2260. */
  2261. void __init pcpu_setup_first_chunk(const struct pcpu_alloc_info *ai,
  2262. void *base_addr)
  2263. {
  2264. size_t size_sum = ai->static_size + ai->reserved_size + ai->dyn_size;
  2265. size_t static_size, dyn_size;
  2266. struct pcpu_chunk *chunk;
  2267. unsigned long *group_offsets;
  2268. size_t *group_sizes;
  2269. unsigned long *unit_off;
  2270. unsigned int cpu;
  2271. int *unit_map;
  2272. int group, unit, i;
  2273. int map_size;
  2274. unsigned long tmp_addr;
  2275. size_t alloc_size;
  2276. #define PCPU_SETUP_BUG_ON(cond) do { \
  2277. if (unlikely(cond)) { \
  2278. pr_emerg("failed to initialize, %s\n", #cond); \
  2279. pr_emerg("cpu_possible_mask=%*pb\n", \
  2280. cpumask_pr_args(cpu_possible_mask)); \
  2281. pcpu_dump_alloc_info(KERN_EMERG, ai); \
  2282. BUG(); \
  2283. } \
  2284. } while (0)
  2285. /* sanity checks */
  2286. PCPU_SETUP_BUG_ON(ai->nr_groups <= 0);
  2287. #ifdef CONFIG_SMP
  2288. PCPU_SETUP_BUG_ON(!ai->static_size);
  2289. PCPU_SETUP_BUG_ON(offset_in_page(__per_cpu_start));
  2290. #endif
  2291. PCPU_SETUP_BUG_ON(!base_addr);
  2292. PCPU_SETUP_BUG_ON(offset_in_page(base_addr));
  2293. PCPU_SETUP_BUG_ON(ai->unit_size < size_sum);
  2294. PCPU_SETUP_BUG_ON(offset_in_page(ai->unit_size));
  2295. PCPU_SETUP_BUG_ON(ai->unit_size < PCPU_MIN_UNIT_SIZE);
  2296. PCPU_SETUP_BUG_ON(!IS_ALIGNED(ai->unit_size, PCPU_BITMAP_BLOCK_SIZE));
  2297. PCPU_SETUP_BUG_ON(ai->dyn_size < PERCPU_DYNAMIC_EARLY_SIZE);
  2298. PCPU_SETUP_BUG_ON(!ai->dyn_size);
  2299. PCPU_SETUP_BUG_ON(!IS_ALIGNED(ai->reserved_size, PCPU_MIN_ALLOC_SIZE));
  2300. PCPU_SETUP_BUG_ON(!(IS_ALIGNED(PCPU_BITMAP_BLOCK_SIZE, PAGE_SIZE) ||
  2301. IS_ALIGNED(PAGE_SIZE, PCPU_BITMAP_BLOCK_SIZE)));
  2302. PCPU_SETUP_BUG_ON(pcpu_verify_alloc_info(ai) < 0);
  2303. /* process group information and build config tables accordingly */
  2304. alloc_size = ai->nr_groups * sizeof(group_offsets[0]);
  2305. group_offsets = memblock_alloc(alloc_size, SMP_CACHE_BYTES);
  2306. if (!group_offsets)
  2307. panic("%s: Failed to allocate %zu bytes\n", __func__,
  2308. alloc_size);
  2309. alloc_size = ai->nr_groups * sizeof(group_sizes[0]);
  2310. group_sizes = memblock_alloc(alloc_size, SMP_CACHE_BYTES);
  2311. if (!group_sizes)
  2312. panic("%s: Failed to allocate %zu bytes\n", __func__,
  2313. alloc_size);
  2314. alloc_size = nr_cpu_ids * sizeof(unit_map[0]);
  2315. unit_map = memblock_alloc(alloc_size, SMP_CACHE_BYTES);
  2316. if (!unit_map)
  2317. panic("%s: Failed to allocate %zu bytes\n", __func__,
  2318. alloc_size);
  2319. alloc_size = nr_cpu_ids * sizeof(unit_off[0]);
  2320. unit_off = memblock_alloc(alloc_size, SMP_CACHE_BYTES);
  2321. if (!unit_off)
  2322. panic("%s: Failed to allocate %zu bytes\n", __func__,
  2323. alloc_size);
  2324. for (cpu = 0; cpu < nr_cpu_ids; cpu++)
  2325. unit_map[cpu] = UINT_MAX;
  2326. pcpu_low_unit_cpu = NR_CPUS;
  2327. pcpu_high_unit_cpu = NR_CPUS;
  2328. for (group = 0, unit = 0; group < ai->nr_groups; group++, unit += i) {
  2329. const struct pcpu_group_info *gi = &ai->groups[group];
  2330. group_offsets[group] = gi->base_offset;
  2331. group_sizes[group] = gi->nr_units * ai->unit_size;
  2332. for (i = 0; i < gi->nr_units; i++) {
  2333. cpu = gi->cpu_map[i];
  2334. if (cpu == NR_CPUS)
  2335. continue;
  2336. PCPU_SETUP_BUG_ON(cpu >= nr_cpu_ids);
  2337. PCPU_SETUP_BUG_ON(!cpu_possible(cpu));
  2338. PCPU_SETUP_BUG_ON(unit_map[cpu] != UINT_MAX);
  2339. unit_map[cpu] = unit + i;
  2340. unit_off[cpu] = gi->base_offset + i * ai->unit_size;
  2341. /* determine low/high unit_cpu */
  2342. if (pcpu_low_unit_cpu == NR_CPUS ||
  2343. unit_off[cpu] < unit_off[pcpu_low_unit_cpu])
  2344. pcpu_low_unit_cpu = cpu;
  2345. if (pcpu_high_unit_cpu == NR_CPUS ||
  2346. unit_off[cpu] > unit_off[pcpu_high_unit_cpu])
  2347. pcpu_high_unit_cpu = cpu;
  2348. }
  2349. }
  2350. pcpu_nr_units = unit;
  2351. for_each_possible_cpu(cpu)
  2352. PCPU_SETUP_BUG_ON(unit_map[cpu] == UINT_MAX);
  2353. /* we're done parsing the input, undefine BUG macro and dump config */
  2354. #undef PCPU_SETUP_BUG_ON
  2355. pcpu_dump_alloc_info(KERN_DEBUG, ai);
  2356. pcpu_nr_groups = ai->nr_groups;
  2357. pcpu_group_offsets = group_offsets;
  2358. pcpu_group_sizes = group_sizes;
  2359. pcpu_unit_map = unit_map;
  2360. pcpu_unit_offsets = unit_off;
  2361. /* determine basic parameters */
  2362. pcpu_unit_pages = ai->unit_size >> PAGE_SHIFT;
  2363. pcpu_unit_size = pcpu_unit_pages << PAGE_SHIFT;
  2364. pcpu_atom_size = ai->atom_size;
  2365. pcpu_chunk_struct_size = struct_size(chunk, populated,
  2366. BITS_TO_LONGS(pcpu_unit_pages));
  2367. pcpu_stats_save_ai(ai);
  2368. /*
  2369. * Allocate chunk slots. The slots after the active slots are:
  2370. * sidelined_slot - isolated, depopulated chunks
  2371. * free_slot - fully free chunks
  2372. * to_depopulate_slot - isolated, chunks to depopulate
  2373. */
  2374. pcpu_sidelined_slot = __pcpu_size_to_slot(pcpu_unit_size) + 1;
  2375. pcpu_free_slot = pcpu_sidelined_slot + 1;
  2376. pcpu_to_depopulate_slot = pcpu_free_slot + 1;
  2377. pcpu_nr_slots = pcpu_to_depopulate_slot + 1;
  2378. pcpu_chunk_lists = memblock_alloc(pcpu_nr_slots *
  2379. sizeof(pcpu_chunk_lists[0]),
  2380. SMP_CACHE_BYTES);
  2381. if (!pcpu_chunk_lists)
  2382. panic("%s: Failed to allocate %zu bytes\n", __func__,
  2383. pcpu_nr_slots * sizeof(pcpu_chunk_lists[0]));
  2384. for (i = 0; i < pcpu_nr_slots; i++)
  2385. INIT_LIST_HEAD(&pcpu_chunk_lists[i]);
  2386. /*
  2387. * The end of the static region needs to be aligned with the
  2388. * minimum allocation size as this offsets the reserved and
  2389. * dynamic region. The first chunk ends page aligned by
  2390. * expanding the dynamic region, therefore the dynamic region
  2391. * can be shrunk to compensate while still staying above the
  2392. * configured sizes.
  2393. */
  2394. static_size = ALIGN(ai->static_size, PCPU_MIN_ALLOC_SIZE);
  2395. dyn_size = ai->dyn_size - (static_size - ai->static_size);
  2396. /*
  2397. * Initialize first chunk.
  2398. * If the reserved_size is non-zero, this initializes the reserved
  2399. * chunk. If the reserved_size is zero, the reserved chunk is NULL
  2400. * and the dynamic region is initialized here. The first chunk,
  2401. * pcpu_first_chunk, will always point to the chunk that serves
  2402. * the dynamic region.
  2403. */
  2404. tmp_addr = (unsigned long)base_addr + static_size;
  2405. map_size = ai->reserved_size ?: dyn_size;
  2406. chunk = pcpu_alloc_first_chunk(tmp_addr, map_size);
  2407. /* init dynamic chunk if necessary */
  2408. if (ai->reserved_size) {
  2409. pcpu_reserved_chunk = chunk;
  2410. tmp_addr = (unsigned long)base_addr + static_size +
  2411. ai->reserved_size;
  2412. map_size = dyn_size;
  2413. chunk = pcpu_alloc_first_chunk(tmp_addr, map_size);
  2414. }
  2415. /* link the first chunk in */
  2416. pcpu_first_chunk = chunk;
  2417. pcpu_nr_empty_pop_pages = pcpu_first_chunk->nr_empty_pop_pages;
  2418. pcpu_chunk_relocate(pcpu_first_chunk, -1);
  2419. /* include all regions of the first chunk */
  2420. pcpu_nr_populated += PFN_DOWN(size_sum);
  2421. pcpu_stats_chunk_alloc();
  2422. trace_percpu_create_chunk(base_addr);
  2423. /* we're done */
  2424. pcpu_base_addr = base_addr;
  2425. }
  2426. #ifdef CONFIG_SMP
  2427. const char * const pcpu_fc_names[PCPU_FC_NR] __initconst = {
  2428. [PCPU_FC_AUTO] = "auto",
  2429. [PCPU_FC_EMBED] = "embed",
  2430. [PCPU_FC_PAGE] = "page",
  2431. };
  2432. enum pcpu_fc pcpu_chosen_fc __initdata = PCPU_FC_AUTO;
  2433. static int __init percpu_alloc_setup(char *str)
  2434. {
  2435. if (!str)
  2436. return -EINVAL;
  2437. if (0)
  2438. /* nada */;
  2439. #ifdef CONFIG_NEED_PER_CPU_EMBED_FIRST_CHUNK
  2440. else if (!strcmp(str, "embed"))
  2441. pcpu_chosen_fc = PCPU_FC_EMBED;
  2442. #endif
  2443. #ifdef CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK
  2444. else if (!strcmp(str, "page"))
  2445. pcpu_chosen_fc = PCPU_FC_PAGE;
  2446. #endif
  2447. else
  2448. pr_warn("unknown allocator %s specified\n", str);
  2449. return 0;
  2450. }
  2451. early_param("percpu_alloc", percpu_alloc_setup);
  2452. /*
  2453. * pcpu_embed_first_chunk() is used by the generic percpu setup.
  2454. * Build it if needed by the arch config or the generic setup is going
  2455. * to be used.
  2456. */
  2457. #if defined(CONFIG_NEED_PER_CPU_EMBED_FIRST_CHUNK) || \
  2458. !defined(CONFIG_HAVE_SETUP_PER_CPU_AREA)
  2459. #define BUILD_EMBED_FIRST_CHUNK
  2460. #endif
  2461. /* build pcpu_page_first_chunk() iff needed by the arch config */
  2462. #if defined(CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK)
  2463. #define BUILD_PAGE_FIRST_CHUNK
  2464. #endif
  2465. /* pcpu_build_alloc_info() is used by both embed and page first chunk */
  2466. #if defined(BUILD_EMBED_FIRST_CHUNK) || defined(BUILD_PAGE_FIRST_CHUNK)
  2467. /**
  2468. * pcpu_build_alloc_info - build alloc_info considering distances between CPUs
  2469. * @reserved_size: the size of reserved percpu area in bytes
  2470. * @dyn_size: minimum free size for dynamic allocation in bytes
  2471. * @atom_size: allocation atom size
  2472. * @cpu_distance_fn: callback to determine distance between cpus, optional
  2473. *
  2474. * This function determines grouping of units, their mappings to cpus
  2475. * and other parameters considering needed percpu size, allocation
  2476. * atom size and distances between CPUs.
  2477. *
  2478. * Groups are always multiples of atom size and CPUs which are of
  2479. * LOCAL_DISTANCE both ways are grouped together and share space for
  2480. * units in the same group. The returned configuration is guaranteed
  2481. * to have CPUs on different nodes on different groups and >=75% usage
  2482. * of allocated virtual address space.
  2483. *
  2484. * RETURNS:
  2485. * On success, pointer to the new allocation_info is returned. On
  2486. * failure, ERR_PTR value is returned.
  2487. */
  2488. static struct pcpu_alloc_info * __init __flatten pcpu_build_alloc_info(
  2489. size_t reserved_size, size_t dyn_size,
  2490. size_t atom_size,
  2491. pcpu_fc_cpu_distance_fn_t cpu_distance_fn)
  2492. {
  2493. static int group_map[NR_CPUS] __initdata;
  2494. static int group_cnt[NR_CPUS] __initdata;
  2495. static struct cpumask mask __initdata;
  2496. const size_t static_size = __per_cpu_end - __per_cpu_start;
  2497. int nr_groups = 1, nr_units = 0;
  2498. size_t size_sum, min_unit_size, alloc_size;
  2499. int upa, max_upa, best_upa; /* units_per_alloc */
  2500. int last_allocs, group, unit;
  2501. unsigned int cpu, tcpu;
  2502. struct pcpu_alloc_info *ai;
  2503. unsigned int *cpu_map;
  2504. /* this function may be called multiple times */
  2505. memset(group_map, 0, sizeof(group_map));
  2506. memset(group_cnt, 0, sizeof(group_cnt));
  2507. cpumask_clear(&mask);
  2508. /* calculate size_sum and ensure dyn_size is enough for early alloc */
  2509. size_sum = PFN_ALIGN(static_size + reserved_size +
  2510. max_t(size_t, dyn_size, PERCPU_DYNAMIC_EARLY_SIZE));
  2511. dyn_size = size_sum - static_size - reserved_size;
  2512. /*
  2513. * Determine min_unit_size, alloc_size and max_upa such that
  2514. * alloc_size is multiple of atom_size and is the smallest
  2515. * which can accommodate 4k aligned segments which are equal to
  2516. * or larger than min_unit_size.
  2517. */
  2518. min_unit_size = max_t(size_t, size_sum, PCPU_MIN_UNIT_SIZE);
  2519. /* determine the maximum # of units that can fit in an allocation */
  2520. alloc_size = roundup(min_unit_size, atom_size);
  2521. upa = alloc_size / min_unit_size;
  2522. while (alloc_size % upa || (offset_in_page(alloc_size / upa)))
  2523. upa--;
  2524. max_upa = upa;
  2525. cpumask_copy(&mask, cpu_possible_mask);
  2526. /* group cpus according to their proximity */
  2527. for (group = 0; !cpumask_empty(&mask); group++) {
  2528. /* pop the group's first cpu */
  2529. cpu = cpumask_first(&mask);
  2530. group_map[cpu] = group;
  2531. group_cnt[group]++;
  2532. cpumask_clear_cpu(cpu, &mask);
  2533. for_each_cpu(tcpu, &mask) {
  2534. if (!cpu_distance_fn ||
  2535. (cpu_distance_fn(cpu, tcpu) == LOCAL_DISTANCE &&
  2536. cpu_distance_fn(tcpu, cpu) == LOCAL_DISTANCE)) {
  2537. group_map[tcpu] = group;
  2538. group_cnt[group]++;
  2539. cpumask_clear_cpu(tcpu, &mask);
  2540. }
  2541. }
  2542. }
  2543. nr_groups = group;
  2544. /*
  2545. * Wasted space is caused by a ratio imbalance of upa to group_cnt.
  2546. * Expand the unit_size until we use >= 75% of the units allocated.
  2547. * Related to atom_size, which could be much larger than the unit_size.
  2548. */
  2549. last_allocs = INT_MAX;
  2550. best_upa = 0;
  2551. for (upa = max_upa; upa; upa--) {
  2552. int allocs = 0, wasted = 0;
  2553. if (alloc_size % upa || (offset_in_page(alloc_size / upa)))
  2554. continue;
  2555. for (group = 0; group < nr_groups; group++) {
  2556. int this_allocs = DIV_ROUND_UP(group_cnt[group], upa);
  2557. allocs += this_allocs;
  2558. wasted += this_allocs * upa - group_cnt[group];
  2559. }
  2560. /*
  2561. * Don't accept if wastage is over 1/3. The
  2562. * greater-than comparison ensures upa==1 always
  2563. * passes the following check.
  2564. */
  2565. if (wasted > num_possible_cpus() / 3)
  2566. continue;
  2567. /* and then don't consume more memory */
  2568. if (allocs > last_allocs)
  2569. break;
  2570. last_allocs = allocs;
  2571. best_upa = upa;
  2572. }
  2573. BUG_ON(!best_upa);
  2574. upa = best_upa;
  2575. /* allocate and fill alloc_info */
  2576. for (group = 0; group < nr_groups; group++)
  2577. nr_units += roundup(group_cnt[group], upa);
  2578. ai = pcpu_alloc_alloc_info(nr_groups, nr_units);
  2579. if (!ai)
  2580. return ERR_PTR(-ENOMEM);
  2581. cpu_map = ai->groups[0].cpu_map;
  2582. for (group = 0; group < nr_groups; group++) {
  2583. ai->groups[group].cpu_map = cpu_map;
  2584. cpu_map += roundup(group_cnt[group], upa);
  2585. }
  2586. ai->static_size = static_size;
  2587. ai->reserved_size = reserved_size;
  2588. ai->dyn_size = dyn_size;
  2589. ai->unit_size = alloc_size / upa;
  2590. ai->atom_size = atom_size;
  2591. ai->alloc_size = alloc_size;
  2592. for (group = 0, unit = 0; group < nr_groups; group++) {
  2593. struct pcpu_group_info *gi = &ai->groups[group];
  2594. /*
  2595. * Initialize base_offset as if all groups are located
  2596. * back-to-back. The caller should update this to
  2597. * reflect actual allocation.
  2598. */
  2599. gi->base_offset = unit * ai->unit_size;
  2600. for_each_possible_cpu(cpu)
  2601. if (group_map[cpu] == group)
  2602. gi->cpu_map[gi->nr_units++] = cpu;
  2603. gi->nr_units = roundup(gi->nr_units, upa);
  2604. unit += gi->nr_units;
  2605. }
  2606. BUG_ON(unit != nr_units);
  2607. return ai;
  2608. }
  2609. static void * __init pcpu_fc_alloc(unsigned int cpu, size_t size, size_t align,
  2610. pcpu_fc_cpu_to_node_fn_t cpu_to_nd_fn)
  2611. {
  2612. const unsigned long goal = __pa(MAX_DMA_ADDRESS);
  2613. #ifdef CONFIG_NUMA
  2614. int node = NUMA_NO_NODE;
  2615. void *ptr;
  2616. if (cpu_to_nd_fn)
  2617. node = cpu_to_nd_fn(cpu);
  2618. if (node == NUMA_NO_NODE || !node_online(node) || !NODE_DATA(node)) {
  2619. ptr = memblock_alloc_from(size, align, goal);
  2620. pr_info("cpu %d has no node %d or node-local memory\n",
  2621. cpu, node);
  2622. pr_debug("per cpu data for cpu%d %zu bytes at 0x%llx\n",
  2623. cpu, size, (u64)__pa(ptr));
  2624. } else {
  2625. ptr = memblock_alloc_try_nid(size, align, goal,
  2626. MEMBLOCK_ALLOC_ACCESSIBLE,
  2627. node);
  2628. pr_debug("per cpu data for cpu%d %zu bytes on node%d at 0x%llx\n",
  2629. cpu, size, node, (u64)__pa(ptr));
  2630. }
  2631. return ptr;
  2632. #else
  2633. return memblock_alloc_from(size, align, goal);
  2634. #endif
  2635. }
  2636. static void __init pcpu_fc_free(void *ptr, size_t size)
  2637. {
  2638. memblock_free(ptr, size);
  2639. }
  2640. #endif /* BUILD_EMBED_FIRST_CHUNK || BUILD_PAGE_FIRST_CHUNK */
  2641. #if defined(BUILD_EMBED_FIRST_CHUNK)
  2642. /**
  2643. * pcpu_embed_first_chunk - embed the first percpu chunk into bootmem
  2644. * @reserved_size: the size of reserved percpu area in bytes
  2645. * @dyn_size: minimum free size for dynamic allocation in bytes
  2646. * @atom_size: allocation atom size
  2647. * @cpu_distance_fn: callback to determine distance between cpus, optional
  2648. * @cpu_to_nd_fn: callback to convert cpu to it's node, optional
  2649. *
  2650. * This is a helper to ease setting up embedded first percpu chunk and
  2651. * can be called where pcpu_setup_first_chunk() is expected.
  2652. *
  2653. * If this function is used to setup the first chunk, it is allocated
  2654. * by calling pcpu_fc_alloc and used as-is without being mapped into
  2655. * vmalloc area. Allocations are always whole multiples of @atom_size
  2656. * aligned to @atom_size.
  2657. *
  2658. * This enables the first chunk to piggy back on the linear physical
  2659. * mapping which often uses larger page size. Please note that this
  2660. * can result in very sparse cpu->unit mapping on NUMA machines thus
  2661. * requiring large vmalloc address space. Don't use this allocator if
  2662. * vmalloc space is not orders of magnitude larger than distances
  2663. * between node memory addresses (ie. 32bit NUMA machines).
  2664. *
  2665. * @dyn_size specifies the minimum dynamic area size.
  2666. *
  2667. * If the needed size is smaller than the minimum or specified unit
  2668. * size, the leftover is returned using pcpu_fc_free.
  2669. *
  2670. * RETURNS:
  2671. * 0 on success, -errno on failure.
  2672. */
  2673. int __init pcpu_embed_first_chunk(size_t reserved_size, size_t dyn_size,
  2674. size_t atom_size,
  2675. pcpu_fc_cpu_distance_fn_t cpu_distance_fn,
  2676. pcpu_fc_cpu_to_node_fn_t cpu_to_nd_fn)
  2677. {
  2678. void *base = (void *)ULONG_MAX;
  2679. void **areas = NULL;
  2680. struct pcpu_alloc_info *ai;
  2681. size_t size_sum, areas_size;
  2682. unsigned long max_distance;
  2683. int group, i, highest_group, rc = 0;
  2684. ai = pcpu_build_alloc_info(reserved_size, dyn_size, atom_size,
  2685. cpu_distance_fn);
  2686. if (IS_ERR(ai))
  2687. return PTR_ERR(ai);
  2688. size_sum = ai->static_size + ai->reserved_size + ai->dyn_size;
  2689. areas_size = PFN_ALIGN(ai->nr_groups * sizeof(void *));
  2690. areas = memblock_alloc(areas_size, SMP_CACHE_BYTES);
  2691. if (!areas) {
  2692. rc = -ENOMEM;
  2693. goto out_free;
  2694. }
  2695. /* allocate, copy and determine base address & max_distance */
  2696. highest_group = 0;
  2697. for (group = 0; group < ai->nr_groups; group++) {
  2698. struct pcpu_group_info *gi = &ai->groups[group];
  2699. unsigned int cpu = NR_CPUS;
  2700. void *ptr;
  2701. for (i = 0; i < gi->nr_units && cpu == NR_CPUS; i++)
  2702. cpu = gi->cpu_map[i];
  2703. BUG_ON(cpu == NR_CPUS);
  2704. /* allocate space for the whole group */
  2705. ptr = pcpu_fc_alloc(cpu, gi->nr_units * ai->unit_size, atom_size, cpu_to_nd_fn);
  2706. if (!ptr) {
  2707. rc = -ENOMEM;
  2708. goto out_free_areas;
  2709. }
  2710. /* kmemleak tracks the percpu allocations separately */
  2711. kmemleak_ignore_phys(__pa(ptr));
  2712. areas[group] = ptr;
  2713. base = min(ptr, base);
  2714. if (ptr > areas[highest_group])
  2715. highest_group = group;
  2716. }
  2717. max_distance = areas[highest_group] - base;
  2718. max_distance += ai->unit_size * ai->groups[highest_group].nr_units;
  2719. /* warn if maximum distance is further than 75% of vmalloc space */
  2720. if (max_distance > VMALLOC_TOTAL * 3 / 4) {
  2721. pr_warn("max_distance=0x%lx too large for vmalloc space 0x%lx\n",
  2722. max_distance, VMALLOC_TOTAL);
  2723. #ifdef CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK
  2724. /* and fail if we have fallback */
  2725. rc = -EINVAL;
  2726. goto out_free_areas;
  2727. #endif
  2728. }
  2729. /*
  2730. * Copy data and free unused parts. This should happen after all
  2731. * allocations are complete; otherwise, we may end up with
  2732. * overlapping groups.
  2733. */
  2734. for (group = 0; group < ai->nr_groups; group++) {
  2735. struct pcpu_group_info *gi = &ai->groups[group];
  2736. void *ptr = areas[group];
  2737. for (i = 0; i < gi->nr_units; i++, ptr += ai->unit_size) {
  2738. if (gi->cpu_map[i] == NR_CPUS) {
  2739. /* unused unit, free whole */
  2740. pcpu_fc_free(ptr, ai->unit_size);
  2741. continue;
  2742. }
  2743. /* copy and return the unused part */
  2744. memcpy(ptr, __per_cpu_load, ai->static_size);
  2745. pcpu_fc_free(ptr + size_sum, ai->unit_size - size_sum);
  2746. }
  2747. }
  2748. /* base address is now known, determine group base offsets */
  2749. for (group = 0; group < ai->nr_groups; group++) {
  2750. ai->groups[group].base_offset = areas[group] - base;
  2751. }
  2752. pr_info("Embedded %zu pages/cpu s%zu r%zu d%zu u%zu\n",
  2753. PFN_DOWN(size_sum), ai->static_size, ai->reserved_size,
  2754. ai->dyn_size, ai->unit_size);
  2755. pcpu_setup_first_chunk(ai, base);
  2756. goto out_free;
  2757. out_free_areas:
  2758. for (group = 0; group < ai->nr_groups; group++)
  2759. if (areas[group])
  2760. pcpu_fc_free(areas[group],
  2761. ai->groups[group].nr_units * ai->unit_size);
  2762. out_free:
  2763. pcpu_free_alloc_info(ai);
  2764. if (areas)
  2765. memblock_free(areas, areas_size);
  2766. return rc;
  2767. }
  2768. #endif /* BUILD_EMBED_FIRST_CHUNK */
  2769. #ifdef BUILD_PAGE_FIRST_CHUNK
  2770. #include <asm/pgalloc.h>
  2771. #ifndef P4D_TABLE_SIZE
  2772. #define P4D_TABLE_SIZE PAGE_SIZE
  2773. #endif
  2774. #ifndef PUD_TABLE_SIZE
  2775. #define PUD_TABLE_SIZE PAGE_SIZE
  2776. #endif
  2777. #ifndef PMD_TABLE_SIZE
  2778. #define PMD_TABLE_SIZE PAGE_SIZE
  2779. #endif
  2780. #ifndef PTE_TABLE_SIZE
  2781. #define PTE_TABLE_SIZE PAGE_SIZE
  2782. #endif
  2783. void __init __weak pcpu_populate_pte(unsigned long addr)
  2784. {
  2785. pgd_t *pgd = pgd_offset_k(addr);
  2786. p4d_t *p4d;
  2787. pud_t *pud;
  2788. pmd_t *pmd;
  2789. if (pgd_none(*pgd)) {
  2790. p4d_t *new;
  2791. new = memblock_alloc(P4D_TABLE_SIZE, P4D_TABLE_SIZE);
  2792. if (!new)
  2793. goto err_alloc;
  2794. pgd_populate(&init_mm, pgd, new);
  2795. }
  2796. p4d = p4d_offset(pgd, addr);
  2797. if (p4d_none(*p4d)) {
  2798. pud_t *new;
  2799. new = memblock_alloc(PUD_TABLE_SIZE, PUD_TABLE_SIZE);
  2800. if (!new)
  2801. goto err_alloc;
  2802. p4d_populate(&init_mm, p4d, new);
  2803. }
  2804. pud = pud_offset(p4d, addr);
  2805. if (pud_none(*pud)) {
  2806. pmd_t *new;
  2807. new = memblock_alloc(PMD_TABLE_SIZE, PMD_TABLE_SIZE);
  2808. if (!new)
  2809. goto err_alloc;
  2810. pud_populate(&init_mm, pud, new);
  2811. }
  2812. pmd = pmd_offset(pud, addr);
  2813. if (!pmd_present(*pmd)) {
  2814. pte_t *new;
  2815. new = memblock_alloc(PTE_TABLE_SIZE, PTE_TABLE_SIZE);
  2816. if (!new)
  2817. goto err_alloc;
  2818. pmd_populate_kernel(&init_mm, pmd, new);
  2819. }
  2820. return;
  2821. err_alloc:
  2822. panic("%s: Failed to allocate memory\n", __func__);
  2823. }
  2824. /**
  2825. * pcpu_page_first_chunk - map the first chunk using PAGE_SIZE pages
  2826. * @reserved_size: the size of reserved percpu area in bytes
  2827. * @cpu_to_nd_fn: callback to convert cpu to it's node, optional
  2828. *
  2829. * This is a helper to ease setting up page-remapped first percpu
  2830. * chunk and can be called where pcpu_setup_first_chunk() is expected.
  2831. *
  2832. * This is the basic allocator. Static percpu area is allocated
  2833. * page-by-page into vmalloc area.
  2834. *
  2835. * RETURNS:
  2836. * 0 on success, -errno on failure.
  2837. */
  2838. int __init pcpu_page_first_chunk(size_t reserved_size, pcpu_fc_cpu_to_node_fn_t cpu_to_nd_fn)
  2839. {
  2840. static struct vm_struct vm;
  2841. struct pcpu_alloc_info *ai;
  2842. char psize_str[16];
  2843. int unit_pages;
  2844. size_t pages_size;
  2845. struct page **pages;
  2846. int unit, i, j, rc = 0;
  2847. int upa;
  2848. int nr_g0_units;
  2849. snprintf(psize_str, sizeof(psize_str), "%luK", PAGE_SIZE >> 10);
  2850. ai = pcpu_build_alloc_info(reserved_size, 0, PAGE_SIZE, NULL);
  2851. if (IS_ERR(ai))
  2852. return PTR_ERR(ai);
  2853. BUG_ON(ai->nr_groups != 1);
  2854. upa = ai->alloc_size/ai->unit_size;
  2855. nr_g0_units = roundup(num_possible_cpus(), upa);
  2856. if (WARN_ON(ai->groups[0].nr_units != nr_g0_units)) {
  2857. pcpu_free_alloc_info(ai);
  2858. return -EINVAL;
  2859. }
  2860. unit_pages = ai->unit_size >> PAGE_SHIFT;
  2861. /* unaligned allocations can't be freed, round up to page size */
  2862. pages_size = PFN_ALIGN(unit_pages * num_possible_cpus() *
  2863. sizeof(pages[0]));
  2864. pages = memblock_alloc(pages_size, SMP_CACHE_BYTES);
  2865. if (!pages)
  2866. panic("%s: Failed to allocate %zu bytes\n", __func__,
  2867. pages_size);
  2868. /* allocate pages */
  2869. j = 0;
  2870. for (unit = 0; unit < num_possible_cpus(); unit++) {
  2871. unsigned int cpu = ai->groups[0].cpu_map[unit];
  2872. for (i = 0; i < unit_pages; i++) {
  2873. void *ptr;
  2874. ptr = pcpu_fc_alloc(cpu, PAGE_SIZE, PAGE_SIZE, cpu_to_nd_fn);
  2875. if (!ptr) {
  2876. pr_warn("failed to allocate %s page for cpu%u\n",
  2877. psize_str, cpu);
  2878. goto enomem;
  2879. }
  2880. /* kmemleak tracks the percpu allocations separately */
  2881. kmemleak_ignore_phys(__pa(ptr));
  2882. pages[j++] = virt_to_page(ptr);
  2883. }
  2884. }
  2885. /* allocate vm area, map the pages and copy static data */
  2886. vm.flags = VM_ALLOC;
  2887. vm.size = num_possible_cpus() * ai->unit_size;
  2888. vm_area_register_early(&vm, PAGE_SIZE);
  2889. for (unit = 0; unit < num_possible_cpus(); unit++) {
  2890. unsigned long unit_addr =
  2891. (unsigned long)vm.addr + unit * ai->unit_size;
  2892. for (i = 0; i < unit_pages; i++)
  2893. pcpu_populate_pte(unit_addr + (i << PAGE_SHIFT));
  2894. /* pte already populated, the following shouldn't fail */
  2895. rc = __pcpu_map_pages(unit_addr, &pages[unit * unit_pages],
  2896. unit_pages);
  2897. if (rc < 0)
  2898. panic("failed to map percpu area, err=%d\n", rc);
  2899. /*
  2900. * FIXME: Archs with virtual cache should flush local
  2901. * cache for the linear mapping here - something
  2902. * equivalent to flush_cache_vmap() on the local cpu.
  2903. * flush_cache_vmap() can't be used as most supporting
  2904. * data structures are not set up yet.
  2905. */
  2906. /* copy static data */
  2907. memcpy((void *)unit_addr, __per_cpu_load, ai->static_size);
  2908. }
  2909. /* we're ready, commit */
  2910. pr_info("%d %s pages/cpu s%zu r%zu d%zu\n",
  2911. unit_pages, psize_str, ai->static_size,
  2912. ai->reserved_size, ai->dyn_size);
  2913. pcpu_setup_first_chunk(ai, vm.addr);
  2914. goto out_free_ar;
  2915. enomem:
  2916. while (--j >= 0)
  2917. pcpu_fc_free(page_address(pages[j]), PAGE_SIZE);
  2918. rc = -ENOMEM;
  2919. out_free_ar:
  2920. memblock_free(pages, pages_size);
  2921. pcpu_free_alloc_info(ai);
  2922. return rc;
  2923. }
  2924. #endif /* BUILD_PAGE_FIRST_CHUNK */
  2925. #ifndef CONFIG_HAVE_SETUP_PER_CPU_AREA
  2926. /*
  2927. * Generic SMP percpu area setup.
  2928. *
  2929. * The embedding helper is used because its behavior closely resembles
  2930. * the original non-dynamic generic percpu area setup. This is
  2931. * important because many archs have addressing restrictions and might
  2932. * fail if the percpu area is located far away from the previous
  2933. * location. As an added bonus, in non-NUMA cases, embedding is
  2934. * generally a good idea TLB-wise because percpu area can piggy back
  2935. * on the physical linear memory mapping which uses large page
  2936. * mappings on applicable archs.
  2937. */
  2938. unsigned long __per_cpu_offset[NR_CPUS] __read_mostly;
  2939. EXPORT_SYMBOL(__per_cpu_offset);
  2940. void __init setup_per_cpu_areas(void)
  2941. {
  2942. unsigned long delta;
  2943. unsigned int cpu;
  2944. int rc;
  2945. /*
  2946. * Always reserve area for module percpu variables. That's
  2947. * what the legacy allocator did.
  2948. */
  2949. rc = pcpu_embed_first_chunk(PERCPU_MODULE_RESERVE, PERCPU_DYNAMIC_RESERVE,
  2950. PAGE_SIZE, NULL, NULL);
  2951. if (rc < 0)
  2952. panic("Failed to initialize percpu areas.");
  2953. delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
  2954. for_each_possible_cpu(cpu)
  2955. __per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
  2956. }
  2957. #endif /* CONFIG_HAVE_SETUP_PER_CPU_AREA */
  2958. #else /* CONFIG_SMP */
  2959. /*
  2960. * UP percpu area setup.
  2961. *
  2962. * UP always uses km-based percpu allocator with identity mapping.
  2963. * Static percpu variables are indistinguishable from the usual static
  2964. * variables and don't require any special preparation.
  2965. */
  2966. void __init setup_per_cpu_areas(void)
  2967. {
  2968. const size_t unit_size =
  2969. roundup_pow_of_two(max_t(size_t, PCPU_MIN_UNIT_SIZE,
  2970. PERCPU_DYNAMIC_RESERVE));
  2971. struct pcpu_alloc_info *ai;
  2972. void *fc;
  2973. ai = pcpu_alloc_alloc_info(1, 1);
  2974. fc = memblock_alloc_from(unit_size, PAGE_SIZE, __pa(MAX_DMA_ADDRESS));
  2975. if (!ai || !fc)
  2976. panic("Failed to allocate memory for percpu areas.");
  2977. /* kmemleak tracks the percpu allocations separately */
  2978. kmemleak_ignore_phys(__pa(fc));
  2979. ai->dyn_size = unit_size;
  2980. ai->unit_size = unit_size;
  2981. ai->atom_size = unit_size;
  2982. ai->alloc_size = unit_size;
  2983. ai->groups[0].nr_units = 1;
  2984. ai->groups[0].cpu_map[0] = 0;
  2985. pcpu_setup_first_chunk(ai, fc);
  2986. pcpu_free_alloc_info(ai);
  2987. }
  2988. #endif /* CONFIG_SMP */
  2989. /*
  2990. * pcpu_nr_pages - calculate total number of populated backing pages
  2991. *
  2992. * This reflects the number of pages populated to back chunks. Metadata is
  2993. * excluded in the number exposed in meminfo as the number of backing pages
  2994. * scales with the number of cpus and can quickly outweigh the memory used for
  2995. * metadata. It also keeps this calculation nice and simple.
  2996. *
  2997. * RETURNS:
  2998. * Total number of populated backing pages in use by the allocator.
  2999. */
  3000. unsigned long pcpu_nr_pages(void)
  3001. {
  3002. return pcpu_nr_populated * pcpu_nr_units;
  3003. }
  3004. EXPORT_SYMBOL_GPL(pcpu_nr_pages);
  3005. /*
  3006. * Percpu allocator is initialized early during boot when neither slab or
  3007. * workqueue is available. Plug async management until everything is up
  3008. * and running.
  3009. */
  3010. static int __init percpu_enable_async(void)
  3011. {
  3012. pcpu_async_enabled = true;
  3013. return 0;
  3014. }
  3015. subsys_initcall(percpu_enable_async);