percpu.c 59 KB

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