7d9bc35e8ed2789ffabab6e2abc6309103497467
[safe/jmp/linux-2.6] / mm / percpu.c
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 num_possible_cpus() units and the first chunk
12  * is used for static percpu variables in the kernel image (special
13  * boot time alloc/init handling necessary as these areas need to be
14  * brought up before allocation services are running).  Unit grows as
15  * necessary and all units grow or shrink in unison.  When a chunk is
16  * filled up, another chunk is allocated.  ie. in vmalloc area
17  *
18  *  c0                           c1                         c2
19  *  -------------------          -------------------        ------------
20  * | u0 | u1 | u2 | u3 |        | u0 | u1 | u2 | u3 |      | u0 | u1 | u
21  *  -------------------  ......  -------------------  ....  ------------
22  *
23  * Allocation is done in offset-size areas of single unit space.  Ie,
24  * an area of 512 bytes at 6k in c1 occupies 512 bytes at 6k of c1:u0,
25  * c1:u1, c1:u2 and c1:u3.  Percpu access can be done by configuring
26  * percpu base registers UNIT_SIZE apart.
27  *
28  * There are usually many small percpu allocations many of them as
29  * small as 4 bytes.  The allocator organizes chunks into lists
30  * according to free size and tries to allocate from the fullest one.
31  * Each chunk keeps the maximum contiguous area size hint which is
32  * guaranteed to be eqaul to or larger than the maximum contiguous
33  * area in the chunk.  This helps the allocator not to iterate the
34  * chunk maps unnecessarily.
35  *
36  * Allocation state in each chunk is kept using an array of integers
37  * on chunk->map.  A positive value in the map represents a free
38  * region and negative allocated.  Allocation inside a chunk is done
39  * by scanning this map sequentially and serving the first matching
40  * entry.  This is mostly copied from the percpu_modalloc() allocator.
41  * Chunks are also linked into a rb tree to ease address to chunk
42  * mapping during free.
43  *
44  * To use this allocator, arch code should do the followings.
45  *
46  * - define CONFIG_HAVE_DYNAMIC_PER_CPU_AREA
47  *
48  * - define __addr_to_pcpu_ptr() and __pcpu_ptr_to_addr() to translate
49  *   regular address to percpu pointer and back
50  *
51  * - use pcpu_setup_first_chunk() during percpu area initialization to
52  *   setup the first chunk containing the kernel static percpu area
53  */
54
55 #include <linux/bitmap.h>
56 #include <linux/bootmem.h>
57 #include <linux/list.h>
58 #include <linux/mm.h>
59 #include <linux/module.h>
60 #include <linux/mutex.h>
61 #include <linux/percpu.h>
62 #include <linux/pfn.h>
63 #include <linux/rbtree.h>
64 #include <linux/slab.h>
65 #include <linux/vmalloc.h>
66
67 #include <asm/cacheflush.h>
68 #include <asm/tlbflush.h>
69
70 #define PCPU_SLOT_BASE_SHIFT            5       /* 1-31 shares the same slot */
71 #define PCPU_DFL_MAP_ALLOC              16      /* start a map with 16 ents */
72
73 struct pcpu_chunk {
74         struct list_head        list;           /* linked to pcpu_slot lists */
75         struct rb_node          rb_node;        /* key is chunk->vm->addr */
76         int                     free_size;      /* free bytes in the chunk */
77         int                     contig_hint;    /* max contiguous size hint */
78         struct vm_struct        *vm;            /* mapped vmalloc region */
79         int                     map_used;       /* # of map entries used */
80         int                     map_alloc;      /* # of map entries allocated */
81         int                     *map;           /* allocation map */
82         bool                    immutable;      /* no [de]population allowed */
83         struct page             **page;         /* points to page array */
84         struct page             *page_ar[];     /* #cpus * UNIT_PAGES */
85 };
86
87 static int pcpu_unit_pages __read_mostly;
88 static int pcpu_unit_size __read_mostly;
89 static int pcpu_chunk_size __read_mostly;
90 static int pcpu_nr_slots __read_mostly;
91 static size_t pcpu_chunk_struct_size __read_mostly;
92
93 /* the address of the first chunk which starts with the kernel static area */
94 void *pcpu_base_addr __read_mostly;
95 EXPORT_SYMBOL_GPL(pcpu_base_addr);
96
97 /* optional reserved chunk, only accessible for reserved allocations */
98 static struct pcpu_chunk *pcpu_reserved_chunk;
99 /* offset limit of the reserved chunk */
100 static int pcpu_reserved_chunk_limit;
101
102 /*
103  * One mutex to rule them all.
104  *
105  * The following mutex is grabbed in the outermost public alloc/free
106  * interface functions and released only when the operation is
107  * complete.  As such, every function in this file other than the
108  * outermost functions are called under pcpu_mutex.
109  *
110  * It can easily be switched to use spinlock such that only the area
111  * allocation and page population commit are protected with it doing
112  * actual [de]allocation without holding any lock.  However, given
113  * what this allocator does, I think it's better to let them run
114  * sequentially.
115  */
116 static DEFINE_MUTEX(pcpu_mutex);
117
118 static struct list_head *pcpu_slot __read_mostly; /* chunk list slots */
119 static struct rb_root pcpu_addr_root = RB_ROOT; /* chunks by address */
120
121 static int __pcpu_size_to_slot(int size)
122 {
123         int highbit = fls(size);        /* size is in bytes */
124         return max(highbit - PCPU_SLOT_BASE_SHIFT + 2, 1);
125 }
126
127 static int pcpu_size_to_slot(int size)
128 {
129         if (size == pcpu_unit_size)
130                 return pcpu_nr_slots - 1;
131         return __pcpu_size_to_slot(size);
132 }
133
134 static int pcpu_chunk_slot(const struct pcpu_chunk *chunk)
135 {
136         if (chunk->free_size < sizeof(int) || chunk->contig_hint < sizeof(int))
137                 return 0;
138
139         return pcpu_size_to_slot(chunk->free_size);
140 }
141
142 static int pcpu_page_idx(unsigned int cpu, int page_idx)
143 {
144         return cpu * pcpu_unit_pages + page_idx;
145 }
146
147 static struct page **pcpu_chunk_pagep(struct pcpu_chunk *chunk,
148                                       unsigned int cpu, int page_idx)
149 {
150         return &chunk->page[pcpu_page_idx(cpu, page_idx)];
151 }
152
153 static unsigned long pcpu_chunk_addr(struct pcpu_chunk *chunk,
154                                      unsigned int cpu, int page_idx)
155 {
156         return (unsigned long)chunk->vm->addr +
157                 (pcpu_page_idx(cpu, page_idx) << PAGE_SHIFT);
158 }
159
160 static bool pcpu_chunk_page_occupied(struct pcpu_chunk *chunk,
161                                      int page_idx)
162 {
163         return *pcpu_chunk_pagep(chunk, 0, page_idx) != NULL;
164 }
165
166 /**
167  * pcpu_mem_alloc - allocate memory
168  * @size: bytes to allocate
169  *
170  * Allocate @size bytes.  If @size is smaller than PAGE_SIZE,
171  * kzalloc() is used; otherwise, vmalloc() is used.  The returned
172  * memory is always zeroed.
173  *
174  * RETURNS:
175  * Pointer to the allocated area on success, NULL on failure.
176  */
177 static void *pcpu_mem_alloc(size_t size)
178 {
179         if (size <= PAGE_SIZE)
180                 return kzalloc(size, GFP_KERNEL);
181         else {
182                 void *ptr = vmalloc(size);
183                 if (ptr)
184                         memset(ptr, 0, size);
185                 return ptr;
186         }
187 }
188
189 /**
190  * pcpu_mem_free - free memory
191  * @ptr: memory to free
192  * @size: size of the area
193  *
194  * Free @ptr.  @ptr should have been allocated using pcpu_mem_alloc().
195  */
196 static void pcpu_mem_free(void *ptr, size_t size)
197 {
198         if (size <= PAGE_SIZE)
199                 kfree(ptr);
200         else
201                 vfree(ptr);
202 }
203
204 /**
205  * pcpu_chunk_relocate - put chunk in the appropriate chunk slot
206  * @chunk: chunk of interest
207  * @oslot: the previous slot it was on
208  *
209  * This function is called after an allocation or free changed @chunk.
210  * New slot according to the changed state is determined and @chunk is
211  * moved to the slot.  Note that the reserved chunk is never put on
212  * chunk slots.
213  */
214 static void pcpu_chunk_relocate(struct pcpu_chunk *chunk, int oslot)
215 {
216         int nslot = pcpu_chunk_slot(chunk);
217
218         if (chunk != pcpu_reserved_chunk && oslot != nslot) {
219                 if (oslot < nslot)
220                         list_move(&chunk->list, &pcpu_slot[nslot]);
221                 else
222                         list_move_tail(&chunk->list, &pcpu_slot[nslot]);
223         }
224 }
225
226 static struct rb_node **pcpu_chunk_rb_search(void *addr,
227                                              struct rb_node **parentp)
228 {
229         struct rb_node **p = &pcpu_addr_root.rb_node;
230         struct rb_node *parent = NULL;
231         struct pcpu_chunk *chunk;
232
233         while (*p) {
234                 parent = *p;
235                 chunk = rb_entry(parent, struct pcpu_chunk, rb_node);
236
237                 if (addr < chunk->vm->addr)
238                         p = &(*p)->rb_left;
239                 else if (addr > chunk->vm->addr)
240                         p = &(*p)->rb_right;
241                 else
242                         break;
243         }
244
245         if (parentp)
246                 *parentp = parent;
247         return p;
248 }
249
250 /**
251  * pcpu_chunk_addr_search - search for chunk containing specified address
252  * @addr: address to search for
253  *
254  * Look for chunk which might contain @addr.  More specifically, it
255  * searchs for the chunk with the highest start address which isn't
256  * beyond @addr.
257  *
258  * RETURNS:
259  * The address of the found chunk.
260  */
261 static struct pcpu_chunk *pcpu_chunk_addr_search(void *addr)
262 {
263         struct rb_node *n, *parent;
264         struct pcpu_chunk *chunk;
265
266         /* is it in the reserved chunk? */
267         if (pcpu_reserved_chunk) {
268                 void *start = pcpu_reserved_chunk->vm->addr;
269
270                 if (addr >= start && addr < start + pcpu_reserved_chunk_limit)
271                         return pcpu_reserved_chunk;
272         }
273
274         /* nah... search the regular ones */
275         n = *pcpu_chunk_rb_search(addr, &parent);
276         if (!n) {
277                 /* no exactly matching chunk, the parent is the closest */
278                 n = parent;
279                 BUG_ON(!n);
280         }
281         chunk = rb_entry(n, struct pcpu_chunk, rb_node);
282
283         if (addr < chunk->vm->addr) {
284                 /* the parent was the next one, look for the previous one */
285                 n = rb_prev(n);
286                 BUG_ON(!n);
287                 chunk = rb_entry(n, struct pcpu_chunk, rb_node);
288         }
289
290         return chunk;
291 }
292
293 /**
294  * pcpu_chunk_addr_insert - insert chunk into address rb tree
295  * @new: chunk to insert
296  *
297  * Insert @new into address rb tree.
298  */
299 static void pcpu_chunk_addr_insert(struct pcpu_chunk *new)
300 {
301         struct rb_node **p, *parent;
302
303         p = pcpu_chunk_rb_search(new->vm->addr, &parent);
304         BUG_ON(*p);
305         rb_link_node(&new->rb_node, parent, p);
306         rb_insert_color(&new->rb_node, &pcpu_addr_root);
307 }
308
309 /**
310  * pcpu_extend_area_map - extend area map for allocation
311  * @chunk: target chunk
312  *
313  * Extend area map of @chunk so that it can accomodate an allocation.
314  * A single allocation can split an area into three areas, so this
315  * function makes sure that @chunk->map has at least two extra slots.
316  *
317  * RETURNS:
318  * 0 if noop, 1 if successfully extended, -errno on failure.
319  */
320 static int pcpu_extend_area_map(struct pcpu_chunk *chunk)
321 {
322         int new_alloc;
323         int *new;
324         size_t size;
325
326         /* has enough? */
327         if (chunk->map_alloc >= chunk->map_used + 2)
328                 return 0;
329
330         new_alloc = PCPU_DFL_MAP_ALLOC;
331         while (new_alloc < chunk->map_used + 2)
332                 new_alloc *= 2;
333
334         new = pcpu_mem_alloc(new_alloc * sizeof(new[0]));
335         if (!new)
336                 return -ENOMEM;
337
338         size = chunk->map_alloc * sizeof(chunk->map[0]);
339         memcpy(new, chunk->map, size);
340
341         /*
342          * map_alloc < PCPU_DFL_MAP_ALLOC indicates that the chunk is
343          * one of the first chunks and still using static map.
344          */
345         if (chunk->map_alloc >= PCPU_DFL_MAP_ALLOC)
346                 pcpu_mem_free(chunk->map, size);
347
348         chunk->map_alloc = new_alloc;
349         chunk->map = new;
350         return 0;
351 }
352
353 /**
354  * pcpu_split_block - split a map block
355  * @chunk: chunk of interest
356  * @i: index of map block to split
357  * @head: head size in bytes (can be 0)
358  * @tail: tail size in bytes (can be 0)
359  *
360  * Split the @i'th map block into two or three blocks.  If @head is
361  * non-zero, @head bytes block is inserted before block @i moving it
362  * to @i+1 and reducing its size by @head bytes.
363  *
364  * If @tail is non-zero, the target block, which can be @i or @i+1
365  * depending on @head, is reduced by @tail bytes and @tail byte block
366  * is inserted after the target block.
367  *
368  * @chunk->map must have enough free slots to accomodate the split.
369  */
370 static void pcpu_split_block(struct pcpu_chunk *chunk, int i,
371                              int head, int tail)
372 {
373         int nr_extra = !!head + !!tail;
374
375         BUG_ON(chunk->map_alloc < chunk->map_used + nr_extra);
376
377         /* insert new subblocks */
378         memmove(&chunk->map[i + nr_extra], &chunk->map[i],
379                 sizeof(chunk->map[0]) * (chunk->map_used - i));
380         chunk->map_used += nr_extra;
381
382         if (head) {
383                 chunk->map[i + 1] = chunk->map[i] - head;
384                 chunk->map[i++] = head;
385         }
386         if (tail) {
387                 chunk->map[i++] -= tail;
388                 chunk->map[i] = tail;
389         }
390 }
391
392 /**
393  * pcpu_alloc_area - allocate area from a pcpu_chunk
394  * @chunk: chunk of interest
395  * @size: wanted size in bytes
396  * @align: wanted align
397  *
398  * Try to allocate @size bytes area aligned at @align from @chunk.
399  * Note that this function only allocates the offset.  It doesn't
400  * populate or map the area.
401  *
402  * @chunk->map must have at least two free slots.
403  *
404  * RETURNS:
405  * Allocated offset in @chunk on success, -1 if no matching area is
406  * found.
407  */
408 static int pcpu_alloc_area(struct pcpu_chunk *chunk, int size, int align)
409 {
410         int oslot = pcpu_chunk_slot(chunk);
411         int max_contig = 0;
412         int i, off;
413
414         for (i = 0, off = 0; i < chunk->map_used; off += abs(chunk->map[i++])) {
415                 bool is_last = i + 1 == chunk->map_used;
416                 int head, tail;
417
418                 /* extra for alignment requirement */
419                 head = ALIGN(off, align) - off;
420                 BUG_ON(i == 0 && head != 0);
421
422                 if (chunk->map[i] < 0)
423                         continue;
424                 if (chunk->map[i] < head + size) {
425                         max_contig = max(chunk->map[i], max_contig);
426                         continue;
427                 }
428
429                 /*
430                  * If head is small or the previous block is free,
431                  * merge'em.  Note that 'small' is defined as smaller
432                  * than sizeof(int), which is very small but isn't too
433                  * uncommon for percpu allocations.
434                  */
435                 if (head && (head < sizeof(int) || chunk->map[i - 1] > 0)) {
436                         if (chunk->map[i - 1] > 0)
437                                 chunk->map[i - 1] += head;
438                         else {
439                                 chunk->map[i - 1] -= head;
440                                 chunk->free_size -= head;
441                         }
442                         chunk->map[i] -= head;
443                         off += head;
444                         head = 0;
445                 }
446
447                 /* if tail is small, just keep it around */
448                 tail = chunk->map[i] - head - size;
449                 if (tail < sizeof(int))
450                         tail = 0;
451
452                 /* split if warranted */
453                 if (head || tail) {
454                         pcpu_split_block(chunk, i, head, tail);
455                         if (head) {
456                                 i++;
457                                 off += head;
458                                 max_contig = max(chunk->map[i - 1], max_contig);
459                         }
460                         if (tail)
461                                 max_contig = max(chunk->map[i + 1], max_contig);
462                 }
463
464                 /* update hint and mark allocated */
465                 if (is_last)
466                         chunk->contig_hint = max_contig; /* fully scanned */
467                 else
468                         chunk->contig_hint = max(chunk->contig_hint,
469                                                  max_contig);
470
471                 chunk->free_size -= chunk->map[i];
472                 chunk->map[i] = -chunk->map[i];
473
474                 pcpu_chunk_relocate(chunk, oslot);
475                 return off;
476         }
477
478         chunk->contig_hint = max_contig;        /* fully scanned */
479         pcpu_chunk_relocate(chunk, oslot);
480
481         /* tell the upper layer that this chunk has no matching area */
482         return -1;
483 }
484
485 /**
486  * pcpu_free_area - free area to a pcpu_chunk
487  * @chunk: chunk of interest
488  * @freeme: offset of area to free
489  *
490  * Free area starting from @freeme to @chunk.  Note that this function
491  * only modifies the allocation map.  It doesn't depopulate or unmap
492  * the area.
493  */
494 static void pcpu_free_area(struct pcpu_chunk *chunk, int freeme)
495 {
496         int oslot = pcpu_chunk_slot(chunk);
497         int i, off;
498
499         for (i = 0, off = 0; i < chunk->map_used; off += abs(chunk->map[i++]))
500                 if (off == freeme)
501                         break;
502         BUG_ON(off != freeme);
503         BUG_ON(chunk->map[i] > 0);
504
505         chunk->map[i] = -chunk->map[i];
506         chunk->free_size += chunk->map[i];
507
508         /* merge with previous? */
509         if (i > 0 && chunk->map[i - 1] >= 0) {
510                 chunk->map[i - 1] += chunk->map[i];
511                 chunk->map_used--;
512                 memmove(&chunk->map[i], &chunk->map[i + 1],
513                         (chunk->map_used - i) * sizeof(chunk->map[0]));
514                 i--;
515         }
516         /* merge with next? */
517         if (i + 1 < chunk->map_used && chunk->map[i + 1] >= 0) {
518                 chunk->map[i] += chunk->map[i + 1];
519                 chunk->map_used--;
520                 memmove(&chunk->map[i + 1], &chunk->map[i + 2],
521                         (chunk->map_used - (i + 1)) * sizeof(chunk->map[0]));
522         }
523
524         chunk->contig_hint = max(chunk->map[i], chunk->contig_hint);
525         pcpu_chunk_relocate(chunk, oslot);
526 }
527
528 /**
529  * pcpu_unmap - unmap pages out of a pcpu_chunk
530  * @chunk: chunk of interest
531  * @page_start: page index of the first page to unmap
532  * @page_end: page index of the last page to unmap + 1
533  * @flush: whether to flush cache and tlb or not
534  *
535  * For each cpu, unmap pages [@page_start,@page_end) out of @chunk.
536  * If @flush is true, vcache is flushed before unmapping and tlb
537  * after.
538  */
539 static void pcpu_unmap(struct pcpu_chunk *chunk, int page_start, int page_end,
540                        bool flush)
541 {
542         unsigned int last = num_possible_cpus() - 1;
543         unsigned int cpu;
544
545         /* unmap must not be done on immutable chunk */
546         WARN_ON(chunk->immutable);
547
548         /*
549          * Each flushing trial can be very expensive, issue flush on
550          * the whole region at once rather than doing it for each cpu.
551          * This could be an overkill but is more scalable.
552          */
553         if (flush)
554                 flush_cache_vunmap(pcpu_chunk_addr(chunk, 0, page_start),
555                                    pcpu_chunk_addr(chunk, last, page_end));
556
557         for_each_possible_cpu(cpu)
558                 unmap_kernel_range_noflush(
559                                 pcpu_chunk_addr(chunk, cpu, page_start),
560                                 (page_end - page_start) << PAGE_SHIFT);
561
562         /* ditto as flush_cache_vunmap() */
563         if (flush)
564                 flush_tlb_kernel_range(pcpu_chunk_addr(chunk, 0, page_start),
565                                        pcpu_chunk_addr(chunk, last, page_end));
566 }
567
568 /**
569  * pcpu_depopulate_chunk - depopulate and unmap an area of a pcpu_chunk
570  * @chunk: chunk to depopulate
571  * @off: offset to the area to depopulate
572  * @size: size of the area to depopulate in bytes
573  * @flush: whether to flush cache and tlb or not
574  *
575  * For each cpu, depopulate and unmap pages [@page_start,@page_end)
576  * from @chunk.  If @flush is true, vcache is flushed before unmapping
577  * and tlb after.
578  */
579 static void pcpu_depopulate_chunk(struct pcpu_chunk *chunk, int off, int size,
580                                   bool flush)
581 {
582         int page_start = PFN_DOWN(off);
583         int page_end = PFN_UP(off + size);
584         int unmap_start = -1;
585         int uninitialized_var(unmap_end);
586         unsigned int cpu;
587         int i;
588
589         for (i = page_start; i < page_end; i++) {
590                 for_each_possible_cpu(cpu) {
591                         struct page **pagep = pcpu_chunk_pagep(chunk, cpu, i);
592
593                         if (!*pagep)
594                                 continue;
595
596                         __free_page(*pagep);
597
598                         /*
599                          * If it's partial depopulation, it might get
600                          * populated or depopulated again.  Mark the
601                          * page gone.
602                          */
603                         *pagep = NULL;
604
605                         unmap_start = unmap_start < 0 ? i : unmap_start;
606                         unmap_end = i + 1;
607                 }
608         }
609
610         if (unmap_start >= 0)
611                 pcpu_unmap(chunk, unmap_start, unmap_end, flush);
612 }
613
614 /**
615  * pcpu_map - map pages into a pcpu_chunk
616  * @chunk: chunk of interest
617  * @page_start: page index of the first page to map
618  * @page_end: page index of the last page to map + 1
619  *
620  * For each cpu, map pages [@page_start,@page_end) into @chunk.
621  * vcache is flushed afterwards.
622  */
623 static int pcpu_map(struct pcpu_chunk *chunk, int page_start, int page_end)
624 {
625         unsigned int last = num_possible_cpus() - 1;
626         unsigned int cpu;
627         int err;
628
629         /* map must not be done on immutable chunk */
630         WARN_ON(chunk->immutable);
631
632         for_each_possible_cpu(cpu) {
633                 err = map_kernel_range_noflush(
634                                 pcpu_chunk_addr(chunk, cpu, page_start),
635                                 (page_end - page_start) << PAGE_SHIFT,
636                                 PAGE_KERNEL,
637                                 pcpu_chunk_pagep(chunk, cpu, page_start));
638                 if (err < 0)
639                         return err;
640         }
641
642         /* flush at once, please read comments in pcpu_unmap() */
643         flush_cache_vmap(pcpu_chunk_addr(chunk, 0, page_start),
644                          pcpu_chunk_addr(chunk, last, page_end));
645         return 0;
646 }
647
648 /**
649  * pcpu_populate_chunk - populate and map an area of a pcpu_chunk
650  * @chunk: chunk of interest
651  * @off: offset to the area to populate
652  * @size: size of the area to populate in bytes
653  *
654  * For each cpu, populate and map pages [@page_start,@page_end) into
655  * @chunk.  The area is cleared on return.
656  */
657 static int pcpu_populate_chunk(struct pcpu_chunk *chunk, int off, int size)
658 {
659         const gfp_t alloc_mask = GFP_KERNEL | __GFP_HIGHMEM | __GFP_COLD;
660         int page_start = PFN_DOWN(off);
661         int page_end = PFN_UP(off + size);
662         int map_start = -1;
663         int uninitialized_var(map_end);
664         unsigned int cpu;
665         int i;
666
667         for (i = page_start; i < page_end; i++) {
668                 if (pcpu_chunk_page_occupied(chunk, i)) {
669                         if (map_start >= 0) {
670                                 if (pcpu_map(chunk, map_start, map_end))
671                                         goto err;
672                                 map_start = -1;
673                         }
674                         continue;
675                 }
676
677                 map_start = map_start < 0 ? i : map_start;
678                 map_end = i + 1;
679
680                 for_each_possible_cpu(cpu) {
681                         struct page **pagep = pcpu_chunk_pagep(chunk, cpu, i);
682
683                         *pagep = alloc_pages_node(cpu_to_node(cpu),
684                                                   alloc_mask, 0);
685                         if (!*pagep)
686                                 goto err;
687                 }
688         }
689
690         if (map_start >= 0 && pcpu_map(chunk, map_start, map_end))
691                 goto err;
692
693         for_each_possible_cpu(cpu)
694                 memset(chunk->vm->addr + cpu * pcpu_unit_size + off, 0,
695                        size);
696
697         return 0;
698 err:
699         /* likely under heavy memory pressure, give memory back */
700         pcpu_depopulate_chunk(chunk, off, size, true);
701         return -ENOMEM;
702 }
703
704 static void free_pcpu_chunk(struct pcpu_chunk *chunk)
705 {
706         if (!chunk)
707                 return;
708         if (chunk->vm)
709                 free_vm_area(chunk->vm);
710         pcpu_mem_free(chunk->map, chunk->map_alloc * sizeof(chunk->map[0]));
711         kfree(chunk);
712 }
713
714 static struct pcpu_chunk *alloc_pcpu_chunk(void)
715 {
716         struct pcpu_chunk *chunk;
717
718         chunk = kzalloc(pcpu_chunk_struct_size, GFP_KERNEL);
719         if (!chunk)
720                 return NULL;
721
722         chunk->map = pcpu_mem_alloc(PCPU_DFL_MAP_ALLOC * sizeof(chunk->map[0]));
723         chunk->map_alloc = PCPU_DFL_MAP_ALLOC;
724         chunk->map[chunk->map_used++] = pcpu_unit_size;
725         chunk->page = chunk->page_ar;
726
727         chunk->vm = get_vm_area(pcpu_chunk_size, GFP_KERNEL);
728         if (!chunk->vm) {
729                 free_pcpu_chunk(chunk);
730                 return NULL;
731         }
732
733         INIT_LIST_HEAD(&chunk->list);
734         chunk->free_size = pcpu_unit_size;
735         chunk->contig_hint = pcpu_unit_size;
736
737         return chunk;
738 }
739
740 /**
741  * pcpu_alloc - the percpu allocator
742  * @size: size of area to allocate in bytes
743  * @align: alignment of area (max PAGE_SIZE)
744  * @reserved: allocate from the reserved chunk if available
745  *
746  * Allocate percpu area of @size bytes aligned at @align.  Might
747  * sleep.  Might trigger writeouts.
748  *
749  * RETURNS:
750  * Percpu pointer to the allocated area on success, NULL on failure.
751  */
752 static void *pcpu_alloc(size_t size, size_t align, bool reserved)
753 {
754         void *ptr = NULL;
755         struct pcpu_chunk *chunk;
756         int slot, off;
757
758         if (unlikely(!size || size > PCPU_MIN_UNIT_SIZE || align > PAGE_SIZE)) {
759                 WARN(true, "illegal size (%zu) or align (%zu) for "
760                      "percpu allocation\n", size, align);
761                 return NULL;
762         }
763
764         mutex_lock(&pcpu_mutex);
765
766         /* serve reserved allocations from the reserved chunk if available */
767         if (reserved && pcpu_reserved_chunk) {
768                 chunk = pcpu_reserved_chunk;
769                 if (size > chunk->contig_hint ||
770                     pcpu_extend_area_map(chunk) < 0)
771                         goto out_unlock;
772                 off = pcpu_alloc_area(chunk, size, align);
773                 if (off >= 0)
774                         goto area_found;
775                 goto out_unlock;
776         }
777
778         /* search through normal chunks */
779         for (slot = pcpu_size_to_slot(size); slot < pcpu_nr_slots; slot++) {
780                 list_for_each_entry(chunk, &pcpu_slot[slot], list) {
781                         if (size > chunk->contig_hint)
782                                 continue;
783                         if (pcpu_extend_area_map(chunk) < 0)
784                                 goto out_unlock;
785                         off = pcpu_alloc_area(chunk, size, align);
786                         if (off >= 0)
787                                 goto area_found;
788                 }
789         }
790
791         /* hmmm... no space left, create a new chunk */
792         chunk = alloc_pcpu_chunk();
793         if (!chunk)
794                 goto out_unlock;
795         pcpu_chunk_relocate(chunk, -1);
796         pcpu_chunk_addr_insert(chunk);
797
798         off = pcpu_alloc_area(chunk, size, align);
799         if (off < 0)
800                 goto out_unlock;
801
802 area_found:
803         /* populate, map and clear the area */
804         if (pcpu_populate_chunk(chunk, off, size)) {
805                 pcpu_free_area(chunk, off);
806                 goto out_unlock;
807         }
808
809         ptr = __addr_to_pcpu_ptr(chunk->vm->addr + off);
810 out_unlock:
811         mutex_unlock(&pcpu_mutex);
812         return ptr;
813 }
814
815 /**
816  * __alloc_percpu - allocate dynamic percpu area
817  * @size: size of area to allocate in bytes
818  * @align: alignment of area (max PAGE_SIZE)
819  *
820  * Allocate percpu area of @size bytes aligned at @align.  Might
821  * sleep.  Might trigger writeouts.
822  *
823  * RETURNS:
824  * Percpu pointer to the allocated area on success, NULL on failure.
825  */
826 void *__alloc_percpu(size_t size, size_t align)
827 {
828         return pcpu_alloc(size, align, false);
829 }
830 EXPORT_SYMBOL_GPL(__alloc_percpu);
831
832 /**
833  * __alloc_reserved_percpu - allocate reserved percpu area
834  * @size: size of area to allocate in bytes
835  * @align: alignment of area (max PAGE_SIZE)
836  *
837  * Allocate percpu area of @size bytes aligned at @align from reserved
838  * percpu area if arch has set it up; otherwise, allocation is served
839  * from the same dynamic area.  Might sleep.  Might trigger writeouts.
840  *
841  * RETURNS:
842  * Percpu pointer to the allocated area on success, NULL on failure.
843  */
844 void *__alloc_reserved_percpu(size_t size, size_t align)
845 {
846         return pcpu_alloc(size, align, true);
847 }
848
849 static void pcpu_kill_chunk(struct pcpu_chunk *chunk)
850 {
851         WARN_ON(chunk->immutable);
852         pcpu_depopulate_chunk(chunk, 0, pcpu_unit_size, false);
853         list_del(&chunk->list);
854         rb_erase(&chunk->rb_node, &pcpu_addr_root);
855         free_pcpu_chunk(chunk);
856 }
857
858 /**
859  * free_percpu - free percpu area
860  * @ptr: pointer to area to free
861  *
862  * Free percpu area @ptr.  Might sleep.
863  */
864 void free_percpu(void *ptr)
865 {
866         void *addr = __pcpu_ptr_to_addr(ptr);
867         struct pcpu_chunk *chunk;
868         int off;
869
870         if (!ptr)
871                 return;
872
873         mutex_lock(&pcpu_mutex);
874
875         chunk = pcpu_chunk_addr_search(addr);
876         off = addr - chunk->vm->addr;
877
878         pcpu_free_area(chunk, off);
879
880         /* the chunk became fully free, kill one if there are other free ones */
881         if (chunk->free_size == pcpu_unit_size) {
882                 struct pcpu_chunk *pos;
883
884                 list_for_each_entry(pos,
885                                     &pcpu_slot[pcpu_chunk_slot(chunk)], list)
886                         if (pos != chunk) {
887                                 pcpu_kill_chunk(pos);
888                                 break;
889                         }
890         }
891
892         mutex_unlock(&pcpu_mutex);
893 }
894 EXPORT_SYMBOL_GPL(free_percpu);
895
896 /**
897  * pcpu_setup_first_chunk - initialize the first percpu chunk
898  * @get_page_fn: callback to fetch page pointer
899  * @static_size: the size of static percpu area in bytes
900  * @reserved_size: the size of reserved percpu area in bytes
901  * @unit_size: unit size in bytes, must be multiple of PAGE_SIZE, -1 for auto
902  * @dyn_size: free size for dynamic allocation in bytes, -1 for auto
903  * @base_addr: mapped address, NULL for auto
904  * @populate_pte_fn: callback to allocate pagetable, NULL if unnecessary
905  *
906  * Initialize the first percpu chunk which contains the kernel static
907  * perpcu area.  This function is to be called from arch percpu area
908  * setup path.  The first two parameters are mandatory.  The rest are
909  * optional.
910  *
911  * @get_page_fn() should return pointer to percpu page given cpu
912  * number and page number.  It should at least return enough pages to
913  * cover the static area.  The returned pages for static area should
914  * have been initialized with valid data.  If @unit_size is specified,
915  * it can also return pages after the static area.  NULL return
916  * indicates end of pages for the cpu.  Note that @get_page_fn() must
917  * return the same number of pages for all cpus.
918  *
919  * @reserved_size, if non-zero, specifies the amount of bytes to
920  * reserve after the static area in the first chunk.  This reserves
921  * the first chunk such that it's available only through reserved
922  * percpu allocation.  This is primarily used to serve module percpu
923  * static areas on architectures where the addressing model has
924  * limited offset range for symbol relocations to guarantee module
925  * percpu symbols fall inside the relocatable range.
926  *
927  * @unit_size, if non-negative, specifies unit size and must be
928  * aligned to PAGE_SIZE and equal to or larger than @static_size +
929  * @reserved_size + @dyn_size.
930  *
931  * @dyn_size, if non-negative, limits the number of bytes available
932  * for dynamic allocation in the first chunk.  Specifying non-negative
933  * value make percpu leave alone the area beyond @static_size +
934  * @reserved_size + @dyn_size.
935  *
936  * Non-null @base_addr means that the caller already allocated virtual
937  * region for the first chunk and mapped it.  percpu must not mess
938  * with the chunk.  Note that @base_addr with 0 @unit_size or non-NULL
939  * @populate_pte_fn doesn't make any sense.
940  *
941  * @populate_pte_fn is used to populate the pagetable.  NULL means the
942  * caller already populated the pagetable.
943  *
944  * If the first chunk ends up with both reserved and dynamic areas, it
945  * is served by two chunks - one to serve the core static and reserved
946  * areas and the other for the dynamic area.  They share the same vm
947  * and page map but uses different area allocation map to stay away
948  * from each other.  The latter chunk is circulated in the chunk slots
949  * and available for dynamic allocation like any other chunks.
950  *
951  * RETURNS:
952  * The determined pcpu_unit_size which can be used to initialize
953  * percpu access.
954  */
955 size_t __init pcpu_setup_first_chunk(pcpu_get_page_fn_t get_page_fn,
956                                      size_t static_size, size_t reserved_size,
957                                      ssize_t unit_size, ssize_t dyn_size,
958                                      void *base_addr,
959                                      pcpu_populate_pte_fn_t populate_pte_fn)
960 {
961         static struct vm_struct first_vm;
962         static int smap[2], dmap[2];
963         struct pcpu_chunk *schunk, *dchunk = NULL;
964         unsigned int cpu;
965         int nr_pages;
966         int err, i;
967
968         /* santiy checks */
969         BUILD_BUG_ON(ARRAY_SIZE(smap) >= PCPU_DFL_MAP_ALLOC ||
970                      ARRAY_SIZE(dmap) >= PCPU_DFL_MAP_ALLOC);
971         BUG_ON(!static_size);
972         if (unit_size >= 0) {
973                 BUG_ON(unit_size < static_size + reserved_size +
974                                    (dyn_size >= 0 ? dyn_size : 0));
975                 BUG_ON(unit_size & ~PAGE_MASK);
976         } else {
977                 BUG_ON(dyn_size >= 0);
978                 BUG_ON(base_addr);
979         }
980         BUG_ON(base_addr && populate_pte_fn);
981
982         if (unit_size >= 0)
983                 pcpu_unit_pages = unit_size >> PAGE_SHIFT;
984         else
985                 pcpu_unit_pages = max_t(int, PCPU_MIN_UNIT_SIZE >> PAGE_SHIFT,
986                                         PFN_UP(static_size + reserved_size));
987
988         pcpu_unit_size = pcpu_unit_pages << PAGE_SHIFT;
989         pcpu_chunk_size = num_possible_cpus() * pcpu_unit_size;
990         pcpu_chunk_struct_size = sizeof(struct pcpu_chunk)
991                 + num_possible_cpus() * pcpu_unit_pages * sizeof(struct page *);
992
993         if (dyn_size < 0)
994                 dyn_size = pcpu_unit_size - static_size - reserved_size;
995
996         /*
997          * Allocate chunk slots.  The additional last slot is for
998          * empty chunks.
999          */
1000         pcpu_nr_slots = __pcpu_size_to_slot(pcpu_unit_size) + 2;
1001         pcpu_slot = alloc_bootmem(pcpu_nr_slots * sizeof(pcpu_slot[0]));
1002         for (i = 0; i < pcpu_nr_slots; i++)
1003                 INIT_LIST_HEAD(&pcpu_slot[i]);
1004
1005         /*
1006          * Initialize static chunk.  If reserved_size is zero, the
1007          * static chunk covers static area + dynamic allocation area
1008          * in the first chunk.  If reserved_size is not zero, it
1009          * covers static area + reserved area (mostly used for module
1010          * static percpu allocation).
1011          */
1012         schunk = alloc_bootmem(pcpu_chunk_struct_size);
1013         INIT_LIST_HEAD(&schunk->list);
1014         schunk->vm = &first_vm;
1015         schunk->map = smap;
1016         schunk->map_alloc = ARRAY_SIZE(smap);
1017         schunk->page = schunk->page_ar;
1018
1019         if (reserved_size) {
1020                 schunk->free_size = reserved_size;
1021                 pcpu_reserved_chunk = schunk;   /* not for dynamic alloc */
1022         } else {
1023                 schunk->free_size = dyn_size;
1024                 dyn_size = 0;                   /* dynamic area covered */
1025         }
1026         schunk->contig_hint = schunk->free_size;
1027
1028         schunk->map[schunk->map_used++] = -static_size;
1029         if (schunk->free_size)
1030                 schunk->map[schunk->map_used++] = schunk->free_size;
1031
1032         pcpu_reserved_chunk_limit = static_size + schunk->free_size;
1033
1034         /* init dynamic chunk if necessary */
1035         if (dyn_size) {
1036                 dchunk = alloc_bootmem(sizeof(struct pcpu_chunk));
1037                 INIT_LIST_HEAD(&dchunk->list);
1038                 dchunk->vm = &first_vm;
1039                 dchunk->map = dmap;
1040                 dchunk->map_alloc = ARRAY_SIZE(dmap);
1041                 dchunk->page = schunk->page_ar; /* share page map with schunk */
1042
1043                 dchunk->contig_hint = dchunk->free_size = dyn_size;
1044                 dchunk->map[dchunk->map_used++] = -pcpu_reserved_chunk_limit;
1045                 dchunk->map[dchunk->map_used++] = dchunk->free_size;
1046         }
1047
1048         /* allocate vm address */
1049         first_vm.flags = VM_ALLOC;
1050         first_vm.size = pcpu_chunk_size;
1051
1052         if (!base_addr)
1053                 vm_area_register_early(&first_vm, PAGE_SIZE);
1054         else {
1055                 /*
1056                  * Pages already mapped.  No need to remap into
1057                  * vmalloc area.  In this case the first chunks can't
1058                  * be mapped or unmapped by percpu and are marked
1059                  * immutable.
1060                  */
1061                 first_vm.addr = base_addr;
1062                 schunk->immutable = true;
1063                 if (dchunk)
1064                         dchunk->immutable = true;
1065         }
1066
1067         /* assign pages */
1068         nr_pages = -1;
1069         for_each_possible_cpu(cpu) {
1070                 for (i = 0; i < pcpu_unit_pages; i++) {
1071                         struct page *page = get_page_fn(cpu, i);
1072
1073                         if (!page)
1074                                 break;
1075                         *pcpu_chunk_pagep(schunk, cpu, i) = page;
1076                 }
1077
1078                 BUG_ON(i < PFN_UP(static_size));
1079
1080                 if (nr_pages < 0)
1081                         nr_pages = i;
1082                 else
1083                         BUG_ON(nr_pages != i);
1084         }
1085
1086         /* map them */
1087         if (populate_pte_fn) {
1088                 for_each_possible_cpu(cpu)
1089                         for (i = 0; i < nr_pages; i++)
1090                                 populate_pte_fn(pcpu_chunk_addr(schunk,
1091                                                                 cpu, i));
1092
1093                 err = pcpu_map(schunk, 0, nr_pages);
1094                 if (err)
1095                         panic("failed to setup static percpu area, err=%d\n",
1096                               err);
1097         }
1098
1099         /* link the first chunk in */
1100         if (!dchunk) {
1101                 pcpu_chunk_relocate(schunk, -1);
1102                 pcpu_chunk_addr_insert(schunk);
1103         } else {
1104                 pcpu_chunk_relocate(dchunk, -1);
1105                 pcpu_chunk_addr_insert(dchunk);
1106         }
1107
1108         /* we're done */
1109         pcpu_base_addr = (void *)pcpu_chunk_addr(schunk, 0, 0);
1110         return pcpu_unit_size;
1111 }