percpu.c 56 KB

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