percpu.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  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.
  8. *
  9. * This is percpu allocator which can handle both static and dynamic
  10. * areas. Percpu areas are allocated in chunks. Each chunk is
  11. * consisted of boot-time determined number of units and the first
  12. * chunk is used for static percpu variables in the kernel image
  13. * (special boot time alloc/init handling necessary as these areas
  14. * need to be brought up before allocation services are running).
  15. * Unit grows as necessary and all units grow or shrink in unison.
  16. * When a chunk is filled up, another chunk is allocated.
  17. *
  18. * c0 c1 c2
  19. * ------------------- ------------------- ------------
  20. * | u0 | u1 | u2 | u3 | | u0 | u1 | u2 | u3 | | u0 | u1 | u
  21. * ------------------- ...... ------------------- .... ------------
  22. *
  23. * Allocation is done in offset-size areas of single unit space. Ie,
  24. * an area of 512 bytes at 6k in c1 occupies 512 bytes at 6k of c1:u0,
  25. * c1:u1, c1:u2 and c1:u3. On UMA, units corresponds directly to
  26. * cpus. On NUMA, the mapping can be non-linear and even sparse.
  27. * Percpu access can be done by configuring percpu base registers
  28. * according to cpu to unit mapping and pcpu_unit_size.
  29. *
  30. * There are usually many small percpu allocations many of them being
  31. * as small as 4 bytes. The allocator organizes chunks into lists
  32. * according to free size and tries to allocate from the fullest one.
  33. * Each chunk keeps the maximum contiguous area size hint which is
  34. * guaranteed to be equal to or larger than the maximum contiguous
  35. * area in the chunk. This helps the allocator not to iterate the
  36. * chunk maps unnecessarily.
  37. *
  38. * Allocation state in each chunk is kept using an array of integers
  39. * on chunk->map. A positive value in the map represents a free
  40. * region and negative allocated. Allocation inside a chunk is done
  41. * by scanning this map sequentially and serving the first matching
  42. * entry. This is mostly copied from the percpu_modalloc() allocator.
  43. * Chunks can be determined from the address using the index field
  44. * in the page struct. The index field contains a pointer to the chunk.
  45. *
  46. * To use this allocator, arch code should do the followings.
  47. *
  48. * - define __addr_to_pcpu_ptr() and __pcpu_ptr_to_addr() to translate
  49. * regular address to percpu pointer and back if they need to be
  50. * different from the default
  51. *
  52. * - use pcpu_setup_first_chunk() during percpu area initialization to
  53. * setup the first chunk containing the kernel static percpu area
  54. */
  55. #include <linux/bitmap.h>
  56. #include <linux/bootmem.h>
  57. #include <linux/err.h>
  58. #include <linux/list.h>
  59. #include <linux/log2.h>
  60. #include <linux/mm.h>
  61. #include <linux/module.h>
  62. #include <linux/mutex.h>
  63. #include <linux/percpu.h>
  64. #include <linux/pfn.h>
  65. #include <linux/slab.h>
  66. #include <linux/spinlock.h>
  67. #include <linux/vmalloc.h>
  68. #include <linux/workqueue.h>
  69. #include <asm/cacheflush.h>
  70. #include <asm/sections.h>
  71. #include <asm/tlbflush.h>
  72. #include <asm/io.h>
  73. #define PCPU_SLOT_BASE_SHIFT 5 /* 1-31 shares the same slot */
  74. #define PCPU_DFL_MAP_ALLOC 16 /* start a map with 16 ents */
  75. #ifdef CONFIG_SMP
  76. /* default addr <-> pcpu_ptr mapping, override in asm/percpu.h if necessary */
  77. #ifndef __addr_to_pcpu_ptr
  78. #define __addr_to_pcpu_ptr(addr) \
  79. (void __percpu *)((unsigned long)(addr) - \
  80. (unsigned long)pcpu_base_addr + \
  81. (unsigned long)__per_cpu_start)
  82. #endif
  83. #ifndef __pcpu_ptr_to_addr
  84. #define __pcpu_ptr_to_addr(ptr) \
  85. (void __force *)((unsigned long)(ptr) + \
  86. (unsigned long)pcpu_base_addr - \
  87. (unsigned long)__per_cpu_start)
  88. #endif
  89. #else /* CONFIG_SMP */
  90. /* on UP, it's always identity mapped */
  91. #define __addr_to_pcpu_ptr(addr) (void __percpu *)(addr)
  92. #define __pcpu_ptr_to_addr(ptr) (void __force *)(ptr)
  93. #endif /* CONFIG_SMP */
  94. struct pcpu_chunk {
  95. struct list_head list; /* linked to pcpu_slot lists */
  96. int free_size; /* free bytes in the chunk */
  97. int contig_hint; /* max contiguous size hint */
  98. void *base_addr; /* base address of this chunk */
  99. int map_used; /* # of map entries used */
  100. int map_alloc; /* # of map entries allocated */
  101. int *map; /* allocation map */
  102. void *data; /* chunk data */
  103. bool immutable; /* no [de]population allowed */
  104. unsigned long populated[]; /* populated bitmap */
  105. };
  106. static int pcpu_unit_pages __read_mostly;
  107. static int pcpu_unit_size __read_mostly;
  108. static int pcpu_nr_units __read_mostly;
  109. static int pcpu_atom_size __read_mostly;
  110. static int pcpu_nr_slots __read_mostly;
  111. static size_t pcpu_chunk_struct_size __read_mostly;
  112. /* cpus with the lowest and highest unit addresses */
  113. static unsigned int pcpu_low_unit_cpu __read_mostly;
  114. static unsigned int pcpu_high_unit_cpu __read_mostly;
  115. /* the address of the first chunk which starts with the kernel static area */
  116. void *pcpu_base_addr __read_mostly;
  117. EXPORT_SYMBOL_GPL(pcpu_base_addr);
  118. static const int *pcpu_unit_map __read_mostly; /* cpu -> unit */
  119. const unsigned long *pcpu_unit_offsets __read_mostly; /* cpu -> unit offset */
  120. /* group information, used for vm allocation */
  121. static int pcpu_nr_groups __read_mostly;
  122. static const unsigned long *pcpu_group_offsets __read_mostly;
  123. static const size_t *pcpu_group_sizes __read_mostly;
  124. /*
  125. * The first chunk which always exists. Note that unlike other
  126. * chunks, this one can be allocated and mapped in several different
  127. * ways and thus often doesn't live in the vmalloc area.
  128. */
  129. static struct pcpu_chunk *pcpu_first_chunk;
  130. /*
  131. * Optional reserved chunk. This chunk reserves part of the first
  132. * chunk and serves it for reserved allocations. The amount of
  133. * reserved offset is in pcpu_reserved_chunk_limit. When reserved
  134. * area doesn't exist, the following variables contain NULL and 0
  135. * respectively.
  136. */
  137. static struct pcpu_chunk *pcpu_reserved_chunk;
  138. static int pcpu_reserved_chunk_limit;
  139. /*
  140. * Synchronization rules.
  141. *
  142. * There are two locks - pcpu_alloc_mutex and pcpu_lock. The former
  143. * protects allocation/reclaim paths, chunks, populated bitmap and
  144. * vmalloc mapping. The latter is a spinlock and protects the index
  145. * data structures - chunk slots, chunks and area maps in chunks.
  146. *
  147. * During allocation, pcpu_alloc_mutex is kept locked all the time and
  148. * pcpu_lock is grabbed and released as necessary. All actual memory
  149. * allocations are done using GFP_KERNEL with pcpu_lock released. In
  150. * general, percpu memory can't be allocated with irq off but
  151. * irqsave/restore are still used in alloc path so that it can be used
  152. * from early init path - sched_init() specifically.
  153. *
  154. * Free path accesses and alters only the index data structures, so it
  155. * can be safely called from atomic context. When memory needs to be
  156. * returned to the system, free path schedules reclaim_work which
  157. * grabs both pcpu_alloc_mutex and pcpu_lock, unlinks chunks to be
  158. * reclaimed, release both locks and frees the chunks. Note that it's
  159. * necessary to grab both locks to remove a chunk from circulation as
  160. * allocation path might be referencing the chunk with only
  161. * pcpu_alloc_mutex locked.
  162. */
  163. static DEFINE_MUTEX(pcpu_alloc_mutex); /* protects whole alloc and reclaim */
  164. static DEFINE_SPINLOCK(pcpu_lock); /* protects index data structures */
  165. static struct list_head *pcpu_slot __read_mostly; /* chunk list slots */
  166. /* reclaim work to release fully free chunks, scheduled from free path */
  167. static void pcpu_reclaim(struct work_struct *work);
  168. static DECLARE_WORK(pcpu_reclaim_work, pcpu_reclaim);
  169. static bool pcpu_addr_in_first_chunk(void *addr)
  170. {
  171. void *first_start = pcpu_first_chunk->base_addr;
  172. return addr >= first_start && addr < first_start + pcpu_unit_size;
  173. }
  174. static bool pcpu_addr_in_reserved_chunk(void *addr)
  175. {
  176. void *first_start = pcpu_first_chunk->base_addr;
  177. return addr >= first_start &&
  178. addr < first_start + pcpu_reserved_chunk_limit;
  179. }
  180. static int __pcpu_size_to_slot(int size)
  181. {
  182. int highbit = fls(size); /* size is in bytes */
  183. return max(highbit - PCPU_SLOT_BASE_SHIFT + 2, 1);
  184. }
  185. static int pcpu_size_to_slot(int size)
  186. {
  187. if (size == pcpu_unit_size)
  188. return pcpu_nr_slots - 1;
  189. return __pcpu_size_to_slot(size);
  190. }
  191. static int pcpu_chunk_slot(const struct pcpu_chunk *chunk)
  192. {
  193. if (chunk->free_size < sizeof(int) || chunk->contig_hint < sizeof(int))
  194. return 0;
  195. return pcpu_size_to_slot(chunk->free_size);
  196. }
  197. /* set the pointer to a chunk in a page struct */
  198. static void pcpu_set_page_chunk(struct page *page, struct pcpu_chunk *pcpu)
  199. {
  200. page->index = (unsigned long)pcpu;
  201. }
  202. /* obtain pointer to a chunk from a page struct */
  203. static struct pcpu_chunk *pcpu_get_page_chunk(struct page *page)
  204. {
  205. return (struct pcpu_chunk *)page->index;
  206. }
  207. static int __maybe_unused pcpu_page_idx(unsigned int cpu, int page_idx)
  208. {
  209. return pcpu_unit_map[cpu] * pcpu_unit_pages + page_idx;
  210. }
  211. static unsigned long pcpu_chunk_addr(struct pcpu_chunk *chunk,
  212. unsigned int cpu, int page_idx)
  213. {
  214. return (unsigned long)chunk->base_addr + pcpu_unit_offsets[cpu] +
  215. (page_idx << PAGE_SHIFT);
  216. }
  217. static void __maybe_unused pcpu_next_unpop(struct pcpu_chunk *chunk,
  218. int *rs, int *re, int end)
  219. {
  220. *rs = find_next_zero_bit(chunk->populated, end, *rs);
  221. *re = find_next_bit(chunk->populated, end, *rs + 1);
  222. }
  223. static void __maybe_unused pcpu_next_pop(struct pcpu_chunk *chunk,
  224. int *rs, int *re, int end)
  225. {
  226. *rs = find_next_bit(chunk->populated, end, *rs);
  227. *re = find_next_zero_bit(chunk->populated, end, *rs + 1);
  228. }
  229. /*
  230. * (Un)populated page region iterators. Iterate over (un)populated
  231. * page regions between @start and @end in @chunk. @rs and @re should
  232. * be integer variables and will be set to start and end page index of
  233. * the current region.
  234. */
  235. #define pcpu_for_each_unpop_region(chunk, rs, re, start, end) \
  236. for ((rs) = (start), pcpu_next_unpop((chunk), &(rs), &(re), (end)); \
  237. (rs) < (re); \
  238. (rs) = (re) + 1, pcpu_next_unpop((chunk), &(rs), &(re), (end)))
  239. #define pcpu_for_each_pop_region(chunk, rs, re, start, end) \
  240. for ((rs) = (start), pcpu_next_pop((chunk), &(rs), &(re), (end)); \
  241. (rs) < (re); \
  242. (rs) = (re) + 1, pcpu_next_pop((chunk), &(rs), &(re), (end)))
  243. /**
  244. * pcpu_mem_alloc - allocate memory
  245. * @size: bytes to allocate
  246. *
  247. * Allocate @size bytes. If @size is smaller than PAGE_SIZE,
  248. * kzalloc() is used; otherwise, vmalloc() is used. The returned
  249. * memory is always zeroed.
  250. *
  251. * CONTEXT:
  252. * Does GFP_KERNEL allocation.
  253. *
  254. * RETURNS:
  255. * Pointer to the allocated area on success, NULL on failure.
  256. */
  257. static void *pcpu_mem_alloc(size_t size)
  258. {
  259. if (WARN_ON_ONCE(!slab_is_available()))
  260. return NULL;
  261. if (size <= PAGE_SIZE)
  262. return kzalloc(size, GFP_KERNEL);
  263. else
  264. return vzalloc(size);
  265. }
  266. /**
  267. * pcpu_mem_free - free memory
  268. * @ptr: memory to free
  269. * @size: size of the area
  270. *
  271. * Free @ptr. @ptr should have been allocated using pcpu_mem_alloc().
  272. */
  273. static void pcpu_mem_free(void *ptr, size_t size)
  274. {
  275. if (size <= PAGE_SIZE)
  276. kfree(ptr);
  277. else
  278. vfree(ptr);
  279. }
  280. /**
  281. * pcpu_chunk_relocate - put chunk in the appropriate chunk slot
  282. * @chunk: chunk of interest
  283. * @oslot: the previous slot it was on
  284. *
  285. * This function is called after an allocation or free changed @chunk.
  286. * New slot according to the changed state is determined and @chunk is
  287. * moved to the slot. Note that the reserved chunk is never put on
  288. * chunk slots.
  289. *
  290. * CONTEXT:
  291. * pcpu_lock.
  292. */
  293. static void pcpu_chunk_relocate(struct pcpu_chunk *chunk, int oslot)
  294. {
  295. int nslot = pcpu_chunk_slot(chunk);
  296. if (chunk != pcpu_reserved_chunk && oslot != nslot) {
  297. if (oslot < nslot)
  298. list_move(&chunk->list, &pcpu_slot[nslot]);
  299. else
  300. list_move_tail(&chunk->list, &pcpu_slot[nslot]);
  301. }
  302. }
  303. /**
  304. * pcpu_need_to_extend - determine whether chunk area map needs to be extended
  305. * @chunk: chunk of interest
  306. *
  307. * Determine whether area map of @chunk needs to be extended to
  308. * accommodate a new allocation.
  309. *
  310. * CONTEXT:
  311. * pcpu_lock.
  312. *
  313. * RETURNS:
  314. * New target map allocation length if extension is necessary, 0
  315. * otherwise.
  316. */
  317. static int pcpu_need_to_extend(struct pcpu_chunk *chunk)
  318. {
  319. int new_alloc;
  320. if (chunk->map_alloc >= chunk->map_used + 2)
  321. return 0;
  322. new_alloc = PCPU_DFL_MAP_ALLOC;
  323. while (new_alloc < chunk->map_used + 2)
  324. new_alloc *= 2;
  325. return new_alloc;
  326. }
  327. /**
  328. * pcpu_extend_area_map - extend area map of a chunk
  329. * @chunk: chunk of interest
  330. * @new_alloc: new target allocation length of the area map
  331. *
  332. * Extend area map of @chunk to have @new_alloc entries.
  333. *
  334. * CONTEXT:
  335. * Does GFP_KERNEL allocation. Grabs and releases pcpu_lock.
  336. *
  337. * RETURNS:
  338. * 0 on success, -errno on failure.
  339. */
  340. static int pcpu_extend_area_map(struct pcpu_chunk *chunk, int new_alloc)
  341. {
  342. int *old = NULL, *new = NULL;
  343. size_t old_size = 0, new_size = new_alloc * sizeof(new[0]);
  344. unsigned long flags;
  345. new = pcpu_mem_alloc(new_size);
  346. if (!new)
  347. return -ENOMEM;
  348. /* acquire pcpu_lock and switch to new area map */
  349. spin_lock_irqsave(&pcpu_lock, flags);
  350. if (new_alloc <= chunk->map_alloc)
  351. goto out_unlock;
  352. old_size = chunk->map_alloc * sizeof(chunk->map[0]);
  353. old = chunk->map;
  354. memcpy(new, old, old_size);
  355. chunk->map_alloc = new_alloc;
  356. chunk->map = new;
  357. new = NULL;
  358. out_unlock:
  359. spin_unlock_irqrestore(&pcpu_lock, flags);
  360. /*
  361. * pcpu_mem_free() might end up calling vfree() which uses
  362. * IRQ-unsafe lock and thus can't be called under pcpu_lock.
  363. */
  364. pcpu_mem_free(old, old_size);
  365. pcpu_mem_free(new, new_size);
  366. return 0;
  367. }
  368. /**
  369. * pcpu_split_block - split a map block
  370. * @chunk: chunk of interest
  371. * @i: index of map block to split
  372. * @head: head size in bytes (can be 0)
  373. * @tail: tail size in bytes (can be 0)
  374. *
  375. * Split the @i'th map block into two or three blocks. If @head is
  376. * non-zero, @head bytes block is inserted before block @i moving it
  377. * to @i+1 and reducing its size by @head bytes.
  378. *
  379. * If @tail is non-zero, the target block, which can be @i or @i+1
  380. * depending on @head, is reduced by @tail bytes and @tail byte block
  381. * is inserted after the target block.
  382. *
  383. * @chunk->map must have enough free slots to accommodate the split.
  384. *
  385. * CONTEXT:
  386. * pcpu_lock.
  387. */
  388. static void pcpu_split_block(struct pcpu_chunk *chunk, int i,
  389. int head, int tail)
  390. {
  391. int nr_extra = !!head + !!tail;
  392. BUG_ON(chunk->map_alloc < chunk->map_used + nr_extra);
  393. /* insert new subblocks */
  394. memmove(&chunk->map[i + nr_extra], &chunk->map[i],
  395. sizeof(chunk->map[0]) * (chunk->map_used - i));
  396. chunk->map_used += nr_extra;
  397. if (head) {
  398. chunk->map[i + 1] = chunk->map[i] - head;
  399. chunk->map[i++] = head;
  400. }
  401. if (tail) {
  402. chunk->map[i++] -= tail;
  403. chunk->map[i] = tail;
  404. }
  405. }
  406. /**
  407. * pcpu_alloc_area - allocate area from a pcpu_chunk
  408. * @chunk: chunk of interest
  409. * @size: wanted size in bytes
  410. * @align: wanted align
  411. *
  412. * Try to allocate @size bytes area aligned at @align from @chunk.
  413. * Note that this function only allocates the offset. It doesn't
  414. * populate or map the area.
  415. *
  416. * @chunk->map must have at least two free slots.
  417. *
  418. * CONTEXT:
  419. * pcpu_lock.
  420. *
  421. * RETURNS:
  422. * Allocated offset in @chunk on success, -1 if no matching area is
  423. * found.
  424. */
  425. static int pcpu_alloc_area(struct pcpu_chunk *chunk, int size, int align)
  426. {
  427. int oslot = pcpu_chunk_slot(chunk);
  428. int max_contig = 0;
  429. int i, off;
  430. for (i = 0, off = 0; i < chunk->map_used; off += abs(chunk->map[i++])) {
  431. bool is_last = i + 1 == chunk->map_used;
  432. int head, tail;
  433. /* extra for alignment requirement */
  434. head = ALIGN(off, align) - off;
  435. BUG_ON(i == 0 && head != 0);
  436. if (chunk->map[i] < 0)
  437. continue;
  438. if (chunk->map[i] < head + size) {
  439. max_contig = max(chunk->map[i], max_contig);
  440. continue;
  441. }
  442. /*
  443. * If head is small or the previous block is free,
  444. * merge'em. Note that 'small' is defined as smaller
  445. * than sizeof(int), which is very small but isn't too
  446. * uncommon for percpu allocations.
  447. */
  448. if (head && (head < sizeof(int) || chunk->map[i - 1] > 0)) {
  449. if (chunk->map[i - 1] > 0)
  450. chunk->map[i - 1] += head;
  451. else {
  452. chunk->map[i - 1] -= head;
  453. chunk->free_size -= head;
  454. }
  455. chunk->map[i] -= head;
  456. off += head;
  457. head = 0;
  458. }
  459. /* if tail is small, just keep it around */
  460. tail = chunk->map[i] - head - size;
  461. if (tail < sizeof(int))
  462. tail = 0;
  463. /* split if warranted */
  464. if (head || tail) {
  465. pcpu_split_block(chunk, i, head, tail);
  466. if (head) {
  467. i++;
  468. off += head;
  469. max_contig = max(chunk->map[i - 1], max_contig);
  470. }
  471. if (tail)
  472. max_contig = max(chunk->map[i + 1], max_contig);
  473. }
  474. /* update hint and mark allocated */
  475. if (is_last)
  476. chunk->contig_hint = max_contig; /* fully scanned */
  477. else
  478. chunk->contig_hint = max(chunk->contig_hint,
  479. max_contig);
  480. chunk->free_size -= chunk->map[i];
  481. chunk->map[i] = -chunk->map[i];
  482. pcpu_chunk_relocate(chunk, oslot);
  483. return off;
  484. }
  485. chunk->contig_hint = max_contig; /* fully scanned */
  486. pcpu_chunk_relocate(chunk, oslot);
  487. /* tell the upper layer that this chunk has no matching area */
  488. return -1;
  489. }
  490. /**
  491. * pcpu_free_area - free area to a pcpu_chunk
  492. * @chunk: chunk of interest
  493. * @freeme: offset of area to free
  494. *
  495. * Free area starting from @freeme to @chunk. Note that this function
  496. * only modifies the allocation map. It doesn't depopulate or unmap
  497. * the area.
  498. *
  499. * CONTEXT:
  500. * pcpu_lock.
  501. */
  502. static void pcpu_free_area(struct pcpu_chunk *chunk, int freeme)
  503. {
  504. int oslot = pcpu_chunk_slot(chunk);
  505. int i, off;
  506. for (i = 0, off = 0; i < chunk->map_used; off += abs(chunk->map[i++]))
  507. if (off == freeme)
  508. break;
  509. BUG_ON(off != freeme);
  510. BUG_ON(chunk->map[i] > 0);
  511. chunk->map[i] = -chunk->map[i];
  512. chunk->free_size += chunk->map[i];
  513. /* merge with previous? */
  514. if (i > 0 && chunk->map[i - 1] >= 0) {
  515. chunk->map[i - 1] += chunk->map[i];
  516. chunk->map_used--;
  517. memmove(&chunk->map[i], &chunk->map[i + 1],
  518. (chunk->map_used - i) * sizeof(chunk->map[0]));
  519. i--;
  520. }
  521. /* merge with next? */
  522. if (i + 1 < chunk->map_used && chunk->map[i + 1] >= 0) {
  523. chunk->map[i] += chunk->map[i + 1];
  524. chunk->map_used--;
  525. memmove(&chunk->map[i + 1], &chunk->map[i + 2],
  526. (chunk->map_used - (i + 1)) * sizeof(chunk->map[0]));
  527. }
  528. chunk->contig_hint = max(chunk->map[i], chunk->contig_hint);
  529. pcpu_chunk_relocate(chunk, oslot);
  530. }
  531. static struct pcpu_chunk *pcpu_alloc_chunk(void)
  532. {
  533. struct pcpu_chunk *chunk;
  534. chunk = pcpu_mem_alloc(pcpu_chunk_struct_size);
  535. if (!chunk)
  536. return NULL;
  537. chunk->map = pcpu_mem_alloc(PCPU_DFL_MAP_ALLOC * sizeof(chunk->map[0]));
  538. if (!chunk->map) {
  539. kfree(chunk);
  540. return NULL;
  541. }
  542. chunk->map_alloc = PCPU_DFL_MAP_ALLOC;
  543. chunk->map[chunk->map_used++] = pcpu_unit_size;
  544. INIT_LIST_HEAD(&chunk->list);
  545. chunk->free_size = pcpu_unit_size;
  546. chunk->contig_hint = pcpu_unit_size;
  547. return chunk;
  548. }
  549. static void pcpu_free_chunk(struct pcpu_chunk *chunk)
  550. {
  551. if (!chunk)
  552. return;
  553. pcpu_mem_free(chunk->map, chunk->map_alloc * sizeof(chunk->map[0]));
  554. kfree(chunk);
  555. }
  556. /*
  557. * Chunk management implementation.
  558. *
  559. * To allow different implementations, chunk alloc/free and
  560. * [de]population are implemented in a separate file which is pulled
  561. * into this file and compiled together. The following functions
  562. * should be implemented.
  563. *
  564. * pcpu_populate_chunk - populate the specified range of a chunk
  565. * pcpu_depopulate_chunk - depopulate the specified range of a chunk
  566. * pcpu_create_chunk - create a new chunk
  567. * pcpu_destroy_chunk - destroy a chunk, always preceded by full depop
  568. * pcpu_addr_to_page - translate address to physical address
  569. * pcpu_verify_alloc_info - check alloc_info is acceptable during init
  570. */
  571. static int pcpu_populate_chunk(struct pcpu_chunk *chunk, int off, int size);
  572. static void pcpu_depopulate_chunk(struct pcpu_chunk *chunk, int off, int size);
  573. static struct pcpu_chunk *pcpu_create_chunk(void);
  574. static void pcpu_destroy_chunk(struct pcpu_chunk *chunk);
  575. static struct page *pcpu_addr_to_page(void *addr);
  576. static int __init pcpu_verify_alloc_info(const struct pcpu_alloc_info *ai);
  577. #ifdef CONFIG_NEED_PER_CPU_KM
  578. #include "percpu-km.c"
  579. #else
  580. #include "percpu-vm.c"
  581. #endif
  582. /**
  583. * pcpu_chunk_addr_search - determine chunk containing specified address
  584. * @addr: address for which the chunk needs to be determined.
  585. *
  586. * RETURNS:
  587. * The address of the found chunk.
  588. */
  589. static struct pcpu_chunk *pcpu_chunk_addr_search(void *addr)
  590. {
  591. /* is it in the first chunk? */
  592. if (pcpu_addr_in_first_chunk(addr)) {
  593. /* is it in the reserved area? */
  594. if (pcpu_addr_in_reserved_chunk(addr))
  595. return pcpu_reserved_chunk;
  596. return pcpu_first_chunk;
  597. }
  598. /*
  599. * The address is relative to unit0 which might be unused and
  600. * thus unmapped. Offset the address to the unit space of the
  601. * current processor before looking it up in the vmalloc
  602. * space. Note that any possible cpu id can be used here, so
  603. * there's no need to worry about preemption or cpu hotplug.
  604. */
  605. addr += pcpu_unit_offsets[raw_smp_processor_id()];
  606. return pcpu_get_page_chunk(pcpu_addr_to_page(addr));
  607. }
  608. /**
  609. * pcpu_alloc - the percpu allocator
  610. * @size: size of area to allocate in bytes
  611. * @align: alignment of area (max PAGE_SIZE)
  612. * @reserved: allocate from the reserved chunk if available
  613. *
  614. * Allocate percpu area of @size bytes aligned at @align.
  615. *
  616. * CONTEXT:
  617. * Does GFP_KERNEL allocation.
  618. *
  619. * RETURNS:
  620. * Percpu pointer to the allocated area on success, NULL on failure.
  621. */
  622. static void __percpu *pcpu_alloc(size_t size, size_t align, bool reserved)
  623. {
  624. static int warn_limit = 10;
  625. struct pcpu_chunk *chunk;
  626. const char *err;
  627. int slot, off, new_alloc;
  628. unsigned long flags;
  629. if (unlikely(!size || size > PCPU_MIN_UNIT_SIZE || align > PAGE_SIZE)) {
  630. WARN(true, "illegal size (%zu) or align (%zu) for "
  631. "percpu allocation\n", size, align);
  632. return NULL;
  633. }
  634. mutex_lock(&pcpu_alloc_mutex);
  635. spin_lock_irqsave(&pcpu_lock, flags);
  636. /* serve reserved allocations from the reserved chunk if available */
  637. if (reserved && pcpu_reserved_chunk) {
  638. chunk = pcpu_reserved_chunk;
  639. if (size > chunk->contig_hint) {
  640. err = "alloc from reserved chunk failed";
  641. goto fail_unlock;
  642. }
  643. while ((new_alloc = pcpu_need_to_extend(chunk))) {
  644. spin_unlock_irqrestore(&pcpu_lock, flags);
  645. if (pcpu_extend_area_map(chunk, new_alloc) < 0) {
  646. err = "failed to extend area map of reserved chunk";
  647. goto fail_unlock_mutex;
  648. }
  649. spin_lock_irqsave(&pcpu_lock, flags);
  650. }
  651. off = pcpu_alloc_area(chunk, size, align);
  652. if (off >= 0)
  653. goto area_found;
  654. err = "alloc from reserved chunk failed";
  655. goto fail_unlock;
  656. }
  657. restart:
  658. /* search through normal chunks */
  659. for (slot = pcpu_size_to_slot(size); slot < pcpu_nr_slots; slot++) {
  660. list_for_each_entry(chunk, &pcpu_slot[slot], list) {
  661. if (size > chunk->contig_hint)
  662. continue;
  663. new_alloc = pcpu_need_to_extend(chunk);
  664. if (new_alloc) {
  665. spin_unlock_irqrestore(&pcpu_lock, flags);
  666. if (pcpu_extend_area_map(chunk,
  667. new_alloc) < 0) {
  668. err = "failed to extend area map";
  669. goto fail_unlock_mutex;
  670. }
  671. spin_lock_irqsave(&pcpu_lock, flags);
  672. /*
  673. * pcpu_lock has been dropped, need to
  674. * restart cpu_slot list walking.
  675. */
  676. goto restart;
  677. }
  678. off = pcpu_alloc_area(chunk, size, align);
  679. if (off >= 0)
  680. goto area_found;
  681. }
  682. }
  683. /* hmmm... no space left, create a new chunk */
  684. spin_unlock_irqrestore(&pcpu_lock, flags);
  685. chunk = pcpu_create_chunk();
  686. if (!chunk) {
  687. err = "failed to allocate new chunk";
  688. goto fail_unlock_mutex;
  689. }
  690. spin_lock_irqsave(&pcpu_lock, flags);
  691. pcpu_chunk_relocate(chunk, -1);
  692. goto restart;
  693. area_found:
  694. spin_unlock_irqrestore(&pcpu_lock, flags);
  695. /* populate, map and clear the area */
  696. if (pcpu_populate_chunk(chunk, off, size)) {
  697. spin_lock_irqsave(&pcpu_lock, flags);
  698. pcpu_free_area(chunk, off);
  699. err = "failed to populate";
  700. goto fail_unlock;
  701. }
  702. mutex_unlock(&pcpu_alloc_mutex);
  703. /* return address relative to base address */
  704. return __addr_to_pcpu_ptr(chunk->base_addr + off);
  705. fail_unlock:
  706. spin_unlock_irqrestore(&pcpu_lock, flags);
  707. fail_unlock_mutex:
  708. mutex_unlock(&pcpu_alloc_mutex);
  709. if (warn_limit) {
  710. pr_warning("PERCPU: allocation failed, size=%zu align=%zu, "
  711. "%s\n", size, align, err);
  712. dump_stack();
  713. if (!--warn_limit)
  714. pr_info("PERCPU: limit reached, disable warning\n");
  715. }
  716. return NULL;
  717. }
  718. /**
  719. * __alloc_percpu - allocate dynamic percpu area
  720. * @size: size of area to allocate in bytes
  721. * @align: alignment of area (max PAGE_SIZE)
  722. *
  723. * Allocate zero-filled percpu area of @size bytes aligned at @align.
  724. * Might sleep. Might trigger writeouts.
  725. *
  726. * CONTEXT:
  727. * Does GFP_KERNEL allocation.
  728. *
  729. * RETURNS:
  730. * Percpu pointer to the allocated area on success, NULL on failure.
  731. */
  732. void __percpu *__alloc_percpu(size_t size, size_t align)
  733. {
  734. return pcpu_alloc(size, align, false);
  735. }
  736. EXPORT_SYMBOL_GPL(__alloc_percpu);
  737. /**
  738. * __alloc_reserved_percpu - allocate reserved percpu area
  739. * @size: size of area to allocate in bytes
  740. * @align: alignment of area (max PAGE_SIZE)
  741. *
  742. * Allocate zero-filled percpu area of @size bytes aligned at @align
  743. * from reserved percpu area if arch has set it up; otherwise,
  744. * allocation is served from the same dynamic area. Might sleep.
  745. * Might trigger writeouts.
  746. *
  747. * CONTEXT:
  748. * Does GFP_KERNEL allocation.
  749. *
  750. * RETURNS:
  751. * Percpu pointer to the allocated area on success, NULL on failure.
  752. */
  753. void __percpu *__alloc_reserved_percpu(size_t size, size_t align)
  754. {
  755. return pcpu_alloc(size, align, true);
  756. }
  757. /**
  758. * pcpu_reclaim - reclaim fully free chunks, workqueue function
  759. * @work: unused
  760. *
  761. * Reclaim all fully free chunks except for the first one.
  762. *
  763. * CONTEXT:
  764. * workqueue context.
  765. */
  766. static void pcpu_reclaim(struct work_struct *work)
  767. {
  768. LIST_HEAD(todo);
  769. struct list_head *head = &pcpu_slot[pcpu_nr_slots - 1];
  770. struct pcpu_chunk *chunk, *next;
  771. mutex_lock(&pcpu_alloc_mutex);
  772. spin_lock_irq(&pcpu_lock);
  773. list_for_each_entry_safe(chunk, next, head, list) {
  774. WARN_ON(chunk->immutable);
  775. /* spare the first one */
  776. if (chunk == list_first_entry(head, struct pcpu_chunk, list))
  777. continue;
  778. list_move(&chunk->list, &todo);
  779. }
  780. spin_unlock_irq(&pcpu_lock);
  781. list_for_each_entry_safe(chunk, next, &todo, list) {
  782. pcpu_depopulate_chunk(chunk, 0, pcpu_unit_size);
  783. pcpu_destroy_chunk(chunk);
  784. }
  785. mutex_unlock(&pcpu_alloc_mutex);
  786. }
  787. /**
  788. * free_percpu - free percpu area
  789. * @ptr: pointer to area to free
  790. *
  791. * Free percpu area @ptr.
  792. *
  793. * CONTEXT:
  794. * Can be called from atomic context.
  795. */
  796. void free_percpu(void __percpu *ptr)
  797. {
  798. void *addr;
  799. struct pcpu_chunk *chunk;
  800. unsigned long flags;
  801. int off;
  802. if (!ptr)
  803. return;
  804. addr = __pcpu_ptr_to_addr(ptr);
  805. spin_lock_irqsave(&pcpu_lock, flags);
  806. chunk = pcpu_chunk_addr_search(addr);
  807. off = addr - chunk->base_addr;
  808. pcpu_free_area(chunk, off);
  809. /* if there are more than one fully free chunks, wake up grim reaper */
  810. if (chunk->free_size == pcpu_unit_size) {
  811. struct pcpu_chunk *pos;
  812. list_for_each_entry(pos, &pcpu_slot[pcpu_nr_slots - 1], list)
  813. if (pos != chunk) {
  814. schedule_work(&pcpu_reclaim_work);
  815. break;
  816. }
  817. }
  818. spin_unlock_irqrestore(&pcpu_lock, flags);
  819. }
  820. EXPORT_SYMBOL_GPL(free_percpu);
  821. /**
  822. * is_kernel_percpu_address - test whether address is from static percpu area
  823. * @addr: address to test
  824. *
  825. * Test whether @addr belongs to in-kernel static percpu area. Module
  826. * static percpu areas are not considered. For those, use
  827. * is_module_percpu_address().
  828. *
  829. * RETURNS:
  830. * %true if @addr is from in-kernel static percpu area, %false otherwise.
  831. */
  832. bool is_kernel_percpu_address(unsigned long addr)
  833. {
  834. #ifdef CONFIG_SMP
  835. const size_t static_size = __per_cpu_end - __per_cpu_start;
  836. void __percpu *base = __addr_to_pcpu_ptr(pcpu_base_addr);
  837. unsigned int cpu;
  838. for_each_possible_cpu(cpu) {
  839. void *start = per_cpu_ptr(base, cpu);
  840. if ((void *)addr >= start && (void *)addr < start + static_size)
  841. return true;
  842. }
  843. #endif
  844. /* on UP, can't distinguish from other static vars, always false */
  845. return false;
  846. }
  847. /**
  848. * per_cpu_ptr_to_phys - convert translated percpu address to physical address
  849. * @addr: the address to be converted to physical address
  850. *
  851. * Given @addr which is dereferenceable address obtained via one of
  852. * percpu access macros, this function translates it into its physical
  853. * address. The caller is responsible for ensuring @addr stays valid
  854. * until this function finishes.
  855. *
  856. * RETURNS:
  857. * The physical address for @addr.
  858. */
  859. phys_addr_t per_cpu_ptr_to_phys(void *addr)
  860. {
  861. void __percpu *base = __addr_to_pcpu_ptr(pcpu_base_addr);
  862. bool in_first_chunk = false;
  863. unsigned long first_low, first_high;
  864. unsigned int cpu;
  865. /*
  866. * The following test on unit_low/high isn't strictly
  867. * necessary but will speed up lookups of addresses which
  868. * aren't in the first chunk.
  869. */
  870. first_low = pcpu_chunk_addr(pcpu_first_chunk, pcpu_low_unit_cpu, 0);
  871. first_high = pcpu_chunk_addr(pcpu_first_chunk, pcpu_high_unit_cpu,
  872. pcpu_unit_pages);
  873. if ((unsigned long)addr >= first_low &&
  874. (unsigned long)addr < first_high) {
  875. for_each_possible_cpu(cpu) {
  876. void *start = per_cpu_ptr(base, cpu);
  877. if (addr >= start && addr < start + pcpu_unit_size) {
  878. in_first_chunk = true;
  879. break;
  880. }
  881. }
  882. }
  883. if (in_first_chunk) {
  884. if (!is_vmalloc_addr(addr))
  885. return __pa(addr);
  886. else
  887. return page_to_phys(vmalloc_to_page(addr)) +
  888. offset_in_page(addr);
  889. } else
  890. return page_to_phys(pcpu_addr_to_page(addr)) +
  891. offset_in_page(addr);
  892. }
  893. /**
  894. * pcpu_alloc_alloc_info - allocate percpu allocation info
  895. * @nr_groups: the number of groups
  896. * @nr_units: the number of units
  897. *
  898. * Allocate ai which is large enough for @nr_groups groups containing
  899. * @nr_units units. The returned ai's groups[0].cpu_map points to the
  900. * cpu_map array which is long enough for @nr_units and filled with
  901. * NR_CPUS. It's the caller's responsibility to initialize cpu_map
  902. * pointer of other groups.
  903. *
  904. * RETURNS:
  905. * Pointer to the allocated pcpu_alloc_info on success, NULL on
  906. * failure.
  907. */
  908. struct pcpu_alloc_info * __init pcpu_alloc_alloc_info(int nr_groups,
  909. int nr_units)
  910. {
  911. struct pcpu_alloc_info *ai;
  912. size_t base_size, ai_size;
  913. void *ptr;
  914. int unit;
  915. base_size = ALIGN(sizeof(*ai) + nr_groups * sizeof(ai->groups[0]),
  916. __alignof__(ai->groups[0].cpu_map[0]));
  917. ai_size = base_size + nr_units * sizeof(ai->groups[0].cpu_map[0]);
  918. ptr = alloc_bootmem_nopanic(PFN_ALIGN(ai_size));
  919. if (!ptr)
  920. return NULL;
  921. ai = ptr;
  922. ptr += base_size;
  923. ai->groups[0].cpu_map = ptr;
  924. for (unit = 0; unit < nr_units; unit++)
  925. ai->groups[0].cpu_map[unit] = NR_CPUS;
  926. ai->nr_groups = nr_groups;
  927. ai->__ai_size = PFN_ALIGN(ai_size);
  928. return ai;
  929. }
  930. /**
  931. * pcpu_free_alloc_info - free percpu allocation info
  932. * @ai: pcpu_alloc_info to free
  933. *
  934. * Free @ai which was allocated by pcpu_alloc_alloc_info().
  935. */
  936. void __init pcpu_free_alloc_info(struct pcpu_alloc_info *ai)
  937. {
  938. free_bootmem(__pa(ai), ai->__ai_size);
  939. }
  940. /**
  941. * pcpu_dump_alloc_info - print out information about pcpu_alloc_info
  942. * @lvl: loglevel
  943. * @ai: allocation info to dump
  944. *
  945. * Print out information about @ai using loglevel @lvl.
  946. */
  947. static void pcpu_dump_alloc_info(const char *lvl,
  948. const struct pcpu_alloc_info *ai)
  949. {
  950. int group_width = 1, cpu_width = 1, width;
  951. char empty_str[] = "--------";
  952. int alloc = 0, alloc_end = 0;
  953. int group, v;
  954. int upa, apl; /* units per alloc, allocs per line */
  955. v = ai->nr_groups;
  956. while (v /= 10)
  957. group_width++;
  958. v = num_possible_cpus();
  959. while (v /= 10)
  960. cpu_width++;
  961. empty_str[min_t(int, cpu_width, sizeof(empty_str) - 1)] = '\0';
  962. upa = ai->alloc_size / ai->unit_size;
  963. width = upa * (cpu_width + 1) + group_width + 3;
  964. apl = rounddown_pow_of_two(max(60 / width, 1));
  965. printk("%spcpu-alloc: s%zu r%zu d%zu u%zu alloc=%zu*%zu",
  966. lvl, ai->static_size, ai->reserved_size, ai->dyn_size,
  967. ai->unit_size, ai->alloc_size / ai->atom_size, ai->atom_size);
  968. for (group = 0; group < ai->nr_groups; group++) {
  969. const struct pcpu_group_info *gi = &ai->groups[group];
  970. int unit = 0, unit_end = 0;
  971. BUG_ON(gi->nr_units % upa);
  972. for (alloc_end += gi->nr_units / upa;
  973. alloc < alloc_end; alloc++) {
  974. if (!(alloc % apl)) {
  975. printk("\n");
  976. printk("%spcpu-alloc: ", lvl);
  977. }
  978. printk("[%0*d] ", group_width, group);
  979. for (unit_end += upa; unit < unit_end; unit++)
  980. if (gi->cpu_map[unit] != NR_CPUS)
  981. printk("%0*d ", cpu_width,
  982. gi->cpu_map[unit]);
  983. else
  984. printk("%s ", empty_str);
  985. }
  986. }
  987. printk("\n");
  988. }
  989. /**
  990. * pcpu_setup_first_chunk - initialize the first percpu chunk
  991. * @ai: pcpu_alloc_info describing how to percpu area is shaped
  992. * @base_addr: mapped address
  993. *
  994. * Initialize the first percpu chunk which contains the kernel static
  995. * perpcu area. This function is to be called from arch percpu area
  996. * setup path.
  997. *
  998. * @ai contains all information necessary to initialize the first
  999. * chunk and prime the dynamic percpu allocator.
  1000. *
  1001. * @ai->static_size is the size of static percpu area.
  1002. *
  1003. * @ai->reserved_size, if non-zero, specifies the amount of bytes to
  1004. * reserve after the static area in the first chunk. This reserves
  1005. * the first chunk such that it's available only through reserved
  1006. * percpu allocation. This is primarily used to serve module percpu
  1007. * static areas on architectures where the addressing model has
  1008. * limited offset range for symbol relocations to guarantee module
  1009. * percpu symbols fall inside the relocatable range.
  1010. *
  1011. * @ai->dyn_size determines the number of bytes available for dynamic
  1012. * allocation in the first chunk. The area between @ai->static_size +
  1013. * @ai->reserved_size + @ai->dyn_size and @ai->unit_size is unused.
  1014. *
  1015. * @ai->unit_size specifies unit size and must be aligned to PAGE_SIZE
  1016. * and equal to or larger than @ai->static_size + @ai->reserved_size +
  1017. * @ai->dyn_size.
  1018. *
  1019. * @ai->atom_size is the allocation atom size and used as alignment
  1020. * for vm areas.
  1021. *
  1022. * @ai->alloc_size is the allocation size and always multiple of
  1023. * @ai->atom_size. This is larger than @ai->atom_size if
  1024. * @ai->unit_size is larger than @ai->atom_size.
  1025. *
  1026. * @ai->nr_groups and @ai->groups describe virtual memory layout of
  1027. * percpu areas. Units which should be colocated are put into the
  1028. * same group. Dynamic VM areas will be allocated according to these
  1029. * groupings. If @ai->nr_groups is zero, a single group containing
  1030. * all units is assumed.
  1031. *
  1032. * The caller should have mapped the first chunk at @base_addr and
  1033. * copied static data to each unit.
  1034. *
  1035. * If the first chunk ends up with both reserved and dynamic areas, it
  1036. * is served by two chunks - one to serve the core static and reserved
  1037. * areas and the other for the dynamic area. They share the same vm
  1038. * and page map but uses different area allocation map to stay away
  1039. * from each other. The latter chunk is circulated in the chunk slots
  1040. * and available for dynamic allocation like any other chunks.
  1041. *
  1042. * RETURNS:
  1043. * 0 on success, -errno on failure.
  1044. */
  1045. int __init pcpu_setup_first_chunk(const struct pcpu_alloc_info *ai,
  1046. void *base_addr)
  1047. {
  1048. static char cpus_buf[4096] __initdata;
  1049. static int smap[PERCPU_DYNAMIC_EARLY_SLOTS] __initdata;
  1050. static int dmap[PERCPU_DYNAMIC_EARLY_SLOTS] __initdata;
  1051. size_t dyn_size = ai->dyn_size;
  1052. size_t size_sum = ai->static_size + ai->reserved_size + dyn_size;
  1053. struct pcpu_chunk *schunk, *dchunk = NULL;
  1054. unsigned long *group_offsets;
  1055. size_t *group_sizes;
  1056. unsigned long *unit_off;
  1057. unsigned int cpu;
  1058. int *unit_map;
  1059. int group, unit, i;
  1060. cpumask_scnprintf(cpus_buf, sizeof(cpus_buf), cpu_possible_mask);
  1061. #define PCPU_SETUP_BUG_ON(cond) do { \
  1062. if (unlikely(cond)) { \
  1063. pr_emerg("PERCPU: failed to initialize, %s", #cond); \
  1064. pr_emerg("PERCPU: cpu_possible_mask=%s\n", cpus_buf); \
  1065. pcpu_dump_alloc_info(KERN_EMERG, ai); \
  1066. BUG(); \
  1067. } \
  1068. } while (0)
  1069. /* sanity checks */
  1070. PCPU_SETUP_BUG_ON(ai->nr_groups <= 0);
  1071. #ifdef CONFIG_SMP
  1072. PCPU_SETUP_BUG_ON(!ai->static_size);
  1073. PCPU_SETUP_BUG_ON((unsigned long)__per_cpu_start & ~PAGE_MASK);
  1074. #endif
  1075. PCPU_SETUP_BUG_ON(!base_addr);
  1076. PCPU_SETUP_BUG_ON((unsigned long)base_addr & ~PAGE_MASK);
  1077. PCPU_SETUP_BUG_ON(ai->unit_size < size_sum);
  1078. PCPU_SETUP_BUG_ON(ai->unit_size & ~PAGE_MASK);
  1079. PCPU_SETUP_BUG_ON(ai->unit_size < PCPU_MIN_UNIT_SIZE);
  1080. PCPU_SETUP_BUG_ON(ai->dyn_size < PERCPU_DYNAMIC_EARLY_SIZE);
  1081. PCPU_SETUP_BUG_ON(pcpu_verify_alloc_info(ai) < 0);
  1082. /* process group information and build config tables accordingly */
  1083. group_offsets = alloc_bootmem(ai->nr_groups * sizeof(group_offsets[0]));
  1084. group_sizes = alloc_bootmem(ai->nr_groups * sizeof(group_sizes[0]));
  1085. unit_map = alloc_bootmem(nr_cpu_ids * sizeof(unit_map[0]));
  1086. unit_off = alloc_bootmem(nr_cpu_ids * sizeof(unit_off[0]));
  1087. for (cpu = 0; cpu < nr_cpu_ids; cpu++)
  1088. unit_map[cpu] = UINT_MAX;
  1089. pcpu_low_unit_cpu = NR_CPUS;
  1090. pcpu_high_unit_cpu = NR_CPUS;
  1091. for (group = 0, unit = 0; group < ai->nr_groups; group++, unit += i) {
  1092. const struct pcpu_group_info *gi = &ai->groups[group];
  1093. group_offsets[group] = gi->base_offset;
  1094. group_sizes[group] = gi->nr_units * ai->unit_size;
  1095. for (i = 0; i < gi->nr_units; i++) {
  1096. cpu = gi->cpu_map[i];
  1097. if (cpu == NR_CPUS)
  1098. continue;
  1099. PCPU_SETUP_BUG_ON(cpu > nr_cpu_ids);
  1100. PCPU_SETUP_BUG_ON(!cpu_possible(cpu));
  1101. PCPU_SETUP_BUG_ON(unit_map[cpu] != UINT_MAX);
  1102. unit_map[cpu] = unit + i;
  1103. unit_off[cpu] = gi->base_offset + i * ai->unit_size;
  1104. /* determine low/high unit_cpu */
  1105. if (pcpu_low_unit_cpu == NR_CPUS ||
  1106. unit_off[cpu] < unit_off[pcpu_low_unit_cpu])
  1107. pcpu_low_unit_cpu = cpu;
  1108. if (pcpu_high_unit_cpu == NR_CPUS ||
  1109. unit_off[cpu] > unit_off[pcpu_high_unit_cpu])
  1110. pcpu_high_unit_cpu = cpu;
  1111. }
  1112. }
  1113. pcpu_nr_units = unit;
  1114. for_each_possible_cpu(cpu)
  1115. PCPU_SETUP_BUG_ON(unit_map[cpu] == UINT_MAX);
  1116. /* we're done parsing the input, undefine BUG macro and dump config */
  1117. #undef PCPU_SETUP_BUG_ON
  1118. pcpu_dump_alloc_info(KERN_DEBUG, ai);
  1119. pcpu_nr_groups = ai->nr_groups;
  1120. pcpu_group_offsets = group_offsets;
  1121. pcpu_group_sizes = group_sizes;
  1122. pcpu_unit_map = unit_map;
  1123. pcpu_unit_offsets = unit_off;
  1124. /* determine basic parameters */
  1125. pcpu_unit_pages = ai->unit_size >> PAGE_SHIFT;
  1126. pcpu_unit_size = pcpu_unit_pages << PAGE_SHIFT;
  1127. pcpu_atom_size = ai->atom_size;
  1128. pcpu_chunk_struct_size = sizeof(struct pcpu_chunk) +
  1129. BITS_TO_LONGS(pcpu_unit_pages) * sizeof(unsigned long);
  1130. /*
  1131. * Allocate chunk slots. The additional last slot is for
  1132. * empty chunks.
  1133. */
  1134. pcpu_nr_slots = __pcpu_size_to_slot(pcpu_unit_size) + 2;
  1135. pcpu_slot = alloc_bootmem(pcpu_nr_slots * sizeof(pcpu_slot[0]));
  1136. for (i = 0; i < pcpu_nr_slots; i++)
  1137. INIT_LIST_HEAD(&pcpu_slot[i]);
  1138. /*
  1139. * Initialize static chunk. If reserved_size is zero, the
  1140. * static chunk covers static area + dynamic allocation area
  1141. * in the first chunk. If reserved_size is not zero, it
  1142. * covers static area + reserved area (mostly used for module
  1143. * static percpu allocation).
  1144. */
  1145. schunk = alloc_bootmem(pcpu_chunk_struct_size);
  1146. INIT_LIST_HEAD(&schunk->list);
  1147. schunk->base_addr = base_addr;
  1148. schunk->map = smap;
  1149. schunk->map_alloc = ARRAY_SIZE(smap);
  1150. schunk->immutable = true;
  1151. bitmap_fill(schunk->populated, pcpu_unit_pages);
  1152. if (ai->reserved_size) {
  1153. schunk->free_size = ai->reserved_size;
  1154. pcpu_reserved_chunk = schunk;
  1155. pcpu_reserved_chunk_limit = ai->static_size + ai->reserved_size;
  1156. } else {
  1157. schunk->free_size = dyn_size;
  1158. dyn_size = 0; /* dynamic area covered */
  1159. }
  1160. schunk->contig_hint = schunk->free_size;
  1161. schunk->map[schunk->map_used++] = -ai->static_size;
  1162. if (schunk->free_size)
  1163. schunk->map[schunk->map_used++] = schunk->free_size;
  1164. /* init dynamic chunk if necessary */
  1165. if (dyn_size) {
  1166. dchunk = alloc_bootmem(pcpu_chunk_struct_size);
  1167. INIT_LIST_HEAD(&dchunk->list);
  1168. dchunk->base_addr = base_addr;
  1169. dchunk->map = dmap;
  1170. dchunk->map_alloc = ARRAY_SIZE(dmap);
  1171. dchunk->immutable = true;
  1172. bitmap_fill(dchunk->populated, pcpu_unit_pages);
  1173. dchunk->contig_hint = dchunk->free_size = dyn_size;
  1174. dchunk->map[dchunk->map_used++] = -pcpu_reserved_chunk_limit;
  1175. dchunk->map[dchunk->map_used++] = dchunk->free_size;
  1176. }
  1177. /* link the first chunk in */
  1178. pcpu_first_chunk = dchunk ?: schunk;
  1179. pcpu_chunk_relocate(pcpu_first_chunk, -1);
  1180. /* we're done */
  1181. pcpu_base_addr = base_addr;
  1182. return 0;
  1183. }
  1184. #ifdef CONFIG_SMP
  1185. const char *pcpu_fc_names[PCPU_FC_NR] __initdata = {
  1186. [PCPU_FC_AUTO] = "auto",
  1187. [PCPU_FC_EMBED] = "embed",
  1188. [PCPU_FC_PAGE] = "page",
  1189. };
  1190. enum pcpu_fc pcpu_chosen_fc __initdata = PCPU_FC_AUTO;
  1191. static int __init percpu_alloc_setup(char *str)
  1192. {
  1193. if (0)
  1194. /* nada */;
  1195. #ifdef CONFIG_NEED_PER_CPU_EMBED_FIRST_CHUNK
  1196. else if (!strcmp(str, "embed"))
  1197. pcpu_chosen_fc = PCPU_FC_EMBED;
  1198. #endif
  1199. #ifdef CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK
  1200. else if (!strcmp(str, "page"))
  1201. pcpu_chosen_fc = PCPU_FC_PAGE;
  1202. #endif
  1203. else
  1204. pr_warning("PERCPU: unknown allocator %s specified\n", str);
  1205. return 0;
  1206. }
  1207. early_param("percpu_alloc", percpu_alloc_setup);
  1208. /*
  1209. * pcpu_embed_first_chunk() is used by the generic percpu setup.
  1210. * Build it if needed by the arch config or the generic setup is going
  1211. * to be used.
  1212. */
  1213. #if defined(CONFIG_NEED_PER_CPU_EMBED_FIRST_CHUNK) || \
  1214. !defined(CONFIG_HAVE_SETUP_PER_CPU_AREA)
  1215. #define BUILD_EMBED_FIRST_CHUNK
  1216. #endif
  1217. /* build pcpu_page_first_chunk() iff needed by the arch config */
  1218. #if defined(CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK)
  1219. #define BUILD_PAGE_FIRST_CHUNK
  1220. #endif
  1221. /* pcpu_build_alloc_info() is used by both embed and page first chunk */
  1222. #if defined(BUILD_EMBED_FIRST_CHUNK) || defined(BUILD_PAGE_FIRST_CHUNK)
  1223. /**
  1224. * pcpu_build_alloc_info - build alloc_info considering distances between CPUs
  1225. * @reserved_size: the size of reserved percpu area in bytes
  1226. * @dyn_size: minimum free size for dynamic allocation in bytes
  1227. * @atom_size: allocation atom size
  1228. * @cpu_distance_fn: callback to determine distance between cpus, optional
  1229. *
  1230. * This function determines grouping of units, their mappings to cpus
  1231. * and other parameters considering needed percpu size, allocation
  1232. * atom size and distances between CPUs.
  1233. *
  1234. * Groups are always mutliples of atom size and CPUs which are of
  1235. * LOCAL_DISTANCE both ways are grouped together and share space for
  1236. * units in the same group. The returned configuration is guaranteed
  1237. * to have CPUs on different nodes on different groups and >=75% usage
  1238. * of allocated virtual address space.
  1239. *
  1240. * RETURNS:
  1241. * On success, pointer to the new allocation_info is returned. On
  1242. * failure, ERR_PTR value is returned.
  1243. */
  1244. static struct pcpu_alloc_info * __init pcpu_build_alloc_info(
  1245. size_t reserved_size, size_t dyn_size,
  1246. size_t atom_size,
  1247. pcpu_fc_cpu_distance_fn_t cpu_distance_fn)
  1248. {
  1249. static int group_map[NR_CPUS] __initdata;
  1250. static int group_cnt[NR_CPUS] __initdata;
  1251. const size_t static_size = __per_cpu_end - __per_cpu_start;
  1252. int nr_groups = 1, nr_units = 0;
  1253. size_t size_sum, min_unit_size, alloc_size;
  1254. int upa, max_upa, uninitialized_var(best_upa); /* units_per_alloc */
  1255. int last_allocs, group, unit;
  1256. unsigned int cpu, tcpu;
  1257. struct pcpu_alloc_info *ai;
  1258. unsigned int *cpu_map;
  1259. /* this function may be called multiple times */
  1260. memset(group_map, 0, sizeof(group_map));
  1261. memset(group_cnt, 0, sizeof(group_cnt));
  1262. /* calculate size_sum and ensure dyn_size is enough for early alloc */
  1263. size_sum = PFN_ALIGN(static_size + reserved_size +
  1264. max_t(size_t, dyn_size, PERCPU_DYNAMIC_EARLY_SIZE));
  1265. dyn_size = size_sum - static_size - reserved_size;
  1266. /*
  1267. * Determine min_unit_size, alloc_size and max_upa such that
  1268. * alloc_size is multiple of atom_size and is the smallest
  1269. * which can accommodate 4k aligned segments which are equal to
  1270. * or larger than min_unit_size.
  1271. */
  1272. min_unit_size = max_t(size_t, size_sum, PCPU_MIN_UNIT_SIZE);
  1273. alloc_size = roundup(min_unit_size, atom_size);
  1274. upa = alloc_size / min_unit_size;
  1275. while (alloc_size % upa || ((alloc_size / upa) & ~PAGE_MASK))
  1276. upa--;
  1277. max_upa = upa;
  1278. /* group cpus according to their proximity */
  1279. for_each_possible_cpu(cpu) {
  1280. group = 0;
  1281. next_group:
  1282. for_each_possible_cpu(tcpu) {
  1283. if (cpu == tcpu)
  1284. break;
  1285. if (group_map[tcpu] == group && cpu_distance_fn &&
  1286. (cpu_distance_fn(cpu, tcpu) > LOCAL_DISTANCE ||
  1287. cpu_distance_fn(tcpu, cpu) > LOCAL_DISTANCE)) {
  1288. group++;
  1289. nr_groups = max(nr_groups, group + 1);
  1290. goto next_group;
  1291. }
  1292. }
  1293. group_map[cpu] = group;
  1294. group_cnt[group]++;
  1295. }
  1296. /*
  1297. * Expand unit size until address space usage goes over 75%
  1298. * and then as much as possible without using more address
  1299. * space.
  1300. */
  1301. last_allocs = INT_MAX;
  1302. for (upa = max_upa; upa; upa--) {
  1303. int allocs = 0, wasted = 0;
  1304. if (alloc_size % upa || ((alloc_size / upa) & ~PAGE_MASK))
  1305. continue;
  1306. for (group = 0; group < nr_groups; group++) {
  1307. int this_allocs = DIV_ROUND_UP(group_cnt[group], upa);
  1308. allocs += this_allocs;
  1309. wasted += this_allocs * upa - group_cnt[group];
  1310. }
  1311. /*
  1312. * Don't accept if wastage is over 1/3. The
  1313. * greater-than comparison ensures upa==1 always
  1314. * passes the following check.
  1315. */
  1316. if (wasted > num_possible_cpus() / 3)
  1317. continue;
  1318. /* and then don't consume more memory */
  1319. if (allocs > last_allocs)
  1320. break;
  1321. last_allocs = allocs;
  1322. best_upa = upa;
  1323. }
  1324. upa = best_upa;
  1325. /* allocate and fill alloc_info */
  1326. for (group = 0; group < nr_groups; group++)
  1327. nr_units += roundup(group_cnt[group], upa);
  1328. ai = pcpu_alloc_alloc_info(nr_groups, nr_units);
  1329. if (!ai)
  1330. return ERR_PTR(-ENOMEM);
  1331. cpu_map = ai->groups[0].cpu_map;
  1332. for (group = 0; group < nr_groups; group++) {
  1333. ai->groups[group].cpu_map = cpu_map;
  1334. cpu_map += roundup(group_cnt[group], upa);
  1335. }
  1336. ai->static_size = static_size;
  1337. ai->reserved_size = reserved_size;
  1338. ai->dyn_size = dyn_size;
  1339. ai->unit_size = alloc_size / upa;
  1340. ai->atom_size = atom_size;
  1341. ai->alloc_size = alloc_size;
  1342. for (group = 0, unit = 0; group_cnt[group]; group++) {
  1343. struct pcpu_group_info *gi = &ai->groups[group];
  1344. /*
  1345. * Initialize base_offset as if all groups are located
  1346. * back-to-back. The caller should update this to
  1347. * reflect actual allocation.
  1348. */
  1349. gi->base_offset = unit * ai->unit_size;
  1350. for_each_possible_cpu(cpu)
  1351. if (group_map[cpu] == group)
  1352. gi->cpu_map[gi->nr_units++] = cpu;
  1353. gi->nr_units = roundup(gi->nr_units, upa);
  1354. unit += gi->nr_units;
  1355. }
  1356. BUG_ON(unit != nr_units);
  1357. return ai;
  1358. }
  1359. #endif /* BUILD_EMBED_FIRST_CHUNK || BUILD_PAGE_FIRST_CHUNK */
  1360. #if defined(BUILD_EMBED_FIRST_CHUNK)
  1361. /**
  1362. * pcpu_embed_first_chunk - embed the first percpu chunk into bootmem
  1363. * @reserved_size: the size of reserved percpu area in bytes
  1364. * @dyn_size: minimum free size for dynamic allocation in bytes
  1365. * @atom_size: allocation atom size
  1366. * @cpu_distance_fn: callback to determine distance between cpus, optional
  1367. * @alloc_fn: function to allocate percpu page
  1368. * @free_fn: function to free percpu page
  1369. *
  1370. * This is a helper to ease setting up embedded first percpu chunk and
  1371. * can be called where pcpu_setup_first_chunk() is expected.
  1372. *
  1373. * If this function is used to setup the first chunk, it is allocated
  1374. * by calling @alloc_fn and used as-is without being mapped into
  1375. * vmalloc area. Allocations are always whole multiples of @atom_size
  1376. * aligned to @atom_size.
  1377. *
  1378. * This enables the first chunk to piggy back on the linear physical
  1379. * mapping which often uses larger page size. Please note that this
  1380. * can result in very sparse cpu->unit mapping on NUMA machines thus
  1381. * requiring large vmalloc address space. Don't use this allocator if
  1382. * vmalloc space is not orders of magnitude larger than distances
  1383. * between node memory addresses (ie. 32bit NUMA machines).
  1384. *
  1385. * @dyn_size specifies the minimum dynamic area size.
  1386. *
  1387. * If the needed size is smaller than the minimum or specified unit
  1388. * size, the leftover is returned using @free_fn.
  1389. *
  1390. * RETURNS:
  1391. * 0 on success, -errno on failure.
  1392. */
  1393. int __init pcpu_embed_first_chunk(size_t reserved_size, size_t dyn_size,
  1394. size_t atom_size,
  1395. pcpu_fc_cpu_distance_fn_t cpu_distance_fn,
  1396. pcpu_fc_alloc_fn_t alloc_fn,
  1397. pcpu_fc_free_fn_t free_fn)
  1398. {
  1399. void *base = (void *)ULONG_MAX;
  1400. void **areas = NULL;
  1401. struct pcpu_alloc_info *ai;
  1402. size_t size_sum, areas_size, max_distance;
  1403. int group, i, rc;
  1404. ai = pcpu_build_alloc_info(reserved_size, dyn_size, atom_size,
  1405. cpu_distance_fn);
  1406. if (IS_ERR(ai))
  1407. return PTR_ERR(ai);
  1408. size_sum = ai->static_size + ai->reserved_size + ai->dyn_size;
  1409. areas_size = PFN_ALIGN(ai->nr_groups * sizeof(void *));
  1410. areas = alloc_bootmem_nopanic(areas_size);
  1411. if (!areas) {
  1412. rc = -ENOMEM;
  1413. goto out_free;
  1414. }
  1415. /* allocate, copy and determine base address */
  1416. for (group = 0; group < ai->nr_groups; group++) {
  1417. struct pcpu_group_info *gi = &ai->groups[group];
  1418. unsigned int cpu = NR_CPUS;
  1419. void *ptr;
  1420. for (i = 0; i < gi->nr_units && cpu == NR_CPUS; i++)
  1421. cpu = gi->cpu_map[i];
  1422. BUG_ON(cpu == NR_CPUS);
  1423. /* allocate space for the whole group */
  1424. ptr = alloc_fn(cpu, gi->nr_units * ai->unit_size, atom_size);
  1425. if (!ptr) {
  1426. rc = -ENOMEM;
  1427. goto out_free_areas;
  1428. }
  1429. areas[group] = ptr;
  1430. base = min(ptr, base);
  1431. for (i = 0; i < gi->nr_units; i++, ptr += ai->unit_size) {
  1432. if (gi->cpu_map[i] == NR_CPUS) {
  1433. /* unused unit, free whole */
  1434. free_fn(ptr, ai->unit_size);
  1435. continue;
  1436. }
  1437. /* copy and return the unused part */
  1438. memcpy(ptr, __per_cpu_load, ai->static_size);
  1439. free_fn(ptr + size_sum, ai->unit_size - size_sum);
  1440. }
  1441. }
  1442. /* base address is now known, determine group base offsets */
  1443. max_distance = 0;
  1444. for (group = 0; group < ai->nr_groups; group++) {
  1445. ai->groups[group].base_offset = areas[group] - base;
  1446. max_distance = max_t(size_t, max_distance,
  1447. ai->groups[group].base_offset);
  1448. }
  1449. max_distance += ai->unit_size;
  1450. /* warn if maximum distance is further than 75% of vmalloc space */
  1451. if (max_distance > (VMALLOC_END - VMALLOC_START) * 3 / 4) {
  1452. pr_warning("PERCPU: max_distance=0x%zx too large for vmalloc "
  1453. "space 0x%lx\n", max_distance,
  1454. (unsigned long)(VMALLOC_END - VMALLOC_START));
  1455. #ifdef CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK
  1456. /* and fail if we have fallback */
  1457. rc = -EINVAL;
  1458. goto out_free;
  1459. #endif
  1460. }
  1461. pr_info("PERCPU: Embedded %zu pages/cpu @%p s%zu r%zu d%zu u%zu\n",
  1462. PFN_DOWN(size_sum), base, ai->static_size, ai->reserved_size,
  1463. ai->dyn_size, ai->unit_size);
  1464. rc = pcpu_setup_first_chunk(ai, base);
  1465. goto out_free;
  1466. out_free_areas:
  1467. for (group = 0; group < ai->nr_groups; group++)
  1468. free_fn(areas[group],
  1469. ai->groups[group].nr_units * ai->unit_size);
  1470. out_free:
  1471. pcpu_free_alloc_info(ai);
  1472. if (areas)
  1473. free_bootmem(__pa(areas), areas_size);
  1474. return rc;
  1475. }
  1476. #endif /* BUILD_EMBED_FIRST_CHUNK */
  1477. #ifdef BUILD_PAGE_FIRST_CHUNK
  1478. /**
  1479. * pcpu_page_first_chunk - map the first chunk using PAGE_SIZE pages
  1480. * @reserved_size: the size of reserved percpu area in bytes
  1481. * @alloc_fn: function to allocate percpu page, always called with PAGE_SIZE
  1482. * @free_fn: function to free percpu page, always called with PAGE_SIZE
  1483. * @populate_pte_fn: function to populate pte
  1484. *
  1485. * This is a helper to ease setting up page-remapped first percpu
  1486. * chunk and can be called where pcpu_setup_first_chunk() is expected.
  1487. *
  1488. * This is the basic allocator. Static percpu area is allocated
  1489. * page-by-page into vmalloc area.
  1490. *
  1491. * RETURNS:
  1492. * 0 on success, -errno on failure.
  1493. */
  1494. int __init pcpu_page_first_chunk(size_t reserved_size,
  1495. pcpu_fc_alloc_fn_t alloc_fn,
  1496. pcpu_fc_free_fn_t free_fn,
  1497. pcpu_fc_populate_pte_fn_t populate_pte_fn)
  1498. {
  1499. static struct vm_struct vm;
  1500. struct pcpu_alloc_info *ai;
  1501. char psize_str[16];
  1502. int unit_pages;
  1503. size_t pages_size;
  1504. struct page **pages;
  1505. int unit, i, j, rc;
  1506. snprintf(psize_str, sizeof(psize_str), "%luK", PAGE_SIZE >> 10);
  1507. ai = pcpu_build_alloc_info(reserved_size, 0, PAGE_SIZE, NULL);
  1508. if (IS_ERR(ai))
  1509. return PTR_ERR(ai);
  1510. BUG_ON(ai->nr_groups != 1);
  1511. BUG_ON(ai->groups[0].nr_units != num_possible_cpus());
  1512. unit_pages = ai->unit_size >> PAGE_SHIFT;
  1513. /* unaligned allocations can't be freed, round up to page size */
  1514. pages_size = PFN_ALIGN(unit_pages * num_possible_cpus() *
  1515. sizeof(pages[0]));
  1516. pages = alloc_bootmem(pages_size);
  1517. /* allocate pages */
  1518. j = 0;
  1519. for (unit = 0; unit < num_possible_cpus(); unit++)
  1520. for (i = 0; i < unit_pages; i++) {
  1521. unsigned int cpu = ai->groups[0].cpu_map[unit];
  1522. void *ptr;
  1523. ptr = alloc_fn(cpu, PAGE_SIZE, PAGE_SIZE);
  1524. if (!ptr) {
  1525. pr_warning("PERCPU: failed to allocate %s page "
  1526. "for cpu%u\n", psize_str, cpu);
  1527. goto enomem;
  1528. }
  1529. pages[j++] = virt_to_page(ptr);
  1530. }
  1531. /* allocate vm area, map the pages and copy static data */
  1532. vm.flags = VM_ALLOC;
  1533. vm.size = num_possible_cpus() * ai->unit_size;
  1534. vm_area_register_early(&vm, PAGE_SIZE);
  1535. for (unit = 0; unit < num_possible_cpus(); unit++) {
  1536. unsigned long unit_addr =
  1537. (unsigned long)vm.addr + unit * ai->unit_size;
  1538. for (i = 0; i < unit_pages; i++)
  1539. populate_pte_fn(unit_addr + (i << PAGE_SHIFT));
  1540. /* pte already populated, the following shouldn't fail */
  1541. rc = __pcpu_map_pages(unit_addr, &pages[unit * unit_pages],
  1542. unit_pages);
  1543. if (rc < 0)
  1544. panic("failed to map percpu area, err=%d\n", rc);
  1545. /*
  1546. * FIXME: Archs with virtual cache should flush local
  1547. * cache for the linear mapping here - something
  1548. * equivalent to flush_cache_vmap() on the local cpu.
  1549. * flush_cache_vmap() can't be used as most supporting
  1550. * data structures are not set up yet.
  1551. */
  1552. /* copy static data */
  1553. memcpy((void *)unit_addr, __per_cpu_load, ai->static_size);
  1554. }
  1555. /* we're ready, commit */
  1556. pr_info("PERCPU: %d %s pages/cpu @%p s%zu r%zu d%zu\n",
  1557. unit_pages, psize_str, vm.addr, ai->static_size,
  1558. ai->reserved_size, ai->dyn_size);
  1559. rc = pcpu_setup_first_chunk(ai, vm.addr);
  1560. goto out_free_ar;
  1561. enomem:
  1562. while (--j >= 0)
  1563. free_fn(page_address(pages[j]), PAGE_SIZE);
  1564. rc = -ENOMEM;
  1565. out_free_ar:
  1566. free_bootmem(__pa(pages), pages_size);
  1567. pcpu_free_alloc_info(ai);
  1568. return rc;
  1569. }
  1570. #endif /* BUILD_PAGE_FIRST_CHUNK */
  1571. #ifndef CONFIG_HAVE_SETUP_PER_CPU_AREA
  1572. /*
  1573. * Generic SMP percpu area setup.
  1574. *
  1575. * The embedding helper is used because its behavior closely resembles
  1576. * the original non-dynamic generic percpu area setup. This is
  1577. * important because many archs have addressing restrictions and might
  1578. * fail if the percpu area is located far away from the previous
  1579. * location. As an added bonus, in non-NUMA cases, embedding is
  1580. * generally a good idea TLB-wise because percpu area can piggy back
  1581. * on the physical linear memory mapping which uses large page
  1582. * mappings on applicable archs.
  1583. */
  1584. unsigned long __per_cpu_offset[NR_CPUS] __read_mostly;
  1585. EXPORT_SYMBOL(__per_cpu_offset);
  1586. static void * __init pcpu_dfl_fc_alloc(unsigned int cpu, size_t size,
  1587. size_t align)
  1588. {
  1589. return __alloc_bootmem_nopanic(size, align, __pa(MAX_DMA_ADDRESS));
  1590. }
  1591. static void __init pcpu_dfl_fc_free(void *ptr, size_t size)
  1592. {
  1593. free_bootmem(__pa(ptr), size);
  1594. }
  1595. void __init setup_per_cpu_areas(void)
  1596. {
  1597. unsigned long delta;
  1598. unsigned int cpu;
  1599. int rc;
  1600. /*
  1601. * Always reserve area for module percpu variables. That's
  1602. * what the legacy allocator did.
  1603. */
  1604. rc = pcpu_embed_first_chunk(PERCPU_MODULE_RESERVE,
  1605. PERCPU_DYNAMIC_RESERVE, PAGE_SIZE, NULL,
  1606. pcpu_dfl_fc_alloc, pcpu_dfl_fc_free);
  1607. if (rc < 0)
  1608. panic("Failed to initialize percpu areas.");
  1609. delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
  1610. for_each_possible_cpu(cpu)
  1611. __per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
  1612. }
  1613. #endif /* CONFIG_HAVE_SETUP_PER_CPU_AREA */
  1614. #else /* CONFIG_SMP */
  1615. /*
  1616. * UP percpu area setup.
  1617. *
  1618. * UP always uses km-based percpu allocator with identity mapping.
  1619. * Static percpu variables are indistinguishable from the usual static
  1620. * variables and don't require any special preparation.
  1621. */
  1622. void __init setup_per_cpu_areas(void)
  1623. {
  1624. const size_t unit_size =
  1625. roundup_pow_of_two(max_t(size_t, PCPU_MIN_UNIT_SIZE,
  1626. PERCPU_DYNAMIC_RESERVE));
  1627. struct pcpu_alloc_info *ai;
  1628. void *fc;
  1629. ai = pcpu_alloc_alloc_info(1, 1);
  1630. fc = __alloc_bootmem(unit_size, PAGE_SIZE, __pa(MAX_DMA_ADDRESS));
  1631. if (!ai || !fc)
  1632. panic("Failed to allocate memory for percpu areas.");
  1633. ai->dyn_size = unit_size;
  1634. ai->unit_size = unit_size;
  1635. ai->atom_size = unit_size;
  1636. ai->alloc_size = unit_size;
  1637. ai->groups[0].nr_units = 1;
  1638. ai->groups[0].cpu_map[0] = 0;
  1639. if (pcpu_setup_first_chunk(ai, fc) < 0)
  1640. panic("Failed to initialize percpu areas.");
  1641. }
  1642. #endif /* CONFIG_SMP */
  1643. /*
  1644. * First and reserved chunks are initialized with temporary allocation
  1645. * map in initdata so that they can be used before slab is online.
  1646. * This function is called after slab is brought up and replaces those
  1647. * with properly allocated maps.
  1648. */
  1649. void __init percpu_init_late(void)
  1650. {
  1651. struct pcpu_chunk *target_chunks[] =
  1652. { pcpu_first_chunk, pcpu_reserved_chunk, NULL };
  1653. struct pcpu_chunk *chunk;
  1654. unsigned long flags;
  1655. int i;
  1656. for (i = 0; (chunk = target_chunks[i]); i++) {
  1657. int *map;
  1658. const size_t size = PERCPU_DYNAMIC_EARLY_SLOTS * sizeof(map[0]);
  1659. BUILD_BUG_ON(size > PAGE_SIZE);
  1660. map = pcpu_mem_alloc(size);
  1661. BUG_ON(!map);
  1662. spin_lock_irqsave(&pcpu_lock, flags);
  1663. memcpy(map, chunk->map, size);
  1664. chunk->map = map;
  1665. spin_unlock_irqrestore(&pcpu_lock, flags);
  1666. }
  1667. }