percpu.c 62 KB

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