percpu.c 63 KB

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