percpu.c 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755
  1. /*
  2. * mm/percpu.c - percpu memory allocator
  3. *
  4. * Copyright (C) 2009 SUSE Linux Products GmbH
  5. * Copyright (C) 2009 Tejun Heo <tj@kernel.org>
  6. *
  7. * Copyright (C) 2017 Facebook Inc.
  8. * Copyright (C) 2017 Dennis Zhou <dennisszhou@gmail.com>
  9. *
  10. * This file is released under the GPLv2 license.
  11. *
  12. * The percpu allocator handles both static and dynamic areas. Percpu
  13. * areas are allocated in chunks which are divided into units. There is
  14. * a 1-to-1 mapping for units to possible cpus. These units are grouped
  15. * based on NUMA properties of the machine.
  16. *
  17. * c0 c1 c2
  18. * ------------------- ------------------- ------------
  19. * | u0 | u1 | u2 | u3 | | u0 | u1 | u2 | u3 | | u0 | u1 | u
  20. * ------------------- ...... ------------------- .... ------------
  21. *
  22. * Allocation is done by offsets into a unit's address space. Ie., an
  23. * area of 512 bytes at 6k in c1 occupies 512 bytes at 6k in c1:u0,
  24. * c1:u1, c1:u2, etc. On NUMA machines, the mapping may be non-linear
  25. * and even sparse. Access is handled by configuring percpu base
  26. * registers according to the cpu to unit mappings and offsetting the
  27. * base address using pcpu_unit_size.
  28. *
  29. * There is special consideration for the first chunk which must handle
  30. * the static percpu variables in the kernel image as allocation services
  31. * are not online yet. In short, the first chunk is structured like so:
  32. *
  33. * <Static | [Reserved] | Dynamic>
  34. *
  35. * The static data is copied from the original section managed by the
  36. * linker. The reserved section, if non-zero, primarily manages static
  37. * percpu variables from kernel modules. Finally, the dynamic section
  38. * takes care of normal allocations.
  39. *
  40. * The allocator organizes chunks into lists according to free size and
  41. * tries to allocate from the fullest chunk first. Each chunk is managed
  42. * by a bitmap with metadata blocks. The allocation map is updated on
  43. * every allocation and free to reflect the current state while the boundary
  44. * map is only updated on allocation. Each metadata block contains
  45. * information to help mitigate the need to iterate over large portions
  46. * of the bitmap. The reverse mapping from page to chunk is stored in
  47. * the page's index. Lastly, units are lazily backed and grow in unison.
  48. *
  49. * There is a unique conversion that goes on here between bytes and bits.
  50. * Each bit represents a fragment of size PCPU_MIN_ALLOC_SIZE. The chunk
  51. * tracks the number of pages it is responsible for in nr_pages. Helper
  52. * functions are used to convert from between the bytes, bits, and blocks.
  53. * All hints are managed in bits unless explicitly stated.
  54. *
  55. * To use this allocator, arch code should do the following:
  56. *
  57. * - define __addr_to_pcpu_ptr() and __pcpu_ptr_to_addr() to translate
  58. * regular address to percpu pointer and back if they need to be
  59. * different from the default
  60. *
  61. * - use pcpu_setup_first_chunk() during percpu area initialization to
  62. * setup the first chunk containing the kernel static percpu area
  63. */
  64. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  65. #include <linux/bitmap.h>
  66. #include <linux/bootmem.h>
  67. #include <linux/err.h>
  68. #include <linux/lcm.h>
  69. #include <linux/list.h>
  70. #include <linux/log2.h>
  71. #include <linux/mm.h>
  72. #include <linux/module.h>
  73. #include <linux/mutex.h>
  74. #include <linux/percpu.h>
  75. #include <linux/pfn.h>
  76. #include <linux/slab.h>
  77. #include <linux/spinlock.h>
  78. #include <linux/vmalloc.h>
  79. #include <linux/workqueue.h>
  80. #include <linux/kmemleak.h>
  81. #include <linux/sched.h>
  82. #include <asm/cacheflush.h>
  83. #include <asm/sections.h>
  84. #include <asm/tlbflush.h>
  85. #include <asm/io.h>
  86. #define CREATE_TRACE_POINTS
  87. #include <trace/events/percpu.h>
  88. #include "percpu-internal.h"
  89. /* the slots are sorted by free bytes left, 1-31 bytes share the same slot */
  90. #define PCPU_SLOT_BASE_SHIFT 5
  91. #define PCPU_EMPTY_POP_PAGES_LOW 2
  92. #define PCPU_EMPTY_POP_PAGES_HIGH 4
  93. #ifdef CONFIG_SMP
  94. /* default addr <-> pcpu_ptr mapping, override in asm/percpu.h if necessary */
  95. #ifndef __addr_to_pcpu_ptr
  96. #define __addr_to_pcpu_ptr(addr) \
  97. (void __percpu *)((unsigned long)(addr) - \
  98. (unsigned long)pcpu_base_addr + \
  99. (unsigned long)__per_cpu_start)
  100. #endif
  101. #ifndef __pcpu_ptr_to_addr
  102. #define __pcpu_ptr_to_addr(ptr) \
  103. (void __force *)((unsigned long)(ptr) + \
  104. (unsigned long)pcpu_base_addr - \
  105. (unsigned long)__per_cpu_start)
  106. #endif
  107. #else /* CONFIG_SMP */
  108. /* on UP, it's always identity mapped */
  109. #define __addr_to_pcpu_ptr(addr) (void __percpu *)(addr)
  110. #define __pcpu_ptr_to_addr(ptr) (void __force *)(ptr)
  111. #endif /* CONFIG_SMP */
  112. static int pcpu_unit_pages __ro_after_init;
  113. static int pcpu_unit_size __ro_after_init;
  114. static int pcpu_nr_units __ro_after_init;
  115. static int pcpu_atom_size __ro_after_init;
  116. int pcpu_nr_slots __ro_after_init;
  117. static size_t pcpu_chunk_struct_size __ro_after_init;
  118. /* cpus with the lowest and highest unit addresses */
  119. static unsigned int pcpu_low_unit_cpu __ro_after_init;
  120. static unsigned int pcpu_high_unit_cpu __ro_after_init;
  121. /* the address of the first chunk which starts with the kernel static area */
  122. void *pcpu_base_addr __ro_after_init;
  123. EXPORT_SYMBOL_GPL(pcpu_base_addr);
  124. static const int *pcpu_unit_map __ro_after_init; /* cpu -> unit */
  125. const unsigned long *pcpu_unit_offsets __ro_after_init; /* cpu -> unit offset */
  126. /* group information, used for vm allocation */
  127. static int pcpu_nr_groups __ro_after_init;
  128. static const unsigned long *pcpu_group_offsets __ro_after_init;
  129. static const size_t *pcpu_group_sizes __ro_after_init;
  130. /*
  131. * The first chunk which always exists. Note that unlike other
  132. * chunks, this one can be allocated and mapped in several different
  133. * ways and thus often doesn't live in the vmalloc area.
  134. */
  135. struct pcpu_chunk *pcpu_first_chunk __ro_after_init;
  136. /*
  137. * Optional reserved chunk. This chunk reserves part of the first
  138. * chunk and serves it for reserved allocations. When the reserved
  139. * region doesn't exist, the following variable is NULL.
  140. */
  141. struct pcpu_chunk *pcpu_reserved_chunk __ro_after_init;
  142. DEFINE_SPINLOCK(pcpu_lock); /* all internal data structures */
  143. static DEFINE_MUTEX(pcpu_alloc_mutex); /* chunk create/destroy, [de]pop, map ext */
  144. struct list_head *pcpu_slot __ro_after_init; /* chunk list slots */
  145. /* chunks which need their map areas extended, protected by pcpu_lock */
  146. static LIST_HEAD(pcpu_map_extend_chunks);
  147. /*
  148. * The number of empty populated pages, protected by pcpu_lock. The
  149. * reserved chunk doesn't contribute to the count.
  150. */
  151. int pcpu_nr_empty_pop_pages;
  152. /*
  153. * Balance work is used to populate or destroy chunks asynchronously. We
  154. * try to keep the number of populated free pages between
  155. * PCPU_EMPTY_POP_PAGES_LOW and HIGH for atomic allocations and at most one
  156. * empty chunk.
  157. */
  158. static void pcpu_balance_workfn(struct work_struct *work);
  159. static DECLARE_WORK(pcpu_balance_work, pcpu_balance_workfn);
  160. static bool pcpu_async_enabled __read_mostly;
  161. static bool pcpu_atomic_alloc_failed;
  162. static void pcpu_schedule_balance_work(void)
  163. {
  164. if (pcpu_async_enabled)
  165. schedule_work(&pcpu_balance_work);
  166. }
  167. /**
  168. * pcpu_addr_in_chunk - check if the address is served from this chunk
  169. * @chunk: chunk of interest
  170. * @addr: percpu address
  171. *
  172. * RETURNS:
  173. * True if the address is served from this chunk.
  174. */
  175. static bool pcpu_addr_in_chunk(struct pcpu_chunk *chunk, void *addr)
  176. {
  177. void *start_addr, *end_addr;
  178. if (!chunk)
  179. return false;
  180. start_addr = chunk->base_addr + chunk->start_offset;
  181. end_addr = chunk->base_addr + chunk->nr_pages * PAGE_SIZE -
  182. chunk->end_offset;
  183. return addr >= start_addr && addr < end_addr;
  184. }
  185. static int __pcpu_size_to_slot(int size)
  186. {
  187. int highbit = fls(size); /* size is in bytes */
  188. return max(highbit - PCPU_SLOT_BASE_SHIFT + 2, 1);
  189. }
  190. static int pcpu_size_to_slot(int size)
  191. {
  192. if (size == pcpu_unit_size)
  193. return pcpu_nr_slots - 1;
  194. return __pcpu_size_to_slot(size);
  195. }
  196. static int pcpu_chunk_slot(const struct pcpu_chunk *chunk)
  197. {
  198. if (chunk->free_bytes < PCPU_MIN_ALLOC_SIZE || chunk->contig_bits == 0)
  199. return 0;
  200. return pcpu_size_to_slot(chunk->free_bytes);
  201. }
  202. /* set the pointer to a chunk in a page struct */
  203. static void pcpu_set_page_chunk(struct page *page, struct pcpu_chunk *pcpu)
  204. {
  205. page->index = (unsigned long)pcpu;
  206. }
  207. /* obtain pointer to a chunk from a page struct */
  208. static struct pcpu_chunk *pcpu_get_page_chunk(struct page *page)
  209. {
  210. return (struct pcpu_chunk *)page->index;
  211. }
  212. static int __maybe_unused pcpu_page_idx(unsigned int cpu, int page_idx)
  213. {
  214. return pcpu_unit_map[cpu] * pcpu_unit_pages + page_idx;
  215. }
  216. static unsigned long pcpu_unit_page_offset(unsigned int cpu, int page_idx)
  217. {
  218. return pcpu_unit_offsets[cpu] + (page_idx << PAGE_SHIFT);
  219. }
  220. static unsigned long pcpu_chunk_addr(struct pcpu_chunk *chunk,
  221. unsigned int cpu, int page_idx)
  222. {
  223. return (unsigned long)chunk->base_addr +
  224. pcpu_unit_page_offset(cpu, page_idx);
  225. }
  226. static void pcpu_next_unpop(unsigned long *bitmap, int *rs, int *re, int end)
  227. {
  228. *rs = find_next_zero_bit(bitmap, end, *rs);
  229. *re = find_next_bit(bitmap, end, *rs + 1);
  230. }
  231. static void pcpu_next_pop(unsigned long *bitmap, int *rs, int *re, int end)
  232. {
  233. *rs = find_next_bit(bitmap, end, *rs);
  234. *re = find_next_zero_bit(bitmap, end, *rs + 1);
  235. }
  236. /*
  237. * Bitmap region iterators. Iterates over the bitmap between
  238. * [@start, @end) in @chunk. @rs and @re should be integer variables
  239. * and will be set to start and end index of the current free region.
  240. */
  241. #define pcpu_for_each_unpop_region(bitmap, rs, re, start, end) \
  242. for ((rs) = (start), pcpu_next_unpop((bitmap), &(rs), &(re), (end)); \
  243. (rs) < (re); \
  244. (rs) = (re) + 1, pcpu_next_unpop((bitmap), &(rs), &(re), (end)))
  245. #define pcpu_for_each_pop_region(bitmap, rs, re, start, end) \
  246. for ((rs) = (start), pcpu_next_pop((bitmap), &(rs), &(re), (end)); \
  247. (rs) < (re); \
  248. (rs) = (re) + 1, pcpu_next_pop((bitmap), &(rs), &(re), (end)))
  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_next_md_free_region - finds the next hint free area
  272. * @chunk: chunk of interest
  273. * @bit_off: chunk offset
  274. * @bits: size of free area
  275. *
  276. * Helper function for pcpu_for_each_md_free_region. It checks
  277. * block->contig_hint and performs aggregation across blocks to find the
  278. * next hint. It modifies bit_off and bits in-place to be consumed in the
  279. * loop.
  280. */
  281. static void pcpu_next_md_free_region(struct pcpu_chunk *chunk, int *bit_off,
  282. int *bits)
  283. {
  284. int i = pcpu_off_to_block_index(*bit_off);
  285. int block_off = pcpu_off_to_block_off(*bit_off);
  286. struct pcpu_block_md *block;
  287. *bits = 0;
  288. for (block = chunk->md_blocks + i; i < pcpu_chunk_nr_blocks(chunk);
  289. block++, i++) {
  290. /* handles contig area across blocks */
  291. if (*bits) {
  292. *bits += block->left_free;
  293. if (block->left_free == PCPU_BITMAP_BLOCK_BITS)
  294. continue;
  295. return;
  296. }
  297. /*
  298. * This checks three things. First is there a contig_hint to
  299. * check. Second, have we checked this hint before by
  300. * comparing the block_off. Third, is this the same as the
  301. * right contig hint. In the last case, it spills over into
  302. * the next block and should be handled by the contig area
  303. * across blocks code.
  304. */
  305. *bits = block->contig_hint;
  306. if (*bits && block->contig_hint_start >= block_off &&
  307. *bits + block->contig_hint_start < PCPU_BITMAP_BLOCK_BITS) {
  308. *bit_off = pcpu_block_off_to_off(i,
  309. block->contig_hint_start);
  310. return;
  311. }
  312. /* reset to satisfy the second predicate above */
  313. block_off = 0;
  314. *bits = block->right_free;
  315. *bit_off = (i + 1) * PCPU_BITMAP_BLOCK_BITS - block->right_free;
  316. }
  317. }
  318. /**
  319. * pcpu_next_fit_region - finds fit areas for a given allocation request
  320. * @chunk: chunk of interest
  321. * @alloc_bits: size of allocation
  322. * @align: alignment of area (max PAGE_SIZE)
  323. * @bit_off: chunk offset
  324. * @bits: size of free area
  325. *
  326. * Finds the next free region that is viable for use with a given size and
  327. * alignment. This only returns if there is a valid area to be used for this
  328. * allocation. block->first_free is returned if the allocation request fits
  329. * within the block to see if the request can be fulfilled prior to the contig
  330. * hint.
  331. */
  332. static void pcpu_next_fit_region(struct pcpu_chunk *chunk, int alloc_bits,
  333. int align, int *bit_off, int *bits)
  334. {
  335. int i = pcpu_off_to_block_index(*bit_off);
  336. int block_off = pcpu_off_to_block_off(*bit_off);
  337. struct pcpu_block_md *block;
  338. *bits = 0;
  339. for (block = chunk->md_blocks + i; i < pcpu_chunk_nr_blocks(chunk);
  340. block++, i++) {
  341. /* handles contig area across blocks */
  342. if (*bits) {
  343. *bits += block->left_free;
  344. if (*bits >= alloc_bits)
  345. return;
  346. if (block->left_free == PCPU_BITMAP_BLOCK_BITS)
  347. continue;
  348. }
  349. /* check block->contig_hint */
  350. *bits = ALIGN(block->contig_hint_start, align) -
  351. block->contig_hint_start;
  352. /*
  353. * This uses the block offset to determine if this has been
  354. * checked in the prior iteration.
  355. */
  356. if (block->contig_hint &&
  357. block->contig_hint_start >= block_off &&
  358. block->contig_hint >= *bits + alloc_bits) {
  359. *bits += alloc_bits + block->contig_hint_start -
  360. block->first_free;
  361. *bit_off = pcpu_block_off_to_off(i, block->first_free);
  362. return;
  363. }
  364. /* reset to satisfy the second predicate above */
  365. block_off = 0;
  366. *bit_off = ALIGN(PCPU_BITMAP_BLOCK_BITS - block->right_free,
  367. align);
  368. *bits = PCPU_BITMAP_BLOCK_BITS - *bit_off;
  369. *bit_off = pcpu_block_off_to_off(i, *bit_off);
  370. if (*bits >= alloc_bits)
  371. return;
  372. }
  373. /* no valid offsets were found - fail condition */
  374. *bit_off = pcpu_chunk_map_bits(chunk);
  375. }
  376. /*
  377. * Metadata free area iterators. These perform aggregation of free areas
  378. * based on the metadata blocks and return the offset @bit_off and size in
  379. * bits of the free area @bits. pcpu_for_each_fit_region only returns when
  380. * a fit is found for the allocation request.
  381. */
  382. #define pcpu_for_each_md_free_region(chunk, bit_off, bits) \
  383. for (pcpu_next_md_free_region((chunk), &(bit_off), &(bits)); \
  384. (bit_off) < pcpu_chunk_map_bits((chunk)); \
  385. (bit_off) += (bits) + 1, \
  386. pcpu_next_md_free_region((chunk), &(bit_off), &(bits)))
  387. #define pcpu_for_each_fit_region(chunk, alloc_bits, align, bit_off, bits) \
  388. for (pcpu_next_fit_region((chunk), (alloc_bits), (align), &(bit_off), \
  389. &(bits)); \
  390. (bit_off) < pcpu_chunk_map_bits((chunk)); \
  391. (bit_off) += (bits), \
  392. pcpu_next_fit_region((chunk), (alloc_bits), (align), &(bit_off), \
  393. &(bits)))
  394. /**
  395. * pcpu_mem_zalloc - allocate memory
  396. * @size: bytes to allocate
  397. * @gfp: allocation flags
  398. *
  399. * Allocate @size bytes. If @size is smaller than PAGE_SIZE,
  400. * kzalloc() is used; otherwise, the equivalent of vzalloc() is used.
  401. * This is to facilitate passing through whitelisted flags. The
  402. * returned memory is always zeroed.
  403. *
  404. * CONTEXT:
  405. * Does GFP_KERNEL allocation.
  406. *
  407. * RETURNS:
  408. * Pointer to the allocated area on success, NULL on failure.
  409. */
  410. static void *pcpu_mem_zalloc(size_t size, gfp_t gfp)
  411. {
  412. if (WARN_ON_ONCE(!slab_is_available()))
  413. return NULL;
  414. if (size <= PAGE_SIZE)
  415. return kzalloc(size, gfp | GFP_KERNEL);
  416. else
  417. return __vmalloc(size, gfp | GFP_KERNEL | __GFP_ZERO,
  418. PAGE_KERNEL);
  419. }
  420. /**
  421. * pcpu_mem_free - free memory
  422. * @ptr: memory to free
  423. *
  424. * Free @ptr. @ptr should have been allocated using pcpu_mem_zalloc().
  425. */
  426. static void pcpu_mem_free(void *ptr)
  427. {
  428. kvfree(ptr);
  429. }
  430. /**
  431. * pcpu_chunk_relocate - put chunk in the appropriate chunk slot
  432. * @chunk: chunk of interest
  433. * @oslot: the previous slot it was on
  434. *
  435. * This function is called after an allocation or free changed @chunk.
  436. * New slot according to the changed state is determined and @chunk is
  437. * moved to the slot. Note that the reserved chunk is never put on
  438. * chunk slots.
  439. *
  440. * CONTEXT:
  441. * pcpu_lock.
  442. */
  443. static void pcpu_chunk_relocate(struct pcpu_chunk *chunk, int oslot)
  444. {
  445. int nslot = pcpu_chunk_slot(chunk);
  446. if (chunk != pcpu_reserved_chunk && oslot != nslot) {
  447. if (oslot < nslot)
  448. list_move(&chunk->list, &pcpu_slot[nslot]);
  449. else
  450. list_move_tail(&chunk->list, &pcpu_slot[nslot]);
  451. }
  452. }
  453. /**
  454. * pcpu_cnt_pop_pages- counts populated backing pages in range
  455. * @chunk: chunk of interest
  456. * @bit_off: start offset
  457. * @bits: size of area to check
  458. *
  459. * Calculates the number of populated pages in the region
  460. * [page_start, page_end). This keeps track of how many empty populated
  461. * pages are available and decide if async work should be scheduled.
  462. *
  463. * RETURNS:
  464. * The nr of populated pages.
  465. */
  466. static inline int pcpu_cnt_pop_pages(struct pcpu_chunk *chunk, int bit_off,
  467. int bits)
  468. {
  469. int page_start = PFN_UP(bit_off * PCPU_MIN_ALLOC_SIZE);
  470. int page_end = PFN_DOWN((bit_off + bits) * PCPU_MIN_ALLOC_SIZE);
  471. if (page_start >= page_end)
  472. return 0;
  473. /*
  474. * bitmap_weight counts the number of bits set in a bitmap up to
  475. * the specified number of bits. This is counting the populated
  476. * pages up to page_end and then subtracting the populated pages
  477. * up to page_start to count the populated pages in
  478. * [page_start, page_end).
  479. */
  480. return bitmap_weight(chunk->populated, page_end) -
  481. bitmap_weight(chunk->populated, page_start);
  482. }
  483. /**
  484. * pcpu_chunk_update - updates the chunk metadata given a free area
  485. * @chunk: chunk of interest
  486. * @bit_off: chunk offset
  487. * @bits: size of free area
  488. *
  489. * This updates the chunk's contig hint and starting offset given a free area.
  490. * Choose the best starting offset if the contig hint is equal.
  491. */
  492. static void pcpu_chunk_update(struct pcpu_chunk *chunk, int bit_off, int bits)
  493. {
  494. if (bits > chunk->contig_bits) {
  495. chunk->contig_bits_start = bit_off;
  496. chunk->contig_bits = bits;
  497. } else if (bits == chunk->contig_bits && chunk->contig_bits_start &&
  498. (!bit_off ||
  499. __ffs(bit_off) > __ffs(chunk->contig_bits_start))) {
  500. /* use the start with the best alignment */
  501. chunk->contig_bits_start = bit_off;
  502. }
  503. }
  504. /**
  505. * pcpu_chunk_refresh_hint - updates metadata about a chunk
  506. * @chunk: chunk of interest
  507. *
  508. * Iterates over the metadata blocks to find the largest contig area.
  509. * It also counts the populated pages and uses the delta to update the
  510. * global count.
  511. *
  512. * Updates:
  513. * chunk->contig_bits
  514. * chunk->contig_bits_start
  515. * nr_empty_pop_pages (chunk and global)
  516. */
  517. static void pcpu_chunk_refresh_hint(struct pcpu_chunk *chunk)
  518. {
  519. int bit_off, bits, nr_empty_pop_pages;
  520. /* clear metadata */
  521. chunk->contig_bits = 0;
  522. bit_off = chunk->first_bit;
  523. bits = nr_empty_pop_pages = 0;
  524. pcpu_for_each_md_free_region(chunk, bit_off, bits) {
  525. pcpu_chunk_update(chunk, bit_off, bits);
  526. nr_empty_pop_pages += pcpu_cnt_pop_pages(chunk, bit_off, bits);
  527. }
  528. /*
  529. * Keep track of nr_empty_pop_pages.
  530. *
  531. * The chunk maintains the previous number of free pages it held,
  532. * so the delta is used to update the global counter. The reserved
  533. * chunk is not part of the free page count as they are populated
  534. * at init and are special to serving reserved allocations.
  535. */
  536. if (chunk != pcpu_reserved_chunk)
  537. pcpu_nr_empty_pop_pages +=
  538. (nr_empty_pop_pages - chunk->nr_empty_pop_pages);
  539. chunk->nr_empty_pop_pages = nr_empty_pop_pages;
  540. }
  541. /**
  542. * pcpu_block_update - updates a block given a free area
  543. * @block: block of interest
  544. * @start: start offset in block
  545. * @end: end offset in block
  546. *
  547. * Updates a block given a known free area. The region [start, end) is
  548. * expected to be the entirety of the free area within a block. Chooses
  549. * the best starting offset if the contig hints are equal.
  550. */
  551. static void pcpu_block_update(struct pcpu_block_md *block, int start, int end)
  552. {
  553. int contig = end - start;
  554. block->first_free = min(block->first_free, start);
  555. if (start == 0)
  556. block->left_free = contig;
  557. if (end == PCPU_BITMAP_BLOCK_BITS)
  558. block->right_free = contig;
  559. if (contig > block->contig_hint) {
  560. block->contig_hint_start = start;
  561. block->contig_hint = contig;
  562. } else if (block->contig_hint_start && contig == block->contig_hint &&
  563. (!start || __ffs(start) > __ffs(block->contig_hint_start))) {
  564. /* use the start with the best alignment */
  565. block->contig_hint_start = start;
  566. }
  567. }
  568. /**
  569. * pcpu_block_refresh_hint
  570. * @chunk: chunk of interest
  571. * @index: index of the metadata block
  572. *
  573. * Scans over the block beginning at first_free and updates the block
  574. * metadata accordingly.
  575. */
  576. static void pcpu_block_refresh_hint(struct pcpu_chunk *chunk, int index)
  577. {
  578. struct pcpu_block_md *block = chunk->md_blocks + index;
  579. unsigned long *alloc_map = pcpu_index_alloc_map(chunk, index);
  580. int rs, re; /* region start, region end */
  581. /* clear hints */
  582. block->contig_hint = 0;
  583. block->left_free = block->right_free = 0;
  584. /* iterate over free areas and update the contig hints */
  585. pcpu_for_each_unpop_region(alloc_map, rs, re, block->first_free,
  586. PCPU_BITMAP_BLOCK_BITS) {
  587. pcpu_block_update(block, rs, re);
  588. }
  589. }
  590. /**
  591. * pcpu_block_update_hint_alloc - update hint on allocation path
  592. * @chunk: chunk of interest
  593. * @bit_off: chunk offset
  594. * @bits: size of request
  595. *
  596. * Updates metadata for the allocation path. The metadata only has to be
  597. * refreshed by a full scan iff the chunk's contig hint is broken. Block level
  598. * scans are required if the block's contig hint is broken.
  599. */
  600. static void pcpu_block_update_hint_alloc(struct pcpu_chunk *chunk, int bit_off,
  601. int bits)
  602. {
  603. struct pcpu_block_md *s_block, *e_block, *block;
  604. int s_index, e_index; /* block indexes of the freed allocation */
  605. int s_off, e_off; /* block offsets of the freed allocation */
  606. /*
  607. * Calculate per block offsets.
  608. * The calculation uses an inclusive range, but the resulting offsets
  609. * are [start, end). e_index always points to the last block in the
  610. * range.
  611. */
  612. s_index = pcpu_off_to_block_index(bit_off);
  613. e_index = pcpu_off_to_block_index(bit_off + bits - 1);
  614. s_off = pcpu_off_to_block_off(bit_off);
  615. e_off = pcpu_off_to_block_off(bit_off + bits - 1) + 1;
  616. s_block = chunk->md_blocks + s_index;
  617. e_block = chunk->md_blocks + e_index;
  618. /*
  619. * Update s_block.
  620. * block->first_free must be updated if the allocation takes its place.
  621. * If the allocation breaks the contig_hint, a scan is required to
  622. * restore this hint.
  623. */
  624. if (s_off == s_block->first_free)
  625. s_block->first_free = find_next_zero_bit(
  626. pcpu_index_alloc_map(chunk, s_index),
  627. PCPU_BITMAP_BLOCK_BITS,
  628. s_off + bits);
  629. if (s_off >= s_block->contig_hint_start &&
  630. s_off < s_block->contig_hint_start + s_block->contig_hint) {
  631. /* block contig hint is broken - scan to fix it */
  632. pcpu_block_refresh_hint(chunk, s_index);
  633. } else {
  634. /* update left and right contig manually */
  635. s_block->left_free = min(s_block->left_free, s_off);
  636. if (s_index == e_index)
  637. s_block->right_free = min_t(int, s_block->right_free,
  638. PCPU_BITMAP_BLOCK_BITS - e_off);
  639. else
  640. s_block->right_free = 0;
  641. }
  642. /*
  643. * Update e_block.
  644. */
  645. if (s_index != e_index) {
  646. /*
  647. * When the allocation is across blocks, the end is along
  648. * the left part of the e_block.
  649. */
  650. e_block->first_free = find_next_zero_bit(
  651. pcpu_index_alloc_map(chunk, e_index),
  652. PCPU_BITMAP_BLOCK_BITS, e_off);
  653. if (e_off == PCPU_BITMAP_BLOCK_BITS) {
  654. /* reset the block */
  655. e_block++;
  656. } else {
  657. if (e_off > e_block->contig_hint_start) {
  658. /* contig hint is broken - scan to fix it */
  659. pcpu_block_refresh_hint(chunk, e_index);
  660. } else {
  661. e_block->left_free = 0;
  662. e_block->right_free =
  663. min_t(int, e_block->right_free,
  664. PCPU_BITMAP_BLOCK_BITS - e_off);
  665. }
  666. }
  667. /* update in-between md_blocks */
  668. for (block = s_block + 1; block < e_block; block++) {
  669. block->contig_hint = 0;
  670. block->left_free = 0;
  671. block->right_free = 0;
  672. }
  673. }
  674. /*
  675. * The only time a full chunk scan is required is if the chunk
  676. * contig hint is broken. Otherwise, it means a smaller space
  677. * was used and therefore the chunk contig hint is still correct.
  678. */
  679. if (bit_off >= chunk->contig_bits_start &&
  680. bit_off < chunk->contig_bits_start + chunk->contig_bits)
  681. pcpu_chunk_refresh_hint(chunk);
  682. }
  683. /**
  684. * pcpu_block_update_hint_free - updates the block hints on the free path
  685. * @chunk: chunk of interest
  686. * @bit_off: chunk offset
  687. * @bits: size of request
  688. *
  689. * Updates metadata for the allocation path. This avoids a blind block
  690. * refresh by making use of the block contig hints. If this fails, it scans
  691. * forward and backward to determine the extent of the free area. This is
  692. * capped at the boundary of blocks.
  693. *
  694. * A chunk update is triggered if a page becomes free, a block becomes free,
  695. * or the free spans across blocks. This tradeoff is to minimize iterating
  696. * over the block metadata to update chunk->contig_bits. chunk->contig_bits
  697. * may be off by up to a page, but it will never be more than the available
  698. * space. If the contig hint is contained in one block, it will be accurate.
  699. */
  700. static void pcpu_block_update_hint_free(struct pcpu_chunk *chunk, int bit_off,
  701. int bits)
  702. {
  703. struct pcpu_block_md *s_block, *e_block, *block;
  704. int s_index, e_index; /* block indexes of the freed allocation */
  705. int s_off, e_off; /* block offsets of the freed allocation */
  706. int start, end; /* start and end of the whole free area */
  707. /*
  708. * Calculate per block offsets.
  709. * The calculation uses an inclusive range, but the resulting offsets
  710. * are [start, end). e_index always points to the last block in the
  711. * range.
  712. */
  713. s_index = pcpu_off_to_block_index(bit_off);
  714. e_index = pcpu_off_to_block_index(bit_off + bits - 1);
  715. s_off = pcpu_off_to_block_off(bit_off);
  716. e_off = pcpu_off_to_block_off(bit_off + bits - 1) + 1;
  717. s_block = chunk->md_blocks + s_index;
  718. e_block = chunk->md_blocks + e_index;
  719. /*
  720. * Check if the freed area aligns with the block->contig_hint.
  721. * If it does, then the scan to find the beginning/end of the
  722. * larger free area can be avoided.
  723. *
  724. * start and end refer to beginning and end of the free area
  725. * within each their respective blocks. This is not necessarily
  726. * the entire free area as it may span blocks past the beginning
  727. * or end of the block.
  728. */
  729. start = s_off;
  730. if (s_off == s_block->contig_hint + s_block->contig_hint_start) {
  731. start = s_block->contig_hint_start;
  732. } else {
  733. /*
  734. * Scan backwards to find the extent of the free area.
  735. * find_last_bit returns the starting bit, so if the start bit
  736. * is returned, that means there was no last bit and the
  737. * remainder of the chunk is free.
  738. */
  739. int l_bit = find_last_bit(pcpu_index_alloc_map(chunk, s_index),
  740. start);
  741. start = (start == l_bit) ? 0 : l_bit + 1;
  742. }
  743. end = e_off;
  744. if (e_off == e_block->contig_hint_start)
  745. end = e_block->contig_hint_start + e_block->contig_hint;
  746. else
  747. end = find_next_bit(pcpu_index_alloc_map(chunk, e_index),
  748. PCPU_BITMAP_BLOCK_BITS, end);
  749. /* update s_block */
  750. e_off = (s_index == e_index) ? end : PCPU_BITMAP_BLOCK_BITS;
  751. pcpu_block_update(s_block, start, e_off);
  752. /* freeing in the same block */
  753. if (s_index != e_index) {
  754. /* update e_block */
  755. pcpu_block_update(e_block, 0, end);
  756. /* reset md_blocks in the middle */
  757. for (block = s_block + 1; block < e_block; block++) {
  758. block->first_free = 0;
  759. block->contig_hint_start = 0;
  760. block->contig_hint = PCPU_BITMAP_BLOCK_BITS;
  761. block->left_free = PCPU_BITMAP_BLOCK_BITS;
  762. block->right_free = PCPU_BITMAP_BLOCK_BITS;
  763. }
  764. }
  765. /*
  766. * Refresh chunk metadata when the free makes a page free, a block
  767. * free, or spans across blocks. The contig hint may be off by up to
  768. * a page, but if the hint is contained in a block, it will be accurate
  769. * with the else condition below.
  770. */
  771. if ((ALIGN_DOWN(end, min(PCPU_BITS_PER_PAGE, PCPU_BITMAP_BLOCK_BITS)) >
  772. ALIGN(start, min(PCPU_BITS_PER_PAGE, PCPU_BITMAP_BLOCK_BITS))) ||
  773. s_index != e_index)
  774. pcpu_chunk_refresh_hint(chunk);
  775. else
  776. pcpu_chunk_update(chunk, pcpu_block_off_to_off(s_index, start),
  777. s_block->contig_hint);
  778. }
  779. /**
  780. * pcpu_is_populated - determines if the region is populated
  781. * @chunk: chunk of interest
  782. * @bit_off: chunk offset
  783. * @bits: size of area
  784. * @next_off: return value for the next offset to start searching
  785. *
  786. * For atomic allocations, check if the backing pages are populated.
  787. *
  788. * RETURNS:
  789. * Bool if the backing pages are populated.
  790. * next_index is to skip over unpopulated blocks in pcpu_find_block_fit.
  791. */
  792. static bool pcpu_is_populated(struct pcpu_chunk *chunk, int bit_off, int bits,
  793. int *next_off)
  794. {
  795. int page_start, page_end, rs, re;
  796. page_start = PFN_DOWN(bit_off * PCPU_MIN_ALLOC_SIZE);
  797. page_end = PFN_UP((bit_off + bits) * PCPU_MIN_ALLOC_SIZE);
  798. rs = page_start;
  799. pcpu_next_unpop(chunk->populated, &rs, &re, page_end);
  800. if (rs >= page_end)
  801. return true;
  802. *next_off = re * PAGE_SIZE / PCPU_MIN_ALLOC_SIZE;
  803. return false;
  804. }
  805. /**
  806. * pcpu_find_block_fit - finds the block index to start searching
  807. * @chunk: chunk of interest
  808. * @alloc_bits: size of request in allocation units
  809. * @align: alignment of area (max PAGE_SIZE bytes)
  810. * @pop_only: use populated regions only
  811. *
  812. * Given a chunk and an allocation spec, find the offset to begin searching
  813. * for a free region. This iterates over the bitmap metadata blocks to
  814. * find an offset that will be guaranteed to fit the requirements. It is
  815. * not quite first fit as if the allocation does not fit in the contig hint
  816. * of a block or chunk, it is skipped. This errs on the side of caution
  817. * to prevent excess iteration. Poor alignment can cause the allocator to
  818. * skip over blocks and chunks that have valid free areas.
  819. *
  820. * RETURNS:
  821. * The offset in the bitmap to begin searching.
  822. * -1 if no offset is found.
  823. */
  824. static int pcpu_find_block_fit(struct pcpu_chunk *chunk, int alloc_bits,
  825. size_t align, bool pop_only)
  826. {
  827. int bit_off, bits, next_off;
  828. /*
  829. * Check to see if the allocation can fit in the chunk's contig hint.
  830. * This is an optimization to prevent scanning by assuming if it
  831. * cannot fit in the global hint, there is memory pressure and creating
  832. * a new chunk would happen soon.
  833. */
  834. bit_off = ALIGN(chunk->contig_bits_start, align) -
  835. chunk->contig_bits_start;
  836. if (bit_off + alloc_bits > chunk->contig_bits)
  837. return -1;
  838. bit_off = chunk->first_bit;
  839. bits = 0;
  840. pcpu_for_each_fit_region(chunk, alloc_bits, align, bit_off, bits) {
  841. if (!pop_only || pcpu_is_populated(chunk, bit_off, bits,
  842. &next_off))
  843. break;
  844. bit_off = next_off;
  845. bits = 0;
  846. }
  847. if (bit_off == pcpu_chunk_map_bits(chunk))
  848. return -1;
  849. return bit_off;
  850. }
  851. /**
  852. * pcpu_alloc_area - allocates an area from a pcpu_chunk
  853. * @chunk: chunk of interest
  854. * @alloc_bits: size of request in allocation units
  855. * @align: alignment of area (max PAGE_SIZE)
  856. * @start: bit_off to start searching
  857. *
  858. * This function takes in a @start offset to begin searching to fit an
  859. * allocation of @alloc_bits with alignment @align. It needs to scan
  860. * the allocation map because if it fits within the block's contig hint,
  861. * @start will be block->first_free. This is an attempt to fill the
  862. * allocation prior to breaking the contig hint. The allocation and
  863. * boundary maps are updated accordingly if it confirms a valid
  864. * free area.
  865. *
  866. * RETURNS:
  867. * Allocated addr offset in @chunk on success.
  868. * -1 if no matching area is found.
  869. */
  870. static int pcpu_alloc_area(struct pcpu_chunk *chunk, int alloc_bits,
  871. size_t align, int start)
  872. {
  873. size_t align_mask = (align) ? (align - 1) : 0;
  874. int bit_off, end, oslot;
  875. lockdep_assert_held(&pcpu_lock);
  876. oslot = pcpu_chunk_slot(chunk);
  877. /*
  878. * Search to find a fit.
  879. */
  880. end = min_t(int, start + alloc_bits + PCPU_BITMAP_BLOCK_BITS,
  881. pcpu_chunk_map_bits(chunk));
  882. bit_off = bitmap_find_next_zero_area(chunk->alloc_map, end, start,
  883. alloc_bits, align_mask);
  884. if (bit_off >= end)
  885. return -1;
  886. /* update alloc map */
  887. bitmap_set(chunk->alloc_map, bit_off, alloc_bits);
  888. /* update boundary map */
  889. set_bit(bit_off, chunk->bound_map);
  890. bitmap_clear(chunk->bound_map, bit_off + 1, alloc_bits - 1);
  891. set_bit(bit_off + alloc_bits, chunk->bound_map);
  892. chunk->free_bytes -= alloc_bits * PCPU_MIN_ALLOC_SIZE;
  893. /* update first free bit */
  894. if (bit_off == chunk->first_bit)
  895. chunk->first_bit = find_next_zero_bit(
  896. chunk->alloc_map,
  897. pcpu_chunk_map_bits(chunk),
  898. bit_off + alloc_bits);
  899. pcpu_block_update_hint_alloc(chunk, bit_off, alloc_bits);
  900. pcpu_chunk_relocate(chunk, oslot);
  901. return bit_off * PCPU_MIN_ALLOC_SIZE;
  902. }
  903. /**
  904. * pcpu_free_area - frees the corresponding offset
  905. * @chunk: chunk of interest
  906. * @off: addr offset into chunk
  907. *
  908. * This function determines the size of an allocation to free using
  909. * the boundary bitmap and clears the allocation map.
  910. */
  911. static void pcpu_free_area(struct pcpu_chunk *chunk, int off)
  912. {
  913. int bit_off, bits, end, oslot;
  914. lockdep_assert_held(&pcpu_lock);
  915. pcpu_stats_area_dealloc(chunk);
  916. oslot = pcpu_chunk_slot(chunk);
  917. bit_off = off / PCPU_MIN_ALLOC_SIZE;
  918. /* find end index */
  919. end = find_next_bit(chunk->bound_map, pcpu_chunk_map_bits(chunk),
  920. bit_off + 1);
  921. bits = end - bit_off;
  922. bitmap_clear(chunk->alloc_map, bit_off, bits);
  923. /* update metadata */
  924. chunk->free_bytes += bits * PCPU_MIN_ALLOC_SIZE;
  925. /* update first free bit */
  926. chunk->first_bit = min(chunk->first_bit, bit_off);
  927. pcpu_block_update_hint_free(chunk, bit_off, bits);
  928. pcpu_chunk_relocate(chunk, oslot);
  929. }
  930. static void pcpu_init_md_blocks(struct pcpu_chunk *chunk)
  931. {
  932. struct pcpu_block_md *md_block;
  933. for (md_block = chunk->md_blocks;
  934. md_block != chunk->md_blocks + pcpu_chunk_nr_blocks(chunk);
  935. md_block++) {
  936. md_block->contig_hint = PCPU_BITMAP_BLOCK_BITS;
  937. md_block->left_free = PCPU_BITMAP_BLOCK_BITS;
  938. md_block->right_free = PCPU_BITMAP_BLOCK_BITS;
  939. }
  940. }
  941. /**
  942. * pcpu_alloc_first_chunk - creates chunks that serve the first chunk
  943. * @tmp_addr: the start of the region served
  944. * @map_size: size of the region served
  945. *
  946. * This is responsible for creating the chunks that serve the first chunk. The
  947. * base_addr is page aligned down of @tmp_addr while the region end is page
  948. * aligned up. Offsets are kept track of to determine the region served. All
  949. * this is done to appease the bitmap allocator in avoiding partial blocks.
  950. *
  951. * RETURNS:
  952. * Chunk serving the region at @tmp_addr of @map_size.
  953. */
  954. static struct pcpu_chunk * __init pcpu_alloc_first_chunk(unsigned long tmp_addr,
  955. int map_size)
  956. {
  957. struct pcpu_chunk *chunk;
  958. unsigned long aligned_addr, lcm_align;
  959. int start_offset, offset_bits, region_size, region_bits;
  960. /* region calculations */
  961. aligned_addr = tmp_addr & PAGE_MASK;
  962. start_offset = tmp_addr - aligned_addr;
  963. /*
  964. * Align the end of the region with the LCM of PAGE_SIZE and
  965. * PCPU_BITMAP_BLOCK_SIZE. One of these constants is a multiple of
  966. * the other.
  967. */
  968. lcm_align = lcm(PAGE_SIZE, PCPU_BITMAP_BLOCK_SIZE);
  969. region_size = ALIGN(start_offset + map_size, lcm_align);
  970. /* allocate chunk */
  971. chunk = memblock_virt_alloc(sizeof(struct pcpu_chunk) +
  972. BITS_TO_LONGS(region_size >> PAGE_SHIFT) * sizeof(unsigned long),
  973. 0);
  974. INIT_LIST_HEAD(&chunk->list);
  975. chunk->base_addr = (void *)aligned_addr;
  976. chunk->start_offset = start_offset;
  977. chunk->end_offset = region_size - chunk->start_offset - map_size;
  978. chunk->nr_pages = region_size >> PAGE_SHIFT;
  979. region_bits = pcpu_chunk_map_bits(chunk);
  980. chunk->alloc_map = memblock_virt_alloc(BITS_TO_LONGS(region_bits) *
  981. sizeof(chunk->alloc_map[0]), 0);
  982. chunk->bound_map = memblock_virt_alloc(BITS_TO_LONGS(region_bits + 1) *
  983. sizeof(chunk->bound_map[0]), 0);
  984. chunk->md_blocks = memblock_virt_alloc(pcpu_chunk_nr_blocks(chunk) *
  985. sizeof(chunk->md_blocks[0]), 0);
  986. pcpu_init_md_blocks(chunk);
  987. /* manage populated page bitmap */
  988. chunk->immutable = true;
  989. bitmap_fill(chunk->populated, chunk->nr_pages);
  990. chunk->nr_populated = chunk->nr_pages;
  991. chunk->nr_empty_pop_pages =
  992. pcpu_cnt_pop_pages(chunk, start_offset / PCPU_MIN_ALLOC_SIZE,
  993. map_size / PCPU_MIN_ALLOC_SIZE);
  994. chunk->contig_bits = map_size / PCPU_MIN_ALLOC_SIZE;
  995. chunk->free_bytes = map_size;
  996. if (chunk->start_offset) {
  997. /* hide the beginning of the bitmap */
  998. offset_bits = chunk->start_offset / PCPU_MIN_ALLOC_SIZE;
  999. bitmap_set(chunk->alloc_map, 0, offset_bits);
  1000. set_bit(0, chunk->bound_map);
  1001. set_bit(offset_bits, chunk->bound_map);
  1002. chunk->first_bit = offset_bits;
  1003. pcpu_block_update_hint_alloc(chunk, 0, offset_bits);
  1004. }
  1005. if (chunk->end_offset) {
  1006. /* hide the end of the bitmap */
  1007. offset_bits = chunk->end_offset / PCPU_MIN_ALLOC_SIZE;
  1008. bitmap_set(chunk->alloc_map,
  1009. pcpu_chunk_map_bits(chunk) - offset_bits,
  1010. offset_bits);
  1011. set_bit((start_offset + map_size) / PCPU_MIN_ALLOC_SIZE,
  1012. chunk->bound_map);
  1013. set_bit(region_bits, chunk->bound_map);
  1014. pcpu_block_update_hint_alloc(chunk, pcpu_chunk_map_bits(chunk)
  1015. - offset_bits, offset_bits);
  1016. }
  1017. return chunk;
  1018. }
  1019. static struct pcpu_chunk *pcpu_alloc_chunk(gfp_t gfp)
  1020. {
  1021. struct pcpu_chunk *chunk;
  1022. int region_bits;
  1023. chunk = pcpu_mem_zalloc(pcpu_chunk_struct_size, gfp);
  1024. if (!chunk)
  1025. return NULL;
  1026. INIT_LIST_HEAD(&chunk->list);
  1027. chunk->nr_pages = pcpu_unit_pages;
  1028. region_bits = pcpu_chunk_map_bits(chunk);
  1029. chunk->alloc_map = pcpu_mem_zalloc(BITS_TO_LONGS(region_bits) *
  1030. sizeof(chunk->alloc_map[0]), gfp);
  1031. if (!chunk->alloc_map)
  1032. goto alloc_map_fail;
  1033. chunk->bound_map = pcpu_mem_zalloc(BITS_TO_LONGS(region_bits + 1) *
  1034. sizeof(chunk->bound_map[0]), gfp);
  1035. if (!chunk->bound_map)
  1036. goto bound_map_fail;
  1037. chunk->md_blocks = pcpu_mem_zalloc(pcpu_chunk_nr_blocks(chunk) *
  1038. sizeof(chunk->md_blocks[0]), gfp);
  1039. if (!chunk->md_blocks)
  1040. goto md_blocks_fail;
  1041. pcpu_init_md_blocks(chunk);
  1042. /* init metadata */
  1043. chunk->contig_bits = region_bits;
  1044. chunk->free_bytes = chunk->nr_pages * PAGE_SIZE;
  1045. return chunk;
  1046. md_blocks_fail:
  1047. pcpu_mem_free(chunk->bound_map);
  1048. bound_map_fail:
  1049. pcpu_mem_free(chunk->alloc_map);
  1050. alloc_map_fail:
  1051. pcpu_mem_free(chunk);
  1052. return NULL;
  1053. }
  1054. static void pcpu_free_chunk(struct pcpu_chunk *chunk)
  1055. {
  1056. if (!chunk)
  1057. return;
  1058. pcpu_mem_free(chunk->md_blocks);
  1059. pcpu_mem_free(chunk->bound_map);
  1060. pcpu_mem_free(chunk->alloc_map);
  1061. pcpu_mem_free(chunk);
  1062. }
  1063. /**
  1064. * pcpu_chunk_populated - post-population bookkeeping
  1065. * @chunk: pcpu_chunk which got populated
  1066. * @page_start: the start page
  1067. * @page_end: the end page
  1068. * @for_alloc: if this is to populate for allocation
  1069. *
  1070. * Pages in [@page_start,@page_end) have been populated to @chunk. Update
  1071. * the bookkeeping information accordingly. Must be called after each
  1072. * successful population.
  1073. *
  1074. * If this is @for_alloc, do not increment pcpu_nr_empty_pop_pages because it
  1075. * is to serve an allocation in that area.
  1076. */
  1077. static void pcpu_chunk_populated(struct pcpu_chunk *chunk, int page_start,
  1078. int page_end, bool for_alloc)
  1079. {
  1080. int nr = page_end - page_start;
  1081. lockdep_assert_held(&pcpu_lock);
  1082. bitmap_set(chunk->populated, page_start, nr);
  1083. chunk->nr_populated += nr;
  1084. if (!for_alloc) {
  1085. chunk->nr_empty_pop_pages += nr;
  1086. pcpu_nr_empty_pop_pages += nr;
  1087. }
  1088. }
  1089. /**
  1090. * pcpu_chunk_depopulated - post-depopulation bookkeeping
  1091. * @chunk: pcpu_chunk which got depopulated
  1092. * @page_start: the start page
  1093. * @page_end: the end page
  1094. *
  1095. * Pages in [@page_start,@page_end) have been depopulated from @chunk.
  1096. * Update the bookkeeping information accordingly. Must be called after
  1097. * each successful depopulation.
  1098. */
  1099. static void pcpu_chunk_depopulated(struct pcpu_chunk *chunk,
  1100. int page_start, int page_end)
  1101. {
  1102. int nr = page_end - page_start;
  1103. lockdep_assert_held(&pcpu_lock);
  1104. bitmap_clear(chunk->populated, page_start, nr);
  1105. chunk->nr_populated -= nr;
  1106. chunk->nr_empty_pop_pages -= nr;
  1107. pcpu_nr_empty_pop_pages -= nr;
  1108. }
  1109. /*
  1110. * Chunk management implementation.
  1111. *
  1112. * To allow different implementations, chunk alloc/free and
  1113. * [de]population are implemented in a separate file which is pulled
  1114. * into this file and compiled together. The following functions
  1115. * should be implemented.
  1116. *
  1117. * pcpu_populate_chunk - populate the specified range of a chunk
  1118. * pcpu_depopulate_chunk - depopulate the specified range of a chunk
  1119. * pcpu_create_chunk - create a new chunk
  1120. * pcpu_destroy_chunk - destroy a chunk, always preceded by full depop
  1121. * pcpu_addr_to_page - translate address to physical address
  1122. * pcpu_verify_alloc_info - check alloc_info is acceptable during init
  1123. */
  1124. static int pcpu_populate_chunk(struct pcpu_chunk *chunk, int off, int size,
  1125. gfp_t gfp);
  1126. static void pcpu_depopulate_chunk(struct pcpu_chunk *chunk, int off, int size);
  1127. static struct pcpu_chunk *pcpu_create_chunk(gfp_t gfp);
  1128. static void pcpu_destroy_chunk(struct pcpu_chunk *chunk);
  1129. static struct page *pcpu_addr_to_page(void *addr);
  1130. static int __init pcpu_verify_alloc_info(const struct pcpu_alloc_info *ai);
  1131. #ifdef CONFIG_NEED_PER_CPU_KM
  1132. #include "percpu-km.c"
  1133. #else
  1134. #include "percpu-vm.c"
  1135. #endif
  1136. /**
  1137. * pcpu_chunk_addr_search - determine chunk containing specified address
  1138. * @addr: address for which the chunk needs to be determined.
  1139. *
  1140. * This is an internal function that handles all but static allocations.
  1141. * Static percpu address values should never be passed into the allocator.
  1142. *
  1143. * RETURNS:
  1144. * The address of the found chunk.
  1145. */
  1146. static struct pcpu_chunk *pcpu_chunk_addr_search(void *addr)
  1147. {
  1148. /* is it in the dynamic region (first chunk)? */
  1149. if (pcpu_addr_in_chunk(pcpu_first_chunk, addr))
  1150. return pcpu_first_chunk;
  1151. /* is it in the reserved region? */
  1152. if (pcpu_addr_in_chunk(pcpu_reserved_chunk, addr))
  1153. return pcpu_reserved_chunk;
  1154. /*
  1155. * The address is relative to unit0 which might be unused and
  1156. * thus unmapped. Offset the address to the unit space of the
  1157. * current processor before looking it up in the vmalloc
  1158. * space. Note that any possible cpu id can be used here, so
  1159. * there's no need to worry about preemption or cpu hotplug.
  1160. */
  1161. addr += pcpu_unit_offsets[raw_smp_processor_id()];
  1162. return pcpu_get_page_chunk(pcpu_addr_to_page(addr));
  1163. }
  1164. /**
  1165. * pcpu_alloc - the percpu allocator
  1166. * @size: size of area to allocate in bytes
  1167. * @align: alignment of area (max PAGE_SIZE)
  1168. * @reserved: allocate from the reserved chunk if available
  1169. * @gfp: allocation flags
  1170. *
  1171. * Allocate percpu area of @size bytes aligned at @align. If @gfp doesn't
  1172. * contain %GFP_KERNEL, the allocation is atomic. If @gfp has __GFP_NOWARN
  1173. * then no warning will be triggered on invalid or failed allocation
  1174. * requests.
  1175. *
  1176. * RETURNS:
  1177. * Percpu pointer to the allocated area on success, NULL on failure.
  1178. */
  1179. static void __percpu *pcpu_alloc(size_t size, size_t align, bool reserved,
  1180. gfp_t gfp)
  1181. {
  1182. bool is_atomic = (gfp & GFP_KERNEL) != GFP_KERNEL;
  1183. bool do_warn = !(gfp & __GFP_NOWARN);
  1184. static int warn_limit = 10;
  1185. struct pcpu_chunk *chunk;
  1186. const char *err;
  1187. int slot, off, cpu, ret;
  1188. unsigned long flags;
  1189. void __percpu *ptr;
  1190. size_t bits, bit_align;
  1191. /*
  1192. * There is now a minimum allocation size of PCPU_MIN_ALLOC_SIZE,
  1193. * therefore alignment must be a minimum of that many bytes.
  1194. * An allocation may have internal fragmentation from rounding up
  1195. * of up to PCPU_MIN_ALLOC_SIZE - 1 bytes.
  1196. */
  1197. if (unlikely(align < PCPU_MIN_ALLOC_SIZE))
  1198. align = PCPU_MIN_ALLOC_SIZE;
  1199. size = ALIGN(size, PCPU_MIN_ALLOC_SIZE);
  1200. bits = size >> PCPU_MIN_ALLOC_SHIFT;
  1201. bit_align = align >> PCPU_MIN_ALLOC_SHIFT;
  1202. if (unlikely(!size || size > PCPU_MIN_UNIT_SIZE || align > PAGE_SIZE ||
  1203. !is_power_of_2(align))) {
  1204. WARN(do_warn, "illegal size (%zu) or align (%zu) for percpu allocation\n",
  1205. size, align);
  1206. return NULL;
  1207. }
  1208. if (!is_atomic)
  1209. mutex_lock(&pcpu_alloc_mutex);
  1210. spin_lock_irqsave(&pcpu_lock, flags);
  1211. /* serve reserved allocations from the reserved chunk if available */
  1212. if (reserved && pcpu_reserved_chunk) {
  1213. chunk = pcpu_reserved_chunk;
  1214. off = pcpu_find_block_fit(chunk, bits, bit_align, is_atomic);
  1215. if (off < 0) {
  1216. err = "alloc from reserved chunk failed";
  1217. goto fail_unlock;
  1218. }
  1219. off = pcpu_alloc_area(chunk, bits, bit_align, off);
  1220. if (off >= 0)
  1221. goto area_found;
  1222. err = "alloc from reserved chunk failed";
  1223. goto fail_unlock;
  1224. }
  1225. restart:
  1226. /* search through normal chunks */
  1227. for (slot = pcpu_size_to_slot(size); slot < pcpu_nr_slots; slot++) {
  1228. list_for_each_entry(chunk, &pcpu_slot[slot], list) {
  1229. off = pcpu_find_block_fit(chunk, bits, bit_align,
  1230. is_atomic);
  1231. if (off < 0)
  1232. continue;
  1233. off = pcpu_alloc_area(chunk, bits, bit_align, off);
  1234. if (off >= 0)
  1235. goto area_found;
  1236. }
  1237. }
  1238. spin_unlock_irqrestore(&pcpu_lock, flags);
  1239. /*
  1240. * No space left. Create a new chunk. We don't want multiple
  1241. * tasks to create chunks simultaneously. Serialize and create iff
  1242. * there's still no empty chunk after grabbing the mutex.
  1243. */
  1244. if (is_atomic) {
  1245. err = "atomic alloc failed, no space left";
  1246. goto fail;
  1247. }
  1248. if (list_empty(&pcpu_slot[pcpu_nr_slots - 1])) {
  1249. chunk = pcpu_create_chunk(0);
  1250. if (!chunk) {
  1251. err = "failed to allocate new chunk";
  1252. goto fail;
  1253. }
  1254. spin_lock_irqsave(&pcpu_lock, flags);
  1255. pcpu_chunk_relocate(chunk, -1);
  1256. } else {
  1257. spin_lock_irqsave(&pcpu_lock, flags);
  1258. }
  1259. goto restart;
  1260. area_found:
  1261. pcpu_stats_area_alloc(chunk, size);
  1262. spin_unlock_irqrestore(&pcpu_lock, flags);
  1263. /* populate if not all pages are already there */
  1264. if (!is_atomic) {
  1265. int page_start, page_end, rs, re;
  1266. page_start = PFN_DOWN(off);
  1267. page_end = PFN_UP(off + size);
  1268. pcpu_for_each_unpop_region(chunk->populated, rs, re,
  1269. page_start, page_end) {
  1270. WARN_ON(chunk->immutable);
  1271. ret = pcpu_populate_chunk(chunk, rs, re, 0);
  1272. spin_lock_irqsave(&pcpu_lock, flags);
  1273. if (ret) {
  1274. pcpu_free_area(chunk, off);
  1275. err = "failed to populate";
  1276. goto fail_unlock;
  1277. }
  1278. pcpu_chunk_populated(chunk, rs, re, true);
  1279. spin_unlock_irqrestore(&pcpu_lock, flags);
  1280. }
  1281. mutex_unlock(&pcpu_alloc_mutex);
  1282. }
  1283. if (pcpu_nr_empty_pop_pages < PCPU_EMPTY_POP_PAGES_LOW)
  1284. pcpu_schedule_balance_work();
  1285. /* clear the areas and return address relative to base address */
  1286. for_each_possible_cpu(cpu)
  1287. memset((void *)pcpu_chunk_addr(chunk, cpu, 0) + off, 0, size);
  1288. ptr = __addr_to_pcpu_ptr(chunk->base_addr + off);
  1289. kmemleak_alloc_percpu(ptr, size, gfp);
  1290. trace_percpu_alloc_percpu(reserved, is_atomic, size, align,
  1291. chunk->base_addr, off, ptr);
  1292. return ptr;
  1293. fail_unlock:
  1294. spin_unlock_irqrestore(&pcpu_lock, flags);
  1295. fail:
  1296. trace_percpu_alloc_percpu_fail(reserved, is_atomic, size, align);
  1297. if (!is_atomic && do_warn && warn_limit) {
  1298. pr_warn("allocation failed, size=%zu align=%zu atomic=%d, %s\n",
  1299. size, align, is_atomic, err);
  1300. dump_stack();
  1301. if (!--warn_limit)
  1302. pr_info("limit reached, disable warning\n");
  1303. }
  1304. if (is_atomic) {
  1305. /* see the flag handling in pcpu_blance_workfn() */
  1306. pcpu_atomic_alloc_failed = true;
  1307. pcpu_schedule_balance_work();
  1308. } else {
  1309. mutex_unlock(&pcpu_alloc_mutex);
  1310. }
  1311. return NULL;
  1312. }
  1313. /**
  1314. * __alloc_percpu_gfp - allocate dynamic percpu area
  1315. * @size: size of area to allocate in bytes
  1316. * @align: alignment of area (max PAGE_SIZE)
  1317. * @gfp: allocation flags
  1318. *
  1319. * Allocate zero-filled percpu area of @size bytes aligned at @align. If
  1320. * @gfp doesn't contain %GFP_KERNEL, the allocation doesn't block and can
  1321. * be called from any context but is a lot more likely to fail. If @gfp
  1322. * has __GFP_NOWARN then no warning will be triggered on invalid or failed
  1323. * allocation requests.
  1324. *
  1325. * RETURNS:
  1326. * Percpu pointer to the allocated area on success, NULL on failure.
  1327. */
  1328. void __percpu *__alloc_percpu_gfp(size_t size, size_t align, gfp_t gfp)
  1329. {
  1330. return pcpu_alloc(size, align, false, gfp);
  1331. }
  1332. EXPORT_SYMBOL_GPL(__alloc_percpu_gfp);
  1333. /**
  1334. * __alloc_percpu - allocate dynamic percpu area
  1335. * @size: size of area to allocate in bytes
  1336. * @align: alignment of area (max PAGE_SIZE)
  1337. *
  1338. * Equivalent to __alloc_percpu_gfp(size, align, %GFP_KERNEL).
  1339. */
  1340. void __percpu *__alloc_percpu(size_t size, size_t align)
  1341. {
  1342. return pcpu_alloc(size, align, false, GFP_KERNEL);
  1343. }
  1344. EXPORT_SYMBOL_GPL(__alloc_percpu);
  1345. /**
  1346. * __alloc_reserved_percpu - allocate reserved percpu area
  1347. * @size: size of area to allocate in bytes
  1348. * @align: alignment of area (max PAGE_SIZE)
  1349. *
  1350. * Allocate zero-filled percpu area of @size bytes aligned at @align
  1351. * from reserved percpu area if arch has set it up; otherwise,
  1352. * allocation is served from the same dynamic area. Might sleep.
  1353. * Might trigger writeouts.
  1354. *
  1355. * CONTEXT:
  1356. * Does GFP_KERNEL allocation.
  1357. *
  1358. * RETURNS:
  1359. * Percpu pointer to the allocated area on success, NULL on failure.
  1360. */
  1361. void __percpu *__alloc_reserved_percpu(size_t size, size_t align)
  1362. {
  1363. return pcpu_alloc(size, align, true, GFP_KERNEL);
  1364. }
  1365. /**
  1366. * pcpu_balance_workfn - manage the amount of free chunks and populated pages
  1367. * @work: unused
  1368. *
  1369. * Reclaim all fully free chunks except for the first one. This is also
  1370. * responsible for maintaining the pool of empty populated pages. However,
  1371. * it is possible that this is called when physical memory is scarce causing
  1372. * OOM killer to be triggered. We should avoid doing so until an actual
  1373. * allocation causes the failure as it is possible that requests can be
  1374. * serviced from already backed regions.
  1375. */
  1376. static void pcpu_balance_workfn(struct work_struct *work)
  1377. {
  1378. /* gfp flags passed to underlying allocators */
  1379. const gfp_t gfp = __GFP_NORETRY | __GFP_NOWARN;
  1380. LIST_HEAD(to_free);
  1381. struct list_head *free_head = &pcpu_slot[pcpu_nr_slots - 1];
  1382. struct pcpu_chunk *chunk, *next;
  1383. int slot, nr_to_pop, ret;
  1384. /*
  1385. * There's no reason to keep around multiple unused chunks and VM
  1386. * areas can be scarce. Destroy all free chunks except for one.
  1387. */
  1388. mutex_lock(&pcpu_alloc_mutex);
  1389. spin_lock_irq(&pcpu_lock);
  1390. list_for_each_entry_safe(chunk, next, free_head, list) {
  1391. WARN_ON(chunk->immutable);
  1392. /* spare the first one */
  1393. if (chunk == list_first_entry(free_head, struct pcpu_chunk, list))
  1394. continue;
  1395. list_move(&chunk->list, &to_free);
  1396. }
  1397. spin_unlock_irq(&pcpu_lock);
  1398. list_for_each_entry_safe(chunk, next, &to_free, list) {
  1399. int rs, re;
  1400. pcpu_for_each_pop_region(chunk->populated, rs, re, 0,
  1401. chunk->nr_pages) {
  1402. pcpu_depopulate_chunk(chunk, rs, re);
  1403. spin_lock_irq(&pcpu_lock);
  1404. pcpu_chunk_depopulated(chunk, rs, re);
  1405. spin_unlock_irq(&pcpu_lock);
  1406. }
  1407. pcpu_destroy_chunk(chunk);
  1408. }
  1409. /*
  1410. * Ensure there are certain number of free populated pages for
  1411. * atomic allocs. Fill up from the most packed so that atomic
  1412. * allocs don't increase fragmentation. If atomic allocation
  1413. * failed previously, always populate the maximum amount. This
  1414. * should prevent atomic allocs larger than PAGE_SIZE from keeping
  1415. * failing indefinitely; however, large atomic allocs are not
  1416. * something we support properly and can be highly unreliable and
  1417. * inefficient.
  1418. */
  1419. retry_pop:
  1420. if (pcpu_atomic_alloc_failed) {
  1421. nr_to_pop = PCPU_EMPTY_POP_PAGES_HIGH;
  1422. /* best effort anyway, don't worry about synchronization */
  1423. pcpu_atomic_alloc_failed = false;
  1424. } else {
  1425. nr_to_pop = clamp(PCPU_EMPTY_POP_PAGES_HIGH -
  1426. pcpu_nr_empty_pop_pages,
  1427. 0, PCPU_EMPTY_POP_PAGES_HIGH);
  1428. }
  1429. for (slot = pcpu_size_to_slot(PAGE_SIZE); slot < pcpu_nr_slots; slot++) {
  1430. int nr_unpop = 0, rs, re;
  1431. if (!nr_to_pop)
  1432. break;
  1433. spin_lock_irq(&pcpu_lock);
  1434. list_for_each_entry(chunk, &pcpu_slot[slot], list) {
  1435. nr_unpop = chunk->nr_pages - chunk->nr_populated;
  1436. if (nr_unpop)
  1437. break;
  1438. }
  1439. spin_unlock_irq(&pcpu_lock);
  1440. if (!nr_unpop)
  1441. continue;
  1442. /* @chunk can't go away while pcpu_alloc_mutex is held */
  1443. pcpu_for_each_unpop_region(chunk->populated, rs, re, 0,
  1444. chunk->nr_pages) {
  1445. int nr = min(re - rs, nr_to_pop);
  1446. ret = pcpu_populate_chunk(chunk, rs, rs + nr, gfp);
  1447. if (!ret) {
  1448. nr_to_pop -= nr;
  1449. spin_lock_irq(&pcpu_lock);
  1450. pcpu_chunk_populated(chunk, rs, rs + nr, false);
  1451. spin_unlock_irq(&pcpu_lock);
  1452. } else {
  1453. nr_to_pop = 0;
  1454. }
  1455. if (!nr_to_pop)
  1456. break;
  1457. }
  1458. }
  1459. if (nr_to_pop) {
  1460. /* ran out of chunks to populate, create a new one and retry */
  1461. chunk = pcpu_create_chunk(gfp);
  1462. if (chunk) {
  1463. spin_lock_irq(&pcpu_lock);
  1464. pcpu_chunk_relocate(chunk, -1);
  1465. spin_unlock_irq(&pcpu_lock);
  1466. goto retry_pop;
  1467. }
  1468. }
  1469. mutex_unlock(&pcpu_alloc_mutex);
  1470. }
  1471. /**
  1472. * free_percpu - free percpu area
  1473. * @ptr: pointer to area to free
  1474. *
  1475. * Free percpu area @ptr.
  1476. *
  1477. * CONTEXT:
  1478. * Can be called from atomic context.
  1479. */
  1480. void free_percpu(void __percpu *ptr)
  1481. {
  1482. void *addr;
  1483. struct pcpu_chunk *chunk;
  1484. unsigned long flags;
  1485. int off;
  1486. bool need_balance = false;
  1487. if (!ptr)
  1488. return;
  1489. kmemleak_free_percpu(ptr);
  1490. addr = __pcpu_ptr_to_addr(ptr);
  1491. spin_lock_irqsave(&pcpu_lock, flags);
  1492. chunk = pcpu_chunk_addr_search(addr);
  1493. off = addr - chunk->base_addr;
  1494. pcpu_free_area(chunk, off);
  1495. /* if there are more than one fully free chunks, wake up grim reaper */
  1496. if (chunk->free_bytes == pcpu_unit_size) {
  1497. struct pcpu_chunk *pos;
  1498. list_for_each_entry(pos, &pcpu_slot[pcpu_nr_slots - 1], list)
  1499. if (pos != chunk) {
  1500. need_balance = true;
  1501. break;
  1502. }
  1503. }
  1504. trace_percpu_free_percpu(chunk->base_addr, off, ptr);
  1505. spin_unlock_irqrestore(&pcpu_lock, flags);
  1506. if (need_balance)
  1507. pcpu_schedule_balance_work();
  1508. }
  1509. EXPORT_SYMBOL_GPL(free_percpu);
  1510. bool __is_kernel_percpu_address(unsigned long addr, unsigned long *can_addr)
  1511. {
  1512. #ifdef CONFIG_SMP
  1513. const size_t static_size = __per_cpu_end - __per_cpu_start;
  1514. void __percpu *base = __addr_to_pcpu_ptr(pcpu_base_addr);
  1515. unsigned int cpu;
  1516. for_each_possible_cpu(cpu) {
  1517. void *start = per_cpu_ptr(base, cpu);
  1518. void *va = (void *)addr;
  1519. if (va >= start && va < start + static_size) {
  1520. if (can_addr) {
  1521. *can_addr = (unsigned long) (va - start);
  1522. *can_addr += (unsigned long)
  1523. per_cpu_ptr(base, get_boot_cpu_id());
  1524. }
  1525. return true;
  1526. }
  1527. }
  1528. #endif
  1529. /* on UP, can't distinguish from other static vars, always false */
  1530. return false;
  1531. }
  1532. /**
  1533. * is_kernel_percpu_address - test whether address is from static percpu area
  1534. * @addr: address to test
  1535. *
  1536. * Test whether @addr belongs to in-kernel static percpu area. Module
  1537. * static percpu areas are not considered. For those, use
  1538. * is_module_percpu_address().
  1539. *
  1540. * RETURNS:
  1541. * %true if @addr is from in-kernel static percpu area, %false otherwise.
  1542. */
  1543. bool is_kernel_percpu_address(unsigned long addr)
  1544. {
  1545. return __is_kernel_percpu_address(addr, NULL);
  1546. }
  1547. /**
  1548. * per_cpu_ptr_to_phys - convert translated percpu address to physical address
  1549. * @addr: the address to be converted to physical address
  1550. *
  1551. * Given @addr which is dereferenceable address obtained via one of
  1552. * percpu access macros, this function translates it into its physical
  1553. * address. The caller is responsible for ensuring @addr stays valid
  1554. * until this function finishes.
  1555. *
  1556. * percpu allocator has special setup for the first chunk, which currently
  1557. * supports either embedding in linear address space or vmalloc mapping,
  1558. * and, from the second one, the backing allocator (currently either vm or
  1559. * km) provides translation.
  1560. *
  1561. * The addr can be translated simply without checking if it falls into the
  1562. * first chunk. But the current code reflects better how percpu allocator
  1563. * actually works, and the verification can discover both bugs in percpu
  1564. * allocator itself and per_cpu_ptr_to_phys() callers. So we keep current
  1565. * code.
  1566. *
  1567. * RETURNS:
  1568. * The physical address for @addr.
  1569. */
  1570. phys_addr_t per_cpu_ptr_to_phys(void *addr)
  1571. {
  1572. void __percpu *base = __addr_to_pcpu_ptr(pcpu_base_addr);
  1573. bool in_first_chunk = false;
  1574. unsigned long first_low, first_high;
  1575. unsigned int cpu;
  1576. /*
  1577. * The following test on unit_low/high isn't strictly
  1578. * necessary but will speed up lookups of addresses which
  1579. * aren't in the first chunk.
  1580. *
  1581. * The address check is against full chunk sizes. pcpu_base_addr
  1582. * points to the beginning of the first chunk including the
  1583. * static region. Assumes good intent as the first chunk may
  1584. * not be full (ie. < pcpu_unit_pages in size).
  1585. */
  1586. first_low = (unsigned long)pcpu_base_addr +
  1587. pcpu_unit_page_offset(pcpu_low_unit_cpu, 0);
  1588. first_high = (unsigned long)pcpu_base_addr +
  1589. pcpu_unit_page_offset(pcpu_high_unit_cpu, pcpu_unit_pages);
  1590. if ((unsigned long)addr >= first_low &&
  1591. (unsigned long)addr < first_high) {
  1592. for_each_possible_cpu(cpu) {
  1593. void *start = per_cpu_ptr(base, cpu);
  1594. if (addr >= start && addr < start + pcpu_unit_size) {
  1595. in_first_chunk = true;
  1596. break;
  1597. }
  1598. }
  1599. }
  1600. if (in_first_chunk) {
  1601. if (!is_vmalloc_addr(addr))
  1602. return __pa(addr);
  1603. else
  1604. return page_to_phys(vmalloc_to_page(addr)) +
  1605. offset_in_page(addr);
  1606. } else
  1607. return page_to_phys(pcpu_addr_to_page(addr)) +
  1608. offset_in_page(addr);
  1609. }
  1610. /**
  1611. * pcpu_alloc_alloc_info - allocate percpu allocation info
  1612. * @nr_groups: the number of groups
  1613. * @nr_units: the number of units
  1614. *
  1615. * Allocate ai which is large enough for @nr_groups groups containing
  1616. * @nr_units units. The returned ai's groups[0].cpu_map points to the
  1617. * cpu_map array which is long enough for @nr_units and filled with
  1618. * NR_CPUS. It's the caller's responsibility to initialize cpu_map
  1619. * pointer of other groups.
  1620. *
  1621. * RETURNS:
  1622. * Pointer to the allocated pcpu_alloc_info on success, NULL on
  1623. * failure.
  1624. */
  1625. struct pcpu_alloc_info * __init pcpu_alloc_alloc_info(int nr_groups,
  1626. int nr_units)
  1627. {
  1628. struct pcpu_alloc_info *ai;
  1629. size_t base_size, ai_size;
  1630. void *ptr;
  1631. int unit;
  1632. base_size = ALIGN(sizeof(*ai) + nr_groups * sizeof(ai->groups[0]),
  1633. __alignof__(ai->groups[0].cpu_map[0]));
  1634. ai_size = base_size + nr_units * sizeof(ai->groups[0].cpu_map[0]);
  1635. ptr = memblock_virt_alloc_nopanic(PFN_ALIGN(ai_size), 0);
  1636. if (!ptr)
  1637. return NULL;
  1638. ai = ptr;
  1639. ptr += base_size;
  1640. ai->groups[0].cpu_map = ptr;
  1641. for (unit = 0; unit < nr_units; unit++)
  1642. ai->groups[0].cpu_map[unit] = NR_CPUS;
  1643. ai->nr_groups = nr_groups;
  1644. ai->__ai_size = PFN_ALIGN(ai_size);
  1645. return ai;
  1646. }
  1647. /**
  1648. * pcpu_free_alloc_info - free percpu allocation info
  1649. * @ai: pcpu_alloc_info to free
  1650. *
  1651. * Free @ai which was allocated by pcpu_alloc_alloc_info().
  1652. */
  1653. void __init pcpu_free_alloc_info(struct pcpu_alloc_info *ai)
  1654. {
  1655. memblock_free_early(__pa(ai), ai->__ai_size);
  1656. }
  1657. /**
  1658. * pcpu_dump_alloc_info - print out information about pcpu_alloc_info
  1659. * @lvl: loglevel
  1660. * @ai: allocation info to dump
  1661. *
  1662. * Print out information about @ai using loglevel @lvl.
  1663. */
  1664. static void pcpu_dump_alloc_info(const char *lvl,
  1665. const struct pcpu_alloc_info *ai)
  1666. {
  1667. int group_width = 1, cpu_width = 1, width;
  1668. char empty_str[] = "--------";
  1669. int alloc = 0, alloc_end = 0;
  1670. int group, v;
  1671. int upa, apl; /* units per alloc, allocs per line */
  1672. v = ai->nr_groups;
  1673. while (v /= 10)
  1674. group_width++;
  1675. v = num_possible_cpus();
  1676. while (v /= 10)
  1677. cpu_width++;
  1678. empty_str[min_t(int, cpu_width, sizeof(empty_str) - 1)] = '\0';
  1679. upa = ai->alloc_size / ai->unit_size;
  1680. width = upa * (cpu_width + 1) + group_width + 3;
  1681. apl = rounddown_pow_of_two(max(60 / width, 1));
  1682. printk("%spcpu-alloc: s%zu r%zu d%zu u%zu alloc=%zu*%zu",
  1683. lvl, ai->static_size, ai->reserved_size, ai->dyn_size,
  1684. ai->unit_size, ai->alloc_size / ai->atom_size, ai->atom_size);
  1685. for (group = 0; group < ai->nr_groups; group++) {
  1686. const struct pcpu_group_info *gi = &ai->groups[group];
  1687. int unit = 0, unit_end = 0;
  1688. BUG_ON(gi->nr_units % upa);
  1689. for (alloc_end += gi->nr_units / upa;
  1690. alloc < alloc_end; alloc++) {
  1691. if (!(alloc % apl)) {
  1692. pr_cont("\n");
  1693. printk("%spcpu-alloc: ", lvl);
  1694. }
  1695. pr_cont("[%0*d] ", group_width, group);
  1696. for (unit_end += upa; unit < unit_end; unit++)
  1697. if (gi->cpu_map[unit] != NR_CPUS)
  1698. pr_cont("%0*d ",
  1699. cpu_width, gi->cpu_map[unit]);
  1700. else
  1701. pr_cont("%s ", empty_str);
  1702. }
  1703. }
  1704. pr_cont("\n");
  1705. }
  1706. /**
  1707. * pcpu_setup_first_chunk - initialize the first percpu chunk
  1708. * @ai: pcpu_alloc_info describing how to percpu area is shaped
  1709. * @base_addr: mapped address
  1710. *
  1711. * Initialize the first percpu chunk which contains the kernel static
  1712. * perpcu area. This function is to be called from arch percpu area
  1713. * setup path.
  1714. *
  1715. * @ai contains all information necessary to initialize the first
  1716. * chunk and prime the dynamic percpu allocator.
  1717. *
  1718. * @ai->static_size is the size of static percpu area.
  1719. *
  1720. * @ai->reserved_size, if non-zero, specifies the amount of bytes to
  1721. * reserve after the static area in the first chunk. This reserves
  1722. * the first chunk such that it's available only through reserved
  1723. * percpu allocation. This is primarily used to serve module percpu
  1724. * static areas on architectures where the addressing model has
  1725. * limited offset range for symbol relocations to guarantee module
  1726. * percpu symbols fall inside the relocatable range.
  1727. *
  1728. * @ai->dyn_size determines the number of bytes available for dynamic
  1729. * allocation in the first chunk. The area between @ai->static_size +
  1730. * @ai->reserved_size + @ai->dyn_size and @ai->unit_size is unused.
  1731. *
  1732. * @ai->unit_size specifies unit size and must be aligned to PAGE_SIZE
  1733. * and equal to or larger than @ai->static_size + @ai->reserved_size +
  1734. * @ai->dyn_size.
  1735. *
  1736. * @ai->atom_size is the allocation atom size and used as alignment
  1737. * for vm areas.
  1738. *
  1739. * @ai->alloc_size is the allocation size and always multiple of
  1740. * @ai->atom_size. This is larger than @ai->atom_size if
  1741. * @ai->unit_size is larger than @ai->atom_size.
  1742. *
  1743. * @ai->nr_groups and @ai->groups describe virtual memory layout of
  1744. * percpu areas. Units which should be colocated are put into the
  1745. * same group. Dynamic VM areas will be allocated according to these
  1746. * groupings. If @ai->nr_groups is zero, a single group containing
  1747. * all units is assumed.
  1748. *
  1749. * The caller should have mapped the first chunk at @base_addr and
  1750. * copied static data to each unit.
  1751. *
  1752. * The first chunk will always contain a static and a dynamic region.
  1753. * However, the static region is not managed by any chunk. If the first
  1754. * chunk also contains a reserved region, it is served by two chunks -
  1755. * one for the reserved region and one for the dynamic region. They
  1756. * share the same vm, but use offset regions in the area allocation map.
  1757. * The chunk serving the dynamic region is circulated in the chunk slots
  1758. * and available for dynamic allocation like any other chunk.
  1759. *
  1760. * RETURNS:
  1761. * 0 on success, -errno on failure.
  1762. */
  1763. int __init pcpu_setup_first_chunk(const struct pcpu_alloc_info *ai,
  1764. void *base_addr)
  1765. {
  1766. size_t size_sum = ai->static_size + ai->reserved_size + ai->dyn_size;
  1767. size_t static_size, dyn_size;
  1768. struct pcpu_chunk *chunk;
  1769. unsigned long *group_offsets;
  1770. size_t *group_sizes;
  1771. unsigned long *unit_off;
  1772. unsigned int cpu;
  1773. int *unit_map;
  1774. int group, unit, i;
  1775. int map_size;
  1776. unsigned long tmp_addr;
  1777. #define PCPU_SETUP_BUG_ON(cond) do { \
  1778. if (unlikely(cond)) { \
  1779. pr_emerg("failed to initialize, %s\n", #cond); \
  1780. pr_emerg("cpu_possible_mask=%*pb\n", \
  1781. cpumask_pr_args(cpu_possible_mask)); \
  1782. pcpu_dump_alloc_info(KERN_EMERG, ai); \
  1783. BUG(); \
  1784. } \
  1785. } while (0)
  1786. /* sanity checks */
  1787. PCPU_SETUP_BUG_ON(ai->nr_groups <= 0);
  1788. #ifdef CONFIG_SMP
  1789. PCPU_SETUP_BUG_ON(!ai->static_size);
  1790. PCPU_SETUP_BUG_ON(offset_in_page(__per_cpu_start));
  1791. #endif
  1792. PCPU_SETUP_BUG_ON(!base_addr);
  1793. PCPU_SETUP_BUG_ON(offset_in_page(base_addr));
  1794. PCPU_SETUP_BUG_ON(ai->unit_size < size_sum);
  1795. PCPU_SETUP_BUG_ON(offset_in_page(ai->unit_size));
  1796. PCPU_SETUP_BUG_ON(ai->unit_size < PCPU_MIN_UNIT_SIZE);
  1797. PCPU_SETUP_BUG_ON(!IS_ALIGNED(ai->unit_size, PCPU_BITMAP_BLOCK_SIZE));
  1798. PCPU_SETUP_BUG_ON(ai->dyn_size < PERCPU_DYNAMIC_EARLY_SIZE);
  1799. PCPU_SETUP_BUG_ON(!ai->dyn_size);
  1800. PCPU_SETUP_BUG_ON(!IS_ALIGNED(ai->reserved_size, PCPU_MIN_ALLOC_SIZE));
  1801. PCPU_SETUP_BUG_ON(!(IS_ALIGNED(PCPU_BITMAP_BLOCK_SIZE, PAGE_SIZE) ||
  1802. IS_ALIGNED(PAGE_SIZE, PCPU_BITMAP_BLOCK_SIZE)));
  1803. PCPU_SETUP_BUG_ON(pcpu_verify_alloc_info(ai) < 0);
  1804. /* process group information and build config tables accordingly */
  1805. group_offsets = memblock_virt_alloc(ai->nr_groups *
  1806. sizeof(group_offsets[0]), 0);
  1807. group_sizes = memblock_virt_alloc(ai->nr_groups *
  1808. sizeof(group_sizes[0]), 0);
  1809. unit_map = memblock_virt_alloc(nr_cpu_ids * sizeof(unit_map[0]), 0);
  1810. unit_off = memblock_virt_alloc(nr_cpu_ids * sizeof(unit_off[0]), 0);
  1811. for (cpu = 0; cpu < nr_cpu_ids; cpu++)
  1812. unit_map[cpu] = UINT_MAX;
  1813. pcpu_low_unit_cpu = NR_CPUS;
  1814. pcpu_high_unit_cpu = NR_CPUS;
  1815. for (group = 0, unit = 0; group < ai->nr_groups; group++, unit += i) {
  1816. const struct pcpu_group_info *gi = &ai->groups[group];
  1817. group_offsets[group] = gi->base_offset;
  1818. group_sizes[group] = gi->nr_units * ai->unit_size;
  1819. for (i = 0; i < gi->nr_units; i++) {
  1820. cpu = gi->cpu_map[i];
  1821. if (cpu == NR_CPUS)
  1822. continue;
  1823. PCPU_SETUP_BUG_ON(cpu >= nr_cpu_ids);
  1824. PCPU_SETUP_BUG_ON(!cpu_possible(cpu));
  1825. PCPU_SETUP_BUG_ON(unit_map[cpu] != UINT_MAX);
  1826. unit_map[cpu] = unit + i;
  1827. unit_off[cpu] = gi->base_offset + i * ai->unit_size;
  1828. /* determine low/high unit_cpu */
  1829. if (pcpu_low_unit_cpu == NR_CPUS ||
  1830. unit_off[cpu] < unit_off[pcpu_low_unit_cpu])
  1831. pcpu_low_unit_cpu = cpu;
  1832. if (pcpu_high_unit_cpu == NR_CPUS ||
  1833. unit_off[cpu] > unit_off[pcpu_high_unit_cpu])
  1834. pcpu_high_unit_cpu = cpu;
  1835. }
  1836. }
  1837. pcpu_nr_units = unit;
  1838. for_each_possible_cpu(cpu)
  1839. PCPU_SETUP_BUG_ON(unit_map[cpu] == UINT_MAX);
  1840. /* we're done parsing the input, undefine BUG macro and dump config */
  1841. #undef PCPU_SETUP_BUG_ON
  1842. pcpu_dump_alloc_info(KERN_DEBUG, ai);
  1843. pcpu_nr_groups = ai->nr_groups;
  1844. pcpu_group_offsets = group_offsets;
  1845. pcpu_group_sizes = group_sizes;
  1846. pcpu_unit_map = unit_map;
  1847. pcpu_unit_offsets = unit_off;
  1848. /* determine basic parameters */
  1849. pcpu_unit_pages = ai->unit_size >> PAGE_SHIFT;
  1850. pcpu_unit_size = pcpu_unit_pages << PAGE_SHIFT;
  1851. pcpu_atom_size = ai->atom_size;
  1852. pcpu_chunk_struct_size = sizeof(struct pcpu_chunk) +
  1853. BITS_TO_LONGS(pcpu_unit_pages) * sizeof(unsigned long);
  1854. pcpu_stats_save_ai(ai);
  1855. /*
  1856. * Allocate chunk slots. The additional last slot is for
  1857. * empty chunks.
  1858. */
  1859. pcpu_nr_slots = __pcpu_size_to_slot(pcpu_unit_size) + 2;
  1860. pcpu_slot = memblock_virt_alloc(
  1861. pcpu_nr_slots * sizeof(pcpu_slot[0]), 0);
  1862. for (i = 0; i < pcpu_nr_slots; i++)
  1863. INIT_LIST_HEAD(&pcpu_slot[i]);
  1864. /*
  1865. * The end of the static region needs to be aligned with the
  1866. * minimum allocation size as this offsets the reserved and
  1867. * dynamic region. The first chunk ends page aligned by
  1868. * expanding the dynamic region, therefore the dynamic region
  1869. * can be shrunk to compensate while still staying above the
  1870. * configured sizes.
  1871. */
  1872. static_size = ALIGN(ai->static_size, PCPU_MIN_ALLOC_SIZE);
  1873. dyn_size = ai->dyn_size - (static_size - ai->static_size);
  1874. /*
  1875. * Initialize first chunk.
  1876. * If the reserved_size is non-zero, this initializes the reserved
  1877. * chunk. If the reserved_size is zero, the reserved chunk is NULL
  1878. * and the dynamic region is initialized here. The first chunk,
  1879. * pcpu_first_chunk, will always point to the chunk that serves
  1880. * the dynamic region.
  1881. */
  1882. tmp_addr = (unsigned long)base_addr + static_size;
  1883. map_size = ai->reserved_size ?: dyn_size;
  1884. chunk = pcpu_alloc_first_chunk(tmp_addr, map_size);
  1885. /* init dynamic chunk if necessary */
  1886. if (ai->reserved_size) {
  1887. pcpu_reserved_chunk = chunk;
  1888. tmp_addr = (unsigned long)base_addr + static_size +
  1889. ai->reserved_size;
  1890. map_size = dyn_size;
  1891. chunk = pcpu_alloc_first_chunk(tmp_addr, map_size);
  1892. }
  1893. /* link the first chunk in */
  1894. pcpu_first_chunk = chunk;
  1895. pcpu_nr_empty_pop_pages = pcpu_first_chunk->nr_empty_pop_pages;
  1896. pcpu_chunk_relocate(pcpu_first_chunk, -1);
  1897. pcpu_stats_chunk_alloc();
  1898. trace_percpu_create_chunk(base_addr);
  1899. /* we're done */
  1900. pcpu_base_addr = base_addr;
  1901. return 0;
  1902. }
  1903. #ifdef CONFIG_SMP
  1904. const char * const pcpu_fc_names[PCPU_FC_NR] __initconst = {
  1905. [PCPU_FC_AUTO] = "auto",
  1906. [PCPU_FC_EMBED] = "embed",
  1907. [PCPU_FC_PAGE] = "page",
  1908. };
  1909. enum pcpu_fc pcpu_chosen_fc __initdata = PCPU_FC_AUTO;
  1910. static int __init percpu_alloc_setup(char *str)
  1911. {
  1912. if (!str)
  1913. return -EINVAL;
  1914. if (0)
  1915. /* nada */;
  1916. #ifdef CONFIG_NEED_PER_CPU_EMBED_FIRST_CHUNK
  1917. else if (!strcmp(str, "embed"))
  1918. pcpu_chosen_fc = PCPU_FC_EMBED;
  1919. #endif
  1920. #ifdef CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK
  1921. else if (!strcmp(str, "page"))
  1922. pcpu_chosen_fc = PCPU_FC_PAGE;
  1923. #endif
  1924. else
  1925. pr_warn("unknown allocator %s specified\n", str);
  1926. return 0;
  1927. }
  1928. early_param("percpu_alloc", percpu_alloc_setup);
  1929. /*
  1930. * pcpu_embed_first_chunk() is used by the generic percpu setup.
  1931. * Build it if needed by the arch config or the generic setup is going
  1932. * to be used.
  1933. */
  1934. #if defined(CONFIG_NEED_PER_CPU_EMBED_FIRST_CHUNK) || \
  1935. !defined(CONFIG_HAVE_SETUP_PER_CPU_AREA)
  1936. #define BUILD_EMBED_FIRST_CHUNK
  1937. #endif
  1938. /* build pcpu_page_first_chunk() iff needed by the arch config */
  1939. #if defined(CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK)
  1940. #define BUILD_PAGE_FIRST_CHUNK
  1941. #endif
  1942. /* pcpu_build_alloc_info() is used by both embed and page first chunk */
  1943. #if defined(BUILD_EMBED_FIRST_CHUNK) || defined(BUILD_PAGE_FIRST_CHUNK)
  1944. /**
  1945. * pcpu_build_alloc_info - build alloc_info considering distances between CPUs
  1946. * @reserved_size: the size of reserved percpu area in bytes
  1947. * @dyn_size: minimum free size for dynamic allocation in bytes
  1948. * @atom_size: allocation atom size
  1949. * @cpu_distance_fn: callback to determine distance between cpus, optional
  1950. *
  1951. * This function determines grouping of units, their mappings to cpus
  1952. * and other parameters considering needed percpu size, allocation
  1953. * atom size and distances between CPUs.
  1954. *
  1955. * Groups are always multiples of atom size and CPUs which are of
  1956. * LOCAL_DISTANCE both ways are grouped together and share space for
  1957. * units in the same group. The returned configuration is guaranteed
  1958. * to have CPUs on different nodes on different groups and >=75% usage
  1959. * of allocated virtual address space.
  1960. *
  1961. * RETURNS:
  1962. * On success, pointer to the new allocation_info is returned. On
  1963. * failure, ERR_PTR value is returned.
  1964. */
  1965. static struct pcpu_alloc_info * __init pcpu_build_alloc_info(
  1966. size_t reserved_size, size_t dyn_size,
  1967. size_t atom_size,
  1968. pcpu_fc_cpu_distance_fn_t cpu_distance_fn)
  1969. {
  1970. static int group_map[NR_CPUS] __initdata;
  1971. static int group_cnt[NR_CPUS] __initdata;
  1972. const size_t static_size = __per_cpu_end - __per_cpu_start;
  1973. int nr_groups = 1, nr_units = 0;
  1974. size_t size_sum, min_unit_size, alloc_size;
  1975. int upa, max_upa, uninitialized_var(best_upa); /* units_per_alloc */
  1976. int last_allocs, group, unit;
  1977. unsigned int cpu, tcpu;
  1978. struct pcpu_alloc_info *ai;
  1979. unsigned int *cpu_map;
  1980. /* this function may be called multiple times */
  1981. memset(group_map, 0, sizeof(group_map));
  1982. memset(group_cnt, 0, sizeof(group_cnt));
  1983. /* calculate size_sum and ensure dyn_size is enough for early alloc */
  1984. size_sum = PFN_ALIGN(static_size + reserved_size +
  1985. max_t(size_t, dyn_size, PERCPU_DYNAMIC_EARLY_SIZE));
  1986. dyn_size = size_sum - static_size - reserved_size;
  1987. /*
  1988. * Determine min_unit_size, alloc_size and max_upa such that
  1989. * alloc_size is multiple of atom_size and is the smallest
  1990. * which can accommodate 4k aligned segments which are equal to
  1991. * or larger than min_unit_size.
  1992. */
  1993. min_unit_size = max_t(size_t, size_sum, PCPU_MIN_UNIT_SIZE);
  1994. /* determine the maximum # of units that can fit in an allocation */
  1995. alloc_size = roundup(min_unit_size, atom_size);
  1996. upa = alloc_size / min_unit_size;
  1997. while (alloc_size % upa || (offset_in_page(alloc_size / upa)))
  1998. upa--;
  1999. max_upa = upa;
  2000. /* group cpus according to their proximity */
  2001. for_each_possible_cpu(cpu) {
  2002. group = 0;
  2003. next_group:
  2004. for_each_possible_cpu(tcpu) {
  2005. if (cpu == tcpu)
  2006. break;
  2007. if (group_map[tcpu] == group && cpu_distance_fn &&
  2008. (cpu_distance_fn(cpu, tcpu) > LOCAL_DISTANCE ||
  2009. cpu_distance_fn(tcpu, cpu) > LOCAL_DISTANCE)) {
  2010. group++;
  2011. nr_groups = max(nr_groups, group + 1);
  2012. goto next_group;
  2013. }
  2014. }
  2015. group_map[cpu] = group;
  2016. group_cnt[group]++;
  2017. }
  2018. /*
  2019. * Wasted space is caused by a ratio imbalance of upa to group_cnt.
  2020. * Expand the unit_size until we use >= 75% of the units allocated.
  2021. * Related to atom_size, which could be much larger than the unit_size.
  2022. */
  2023. last_allocs = INT_MAX;
  2024. for (upa = max_upa; upa; upa--) {
  2025. int allocs = 0, wasted = 0;
  2026. if (alloc_size % upa || (offset_in_page(alloc_size / upa)))
  2027. continue;
  2028. for (group = 0; group < nr_groups; group++) {
  2029. int this_allocs = DIV_ROUND_UP(group_cnt[group], upa);
  2030. allocs += this_allocs;
  2031. wasted += this_allocs * upa - group_cnt[group];
  2032. }
  2033. /*
  2034. * Don't accept if wastage is over 1/3. The
  2035. * greater-than comparison ensures upa==1 always
  2036. * passes the following check.
  2037. */
  2038. if (wasted > num_possible_cpus() / 3)
  2039. continue;
  2040. /* and then don't consume more memory */
  2041. if (allocs > last_allocs)
  2042. break;
  2043. last_allocs = allocs;
  2044. best_upa = upa;
  2045. }
  2046. upa = best_upa;
  2047. /* allocate and fill alloc_info */
  2048. for (group = 0; group < nr_groups; group++)
  2049. nr_units += roundup(group_cnt[group], upa);
  2050. ai = pcpu_alloc_alloc_info(nr_groups, nr_units);
  2051. if (!ai)
  2052. return ERR_PTR(-ENOMEM);
  2053. cpu_map = ai->groups[0].cpu_map;
  2054. for (group = 0; group < nr_groups; group++) {
  2055. ai->groups[group].cpu_map = cpu_map;
  2056. cpu_map += roundup(group_cnt[group], upa);
  2057. }
  2058. ai->static_size = static_size;
  2059. ai->reserved_size = reserved_size;
  2060. ai->dyn_size = dyn_size;
  2061. ai->unit_size = alloc_size / upa;
  2062. ai->atom_size = atom_size;
  2063. ai->alloc_size = alloc_size;
  2064. for (group = 0, unit = 0; group_cnt[group]; group++) {
  2065. struct pcpu_group_info *gi = &ai->groups[group];
  2066. /*
  2067. * Initialize base_offset as if all groups are located
  2068. * back-to-back. The caller should update this to
  2069. * reflect actual allocation.
  2070. */
  2071. gi->base_offset = unit * ai->unit_size;
  2072. for_each_possible_cpu(cpu)
  2073. if (group_map[cpu] == group)
  2074. gi->cpu_map[gi->nr_units++] = cpu;
  2075. gi->nr_units = roundup(gi->nr_units, upa);
  2076. unit += gi->nr_units;
  2077. }
  2078. BUG_ON(unit != nr_units);
  2079. return ai;
  2080. }
  2081. #endif /* BUILD_EMBED_FIRST_CHUNK || BUILD_PAGE_FIRST_CHUNK */
  2082. #if defined(BUILD_EMBED_FIRST_CHUNK)
  2083. /**
  2084. * pcpu_embed_first_chunk - embed the first percpu chunk into bootmem
  2085. * @reserved_size: the size of reserved percpu area in bytes
  2086. * @dyn_size: minimum free size for dynamic allocation in bytes
  2087. * @atom_size: allocation atom size
  2088. * @cpu_distance_fn: callback to determine distance between cpus, optional
  2089. * @alloc_fn: function to allocate percpu page
  2090. * @free_fn: function to free percpu page
  2091. *
  2092. * This is a helper to ease setting up embedded first percpu chunk and
  2093. * can be called where pcpu_setup_first_chunk() is expected.
  2094. *
  2095. * If this function is used to setup the first chunk, it is allocated
  2096. * by calling @alloc_fn and used as-is without being mapped into
  2097. * vmalloc area. Allocations are always whole multiples of @atom_size
  2098. * aligned to @atom_size.
  2099. *
  2100. * This enables the first chunk to piggy back on the linear physical
  2101. * mapping which often uses larger page size. Please note that this
  2102. * can result in very sparse cpu->unit mapping on NUMA machines thus
  2103. * requiring large vmalloc address space. Don't use this allocator if
  2104. * vmalloc space is not orders of magnitude larger than distances
  2105. * between node memory addresses (ie. 32bit NUMA machines).
  2106. *
  2107. * @dyn_size specifies the minimum dynamic area size.
  2108. *
  2109. * If the needed size is smaller than the minimum or specified unit
  2110. * size, the leftover is returned using @free_fn.
  2111. *
  2112. * RETURNS:
  2113. * 0 on success, -errno on failure.
  2114. */
  2115. int __init pcpu_embed_first_chunk(size_t reserved_size, size_t dyn_size,
  2116. size_t atom_size,
  2117. pcpu_fc_cpu_distance_fn_t cpu_distance_fn,
  2118. pcpu_fc_alloc_fn_t alloc_fn,
  2119. pcpu_fc_free_fn_t free_fn)
  2120. {
  2121. void *base = (void *)ULONG_MAX;
  2122. void **areas = NULL;
  2123. struct pcpu_alloc_info *ai;
  2124. size_t size_sum, areas_size;
  2125. unsigned long max_distance;
  2126. int group, i, highest_group, rc;
  2127. ai = pcpu_build_alloc_info(reserved_size, dyn_size, atom_size,
  2128. cpu_distance_fn);
  2129. if (IS_ERR(ai))
  2130. return PTR_ERR(ai);
  2131. size_sum = ai->static_size + ai->reserved_size + ai->dyn_size;
  2132. areas_size = PFN_ALIGN(ai->nr_groups * sizeof(void *));
  2133. areas = memblock_virt_alloc_nopanic(areas_size, 0);
  2134. if (!areas) {
  2135. rc = -ENOMEM;
  2136. goto out_free;
  2137. }
  2138. /* allocate, copy and determine base address & max_distance */
  2139. highest_group = 0;
  2140. for (group = 0; group < ai->nr_groups; group++) {
  2141. struct pcpu_group_info *gi = &ai->groups[group];
  2142. unsigned int cpu = NR_CPUS;
  2143. void *ptr;
  2144. for (i = 0; i < gi->nr_units && cpu == NR_CPUS; i++)
  2145. cpu = gi->cpu_map[i];
  2146. BUG_ON(cpu == NR_CPUS);
  2147. /* allocate space for the whole group */
  2148. ptr = alloc_fn(cpu, gi->nr_units * ai->unit_size, atom_size);
  2149. if (!ptr) {
  2150. rc = -ENOMEM;
  2151. goto out_free_areas;
  2152. }
  2153. /* kmemleak tracks the percpu allocations separately */
  2154. kmemleak_free(ptr);
  2155. areas[group] = ptr;
  2156. base = min(ptr, base);
  2157. if (ptr > areas[highest_group])
  2158. highest_group = group;
  2159. }
  2160. max_distance = areas[highest_group] - base;
  2161. max_distance += ai->unit_size * ai->groups[highest_group].nr_units;
  2162. /* warn if maximum distance is further than 75% of vmalloc space */
  2163. if (max_distance > VMALLOC_TOTAL * 3 / 4) {
  2164. pr_warn("max_distance=0x%lx too large for vmalloc space 0x%lx\n",
  2165. max_distance, VMALLOC_TOTAL);
  2166. #ifdef CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK
  2167. /* and fail if we have fallback */
  2168. rc = -EINVAL;
  2169. goto out_free_areas;
  2170. #endif
  2171. }
  2172. /*
  2173. * Copy data and free unused parts. This should happen after all
  2174. * allocations are complete; otherwise, we may end up with
  2175. * overlapping groups.
  2176. */
  2177. for (group = 0; group < ai->nr_groups; group++) {
  2178. struct pcpu_group_info *gi = &ai->groups[group];
  2179. void *ptr = areas[group];
  2180. for (i = 0; i < gi->nr_units; i++, ptr += ai->unit_size) {
  2181. if (gi->cpu_map[i] == NR_CPUS) {
  2182. /* unused unit, free whole */
  2183. free_fn(ptr, ai->unit_size);
  2184. continue;
  2185. }
  2186. /* copy and return the unused part */
  2187. memcpy(ptr, __per_cpu_load, ai->static_size);
  2188. free_fn(ptr + size_sum, ai->unit_size - size_sum);
  2189. }
  2190. }
  2191. /* base address is now known, determine group base offsets */
  2192. for (group = 0; group < ai->nr_groups; group++) {
  2193. ai->groups[group].base_offset = areas[group] - base;
  2194. }
  2195. pr_info("Embedded %zu pages/cpu s%zu r%zu d%zu u%zu\n",
  2196. PFN_DOWN(size_sum), ai->static_size, ai->reserved_size,
  2197. ai->dyn_size, ai->unit_size);
  2198. rc = pcpu_setup_first_chunk(ai, base);
  2199. goto out_free;
  2200. out_free_areas:
  2201. for (group = 0; group < ai->nr_groups; group++)
  2202. if (areas[group])
  2203. free_fn(areas[group],
  2204. ai->groups[group].nr_units * ai->unit_size);
  2205. out_free:
  2206. pcpu_free_alloc_info(ai);
  2207. if (areas)
  2208. memblock_free_early(__pa(areas), areas_size);
  2209. return rc;
  2210. }
  2211. #endif /* BUILD_EMBED_FIRST_CHUNK */
  2212. #ifdef BUILD_PAGE_FIRST_CHUNK
  2213. /**
  2214. * pcpu_page_first_chunk - map the first chunk using PAGE_SIZE pages
  2215. * @reserved_size: the size of reserved percpu area in bytes
  2216. * @alloc_fn: function to allocate percpu page, always called with PAGE_SIZE
  2217. * @free_fn: function to free percpu page, always called with PAGE_SIZE
  2218. * @populate_pte_fn: function to populate pte
  2219. *
  2220. * This is a helper to ease setting up page-remapped first percpu
  2221. * chunk and can be called where pcpu_setup_first_chunk() is expected.
  2222. *
  2223. * This is the basic allocator. Static percpu area is allocated
  2224. * page-by-page into vmalloc area.
  2225. *
  2226. * RETURNS:
  2227. * 0 on success, -errno on failure.
  2228. */
  2229. int __init pcpu_page_first_chunk(size_t reserved_size,
  2230. pcpu_fc_alloc_fn_t alloc_fn,
  2231. pcpu_fc_free_fn_t free_fn,
  2232. pcpu_fc_populate_pte_fn_t populate_pte_fn)
  2233. {
  2234. static struct vm_struct vm;
  2235. struct pcpu_alloc_info *ai;
  2236. char psize_str[16];
  2237. int unit_pages;
  2238. size_t pages_size;
  2239. struct page **pages;
  2240. int unit, i, j, rc;
  2241. int upa;
  2242. int nr_g0_units;
  2243. snprintf(psize_str, sizeof(psize_str), "%luK", PAGE_SIZE >> 10);
  2244. ai = pcpu_build_alloc_info(reserved_size, 0, PAGE_SIZE, NULL);
  2245. if (IS_ERR(ai))
  2246. return PTR_ERR(ai);
  2247. BUG_ON(ai->nr_groups != 1);
  2248. upa = ai->alloc_size/ai->unit_size;
  2249. nr_g0_units = roundup(num_possible_cpus(), upa);
  2250. if (unlikely(WARN_ON(ai->groups[0].nr_units != nr_g0_units))) {
  2251. pcpu_free_alloc_info(ai);
  2252. return -EINVAL;
  2253. }
  2254. unit_pages = ai->unit_size >> PAGE_SHIFT;
  2255. /* unaligned allocations can't be freed, round up to page size */
  2256. pages_size = PFN_ALIGN(unit_pages * num_possible_cpus() *
  2257. sizeof(pages[0]));
  2258. pages = memblock_virt_alloc(pages_size, 0);
  2259. /* allocate pages */
  2260. j = 0;
  2261. for (unit = 0; unit < num_possible_cpus(); unit++) {
  2262. unsigned int cpu = ai->groups[0].cpu_map[unit];
  2263. for (i = 0; i < unit_pages; i++) {
  2264. void *ptr;
  2265. ptr = alloc_fn(cpu, PAGE_SIZE, PAGE_SIZE);
  2266. if (!ptr) {
  2267. pr_warn("failed to allocate %s page for cpu%u\n",
  2268. psize_str, cpu);
  2269. goto enomem;
  2270. }
  2271. /* kmemleak tracks the percpu allocations separately */
  2272. kmemleak_free(ptr);
  2273. pages[j++] = virt_to_page(ptr);
  2274. }
  2275. }
  2276. /* allocate vm area, map the pages and copy static data */
  2277. vm.flags = VM_ALLOC;
  2278. vm.size = num_possible_cpus() * ai->unit_size;
  2279. vm_area_register_early(&vm, PAGE_SIZE);
  2280. for (unit = 0; unit < num_possible_cpus(); unit++) {
  2281. unsigned long unit_addr =
  2282. (unsigned long)vm.addr + unit * ai->unit_size;
  2283. for (i = 0; i < unit_pages; i++)
  2284. populate_pte_fn(unit_addr + (i << PAGE_SHIFT));
  2285. /* pte already populated, the following shouldn't fail */
  2286. rc = __pcpu_map_pages(unit_addr, &pages[unit * unit_pages],
  2287. unit_pages);
  2288. if (rc < 0)
  2289. panic("failed to map percpu area, err=%d\n", rc);
  2290. /*
  2291. * FIXME: Archs with virtual cache should flush local
  2292. * cache for the linear mapping here - something
  2293. * equivalent to flush_cache_vmap() on the local cpu.
  2294. * flush_cache_vmap() can't be used as most supporting
  2295. * data structures are not set up yet.
  2296. */
  2297. /* copy static data */
  2298. memcpy((void *)unit_addr, __per_cpu_load, ai->static_size);
  2299. }
  2300. /* we're ready, commit */
  2301. pr_info("%d %s pages/cpu s%zu r%zu d%zu\n",
  2302. unit_pages, psize_str, ai->static_size,
  2303. ai->reserved_size, ai->dyn_size);
  2304. rc = pcpu_setup_first_chunk(ai, vm.addr);
  2305. goto out_free_ar;
  2306. enomem:
  2307. while (--j >= 0)
  2308. free_fn(page_address(pages[j]), PAGE_SIZE);
  2309. rc = -ENOMEM;
  2310. out_free_ar:
  2311. memblock_free_early(__pa(pages), pages_size);
  2312. pcpu_free_alloc_info(ai);
  2313. return rc;
  2314. }
  2315. #endif /* BUILD_PAGE_FIRST_CHUNK */
  2316. #ifndef CONFIG_HAVE_SETUP_PER_CPU_AREA
  2317. /*
  2318. * Generic SMP percpu area setup.
  2319. *
  2320. * The embedding helper is used because its behavior closely resembles
  2321. * the original non-dynamic generic percpu area setup. This is
  2322. * important because many archs have addressing restrictions and might
  2323. * fail if the percpu area is located far away from the previous
  2324. * location. As an added bonus, in non-NUMA cases, embedding is
  2325. * generally a good idea TLB-wise because percpu area can piggy back
  2326. * on the physical linear memory mapping which uses large page
  2327. * mappings on applicable archs.
  2328. */
  2329. unsigned long __per_cpu_offset[NR_CPUS] __read_mostly;
  2330. EXPORT_SYMBOL(__per_cpu_offset);
  2331. static void * __init pcpu_dfl_fc_alloc(unsigned int cpu, size_t size,
  2332. size_t align)
  2333. {
  2334. return memblock_virt_alloc_from_nopanic(
  2335. size, align, __pa(MAX_DMA_ADDRESS));
  2336. }
  2337. static void __init pcpu_dfl_fc_free(void *ptr, size_t size)
  2338. {
  2339. memblock_free_early(__pa(ptr), size);
  2340. }
  2341. void __init setup_per_cpu_areas(void)
  2342. {
  2343. unsigned long delta;
  2344. unsigned int cpu;
  2345. int rc;
  2346. /*
  2347. * Always reserve area for module percpu variables. That's
  2348. * what the legacy allocator did.
  2349. */
  2350. rc = pcpu_embed_first_chunk(PERCPU_MODULE_RESERVE,
  2351. PERCPU_DYNAMIC_RESERVE, PAGE_SIZE, NULL,
  2352. pcpu_dfl_fc_alloc, pcpu_dfl_fc_free);
  2353. if (rc < 0)
  2354. panic("Failed to initialize percpu areas.");
  2355. delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
  2356. for_each_possible_cpu(cpu)
  2357. __per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
  2358. }
  2359. #endif /* CONFIG_HAVE_SETUP_PER_CPU_AREA */
  2360. #else /* CONFIG_SMP */
  2361. /*
  2362. * UP percpu area setup.
  2363. *
  2364. * UP always uses km-based percpu allocator with identity mapping.
  2365. * Static percpu variables are indistinguishable from the usual static
  2366. * variables and don't require any special preparation.
  2367. */
  2368. void __init setup_per_cpu_areas(void)
  2369. {
  2370. const size_t unit_size =
  2371. roundup_pow_of_two(max_t(size_t, PCPU_MIN_UNIT_SIZE,
  2372. PERCPU_DYNAMIC_RESERVE));
  2373. struct pcpu_alloc_info *ai;
  2374. void *fc;
  2375. ai = pcpu_alloc_alloc_info(1, 1);
  2376. fc = memblock_virt_alloc_from_nopanic(unit_size,
  2377. PAGE_SIZE,
  2378. __pa(MAX_DMA_ADDRESS));
  2379. if (!ai || !fc)
  2380. panic("Failed to allocate memory for percpu areas.");
  2381. /* kmemleak tracks the percpu allocations separately */
  2382. kmemleak_free(fc);
  2383. ai->dyn_size = unit_size;
  2384. ai->unit_size = unit_size;
  2385. ai->atom_size = unit_size;
  2386. ai->alloc_size = unit_size;
  2387. ai->groups[0].nr_units = 1;
  2388. ai->groups[0].cpu_map[0] = 0;
  2389. if (pcpu_setup_first_chunk(ai, fc) < 0)
  2390. panic("Failed to initialize percpu areas.");
  2391. }
  2392. #endif /* CONFIG_SMP */
  2393. /*
  2394. * Percpu allocator is initialized early during boot when neither slab or
  2395. * workqueue is available. Plug async management until everything is up
  2396. * and running.
  2397. */
  2398. static int __init percpu_enable_async(void)
  2399. {
  2400. pcpu_async_enabled = true;
  2401. return 0;
  2402. }
  2403. subsys_initcall(percpu_enable_async);