percpu.c 57 KB

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