percpu.c 63 KB

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