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