percpu.c 69 KB

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