percpu.c 55 KB

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