percpu.c 63 KB

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