]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame_incremental - mm/zsmalloc.c
zsmalloc: introduce zspage structure
[mirror_ubuntu-artful-kernel.git] / mm / zsmalloc.c
... / ...
CommitLineData
1/*
2 * zsmalloc memory allocator
3 *
4 * Copyright (C) 2011 Nitin Gupta
5 * Copyright (C) 2012, 2013 Minchan Kim
6 *
7 * This code is released using a dual license strategy: BSD/GPL
8 * You can choose the license that better fits your requirements.
9 *
10 * Released under the terms of 3-clause BSD License
11 * Released under the terms of GNU General Public License Version 2.0
12 */
13
14/*
15 * Following is how we use various fields and flags of underlying
16 * struct page(s) to form a zspage.
17 *
18 * Usage of struct page fields:
19 * page->private: points to zspage
20 * page->index: offset of the first object starting in this page.
21 * For the first page, this is always 0, so we use this field
22 * to store handle for huge object.
23 * page->next: links together all component pages of a zspage
24 *
25 * Usage of struct page flags:
26 * PG_private: identifies the first component page
27 * PG_private2: identifies the last component page
28 *
29 */
30
31#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
32
33#include <linux/module.h>
34#include <linux/kernel.h>
35#include <linux/sched.h>
36#include <linux/bitops.h>
37#include <linux/errno.h>
38#include <linux/highmem.h>
39#include <linux/string.h>
40#include <linux/slab.h>
41#include <asm/tlbflush.h>
42#include <asm/pgtable.h>
43#include <linux/cpumask.h>
44#include <linux/cpu.h>
45#include <linux/vmalloc.h>
46#include <linux/preempt.h>
47#include <linux/spinlock.h>
48#include <linux/types.h>
49#include <linux/debugfs.h>
50#include <linux/zsmalloc.h>
51#include <linux/zpool.h>
52
53/*
54 * This must be power of 2 and greater than of equal to sizeof(link_free).
55 * These two conditions ensure that any 'struct link_free' itself doesn't
56 * span more than 1 page which avoids complex case of mapping 2 pages simply
57 * to restore link_free pointer values.
58 */
59#define ZS_ALIGN 8
60
61/*
62 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
63 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
64 */
65#define ZS_MAX_ZSPAGE_ORDER 2
66#define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
67
68#define ZS_HANDLE_SIZE (sizeof(unsigned long))
69
70/*
71 * Object location (<PFN>, <obj_idx>) is encoded as
72 * as single (unsigned long) handle value.
73 *
74 * Note that object index <obj_idx> is relative to system
75 * page <PFN> it is stored in, so for each sub-page belonging
76 * to a zspage, obj_idx starts with 0.
77 *
78 * This is made more complicated by various memory models and PAE.
79 */
80
81#ifndef MAX_PHYSMEM_BITS
82#ifdef CONFIG_HIGHMEM64G
83#define MAX_PHYSMEM_BITS 36
84#else /* !CONFIG_HIGHMEM64G */
85/*
86 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
87 * be PAGE_SHIFT
88 */
89#define MAX_PHYSMEM_BITS BITS_PER_LONG
90#endif
91#endif
92#define _PFN_BITS (MAX_PHYSMEM_BITS - PAGE_SHIFT)
93
94/*
95 * Memory for allocating for handle keeps object position by
96 * encoding <page, obj_idx> and the encoded value has a room
97 * in least bit(ie, look at obj_to_location).
98 * We use the bit to synchronize between object access by
99 * user and migration.
100 */
101#define HANDLE_PIN_BIT 0
102
103/*
104 * Head in allocated object should have OBJ_ALLOCATED_TAG
105 * to identify the object was allocated or not.
106 * It's okay to add the status bit in the least bit because
107 * header keeps handle which is 4byte-aligned address so we
108 * have room for two bit at least.
109 */
110#define OBJ_ALLOCATED_TAG 1
111#define OBJ_TAG_BITS 1
112#define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
113#define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
114
115#define MAX(a, b) ((a) >= (b) ? (a) : (b))
116/* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
117#define ZS_MIN_ALLOC_SIZE \
118 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
119/* each chunk includes extra space to keep handle */
120#define ZS_MAX_ALLOC_SIZE PAGE_SIZE
121
122/*
123 * On systems with 4K page size, this gives 255 size classes! There is a
124 * trader-off here:
125 * - Large number of size classes is potentially wasteful as free page are
126 * spread across these classes
127 * - Small number of size classes causes large internal fragmentation
128 * - Probably its better to use specific size classes (empirically
129 * determined). NOTE: all those class sizes must be set as multiple of
130 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
131 *
132 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
133 * (reason above)
134 */
135#define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS)
136
137/*
138 * We do not maintain any list for completely empty or full pages
139 */
140enum fullness_group {
141 ZS_ALMOST_FULL,
142 ZS_ALMOST_EMPTY,
143 ZS_EMPTY,
144 ZS_FULL
145};
146
147enum zs_stat_type {
148 OBJ_ALLOCATED,
149 OBJ_USED,
150 CLASS_ALMOST_FULL,
151 CLASS_ALMOST_EMPTY,
152};
153
154#ifdef CONFIG_ZSMALLOC_STAT
155#define NR_ZS_STAT_TYPE (CLASS_ALMOST_EMPTY + 1)
156#else
157#define NR_ZS_STAT_TYPE (OBJ_USED + 1)
158#endif
159
160struct zs_size_stat {
161 unsigned long objs[NR_ZS_STAT_TYPE];
162};
163
164#ifdef CONFIG_ZSMALLOC_STAT
165static struct dentry *zs_stat_root;
166#endif
167
168/*
169 * number of size_classes
170 */
171static int zs_size_classes;
172
173/*
174 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
175 * n <= N / f, where
176 * n = number of allocated objects
177 * N = total number of objects zspage can store
178 * f = fullness_threshold_frac
179 *
180 * Similarly, we assign zspage to:
181 * ZS_ALMOST_FULL when n > N / f
182 * ZS_EMPTY when n == 0
183 * ZS_FULL when n == N
184 *
185 * (see: fix_fullness_group())
186 */
187static const int fullness_threshold_frac = 4;
188
189struct size_class {
190 spinlock_t lock;
191 struct list_head fullness_list[2];
192 /*
193 * Size of objects stored in this class. Must be multiple
194 * of ZS_ALIGN.
195 */
196 int size;
197 int objs_per_zspage;
198 unsigned int index;
199
200 struct zs_size_stat stats;
201
202 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
203 int pages_per_zspage;
204 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
205 bool huge;
206};
207
208/*
209 * Placed within free objects to form a singly linked list.
210 * For every zspage, zspage->freeobj gives head of this list.
211 *
212 * This must be power of 2 and less than or equal to ZS_ALIGN
213 */
214struct link_free {
215 union {
216 /*
217 * Position of next free chunk (encodes <PFN, obj_idx>)
218 * It's valid for non-allocated object
219 */
220 void *next;
221 /*
222 * Handle of allocated object.
223 */
224 unsigned long handle;
225 };
226};
227
228struct zs_pool {
229 const char *name;
230
231 struct size_class **size_class;
232 struct kmem_cache *handle_cachep;
233 struct kmem_cache *zspage_cachep;
234
235 atomic_long_t pages_allocated;
236
237 struct zs_pool_stats stats;
238
239 /* Compact classes */
240 struct shrinker shrinker;
241 /*
242 * To signify that register_shrinker() was successful
243 * and unregister_shrinker() will not Oops.
244 */
245 bool shrinker_enabled;
246#ifdef CONFIG_ZSMALLOC_STAT
247 struct dentry *stat_dentry;
248#endif
249};
250
251/*
252 * A zspage's class index and fullness group
253 * are encoded in its (first)page->mapping
254 */
255#define FULLNESS_BITS 2
256#define CLASS_BITS 8
257
258struct zspage {
259 struct {
260 unsigned int fullness:FULLNESS_BITS;
261 unsigned int class:CLASS_BITS;
262 };
263 unsigned int inuse;
264 void *freeobj;
265 struct page *first_page;
266 struct list_head list; /* fullness list */
267};
268
269struct mapping_area {
270#ifdef CONFIG_PGTABLE_MAPPING
271 struct vm_struct *vm; /* vm area for mapping object that span pages */
272#else
273 char *vm_buf; /* copy buffer for objects that span pages */
274#endif
275 char *vm_addr; /* address of kmap_atomic()'ed pages */
276 enum zs_mapmode vm_mm; /* mapping mode */
277};
278
279static int create_cache(struct zs_pool *pool)
280{
281 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
282 0, 0, NULL);
283 if (!pool->handle_cachep)
284 return 1;
285
286 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
287 0, 0, NULL);
288 if (!pool->zspage_cachep) {
289 kmem_cache_destroy(pool->handle_cachep);
290 pool->handle_cachep = NULL;
291 return 1;
292 }
293
294 return 0;
295}
296
297static void destroy_cache(struct zs_pool *pool)
298{
299 kmem_cache_destroy(pool->handle_cachep);
300 kmem_cache_destroy(pool->zspage_cachep);
301}
302
303static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
304{
305 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
306 gfp & ~__GFP_HIGHMEM);
307}
308
309static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
310{
311 kmem_cache_free(pool->handle_cachep, (void *)handle);
312}
313
314static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
315{
316 return kmem_cache_alloc(pool->zspage_cachep, flags & ~__GFP_HIGHMEM);
317};
318
319static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
320{
321 kmem_cache_free(pool->zspage_cachep, zspage);
322}
323
324static void record_obj(unsigned long handle, unsigned long obj)
325{
326 /*
327 * lsb of @obj represents handle lock while other bits
328 * represent object value the handle is pointing so
329 * updating shouldn't do store tearing.
330 */
331 WRITE_ONCE(*(unsigned long *)handle, obj);
332}
333
334/* zpool driver */
335
336#ifdef CONFIG_ZPOOL
337
338static void *zs_zpool_create(const char *name, gfp_t gfp,
339 const struct zpool_ops *zpool_ops,
340 struct zpool *zpool)
341{
342 /*
343 * Ignore global gfp flags: zs_malloc() may be invoked from
344 * different contexts and its caller must provide a valid
345 * gfp mask.
346 */
347 return zs_create_pool(name);
348}
349
350static void zs_zpool_destroy(void *pool)
351{
352 zs_destroy_pool(pool);
353}
354
355static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
356 unsigned long *handle)
357{
358 *handle = zs_malloc(pool, size, gfp);
359 return *handle ? 0 : -1;
360}
361static void zs_zpool_free(void *pool, unsigned long handle)
362{
363 zs_free(pool, handle);
364}
365
366static int zs_zpool_shrink(void *pool, unsigned int pages,
367 unsigned int *reclaimed)
368{
369 return -EINVAL;
370}
371
372static void *zs_zpool_map(void *pool, unsigned long handle,
373 enum zpool_mapmode mm)
374{
375 enum zs_mapmode zs_mm;
376
377 switch (mm) {
378 case ZPOOL_MM_RO:
379 zs_mm = ZS_MM_RO;
380 break;
381 case ZPOOL_MM_WO:
382 zs_mm = ZS_MM_WO;
383 break;
384 case ZPOOL_MM_RW: /* fallthru */
385 default:
386 zs_mm = ZS_MM_RW;
387 break;
388 }
389
390 return zs_map_object(pool, handle, zs_mm);
391}
392static void zs_zpool_unmap(void *pool, unsigned long handle)
393{
394 zs_unmap_object(pool, handle);
395}
396
397static u64 zs_zpool_total_size(void *pool)
398{
399 return zs_get_total_pages(pool) << PAGE_SHIFT;
400}
401
402static struct zpool_driver zs_zpool_driver = {
403 .type = "zsmalloc",
404 .owner = THIS_MODULE,
405 .create = zs_zpool_create,
406 .destroy = zs_zpool_destroy,
407 .malloc = zs_zpool_malloc,
408 .free = zs_zpool_free,
409 .shrink = zs_zpool_shrink,
410 .map = zs_zpool_map,
411 .unmap = zs_zpool_unmap,
412 .total_size = zs_zpool_total_size,
413};
414
415MODULE_ALIAS("zpool-zsmalloc");
416#endif /* CONFIG_ZPOOL */
417
418static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
419{
420 return pages_per_zspage * PAGE_SIZE / size;
421}
422
423/* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
424static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
425
426static int is_first_page(struct page *page)
427{
428 return PagePrivate(page);
429}
430
431static inline int get_zspage_inuse(struct zspage *zspage)
432{
433 return zspage->inuse;
434}
435
436static inline void set_zspage_inuse(struct zspage *zspage, int val)
437{
438 zspage->inuse = val;
439}
440
441static inline void mod_zspage_inuse(struct zspage *zspage, int val)
442{
443 zspage->inuse += val;
444}
445
446static inline int get_first_obj_offset(struct page *page)
447{
448 if (is_first_page(page))
449 return 0;
450
451 return page->index;
452}
453
454static inline void set_first_obj_offset(struct page *page, int offset)
455{
456 if (is_first_page(page))
457 return;
458
459 page->index = offset;
460}
461
462static inline unsigned long get_freeobj(struct zspage *zspage)
463{
464 return (unsigned long)zspage->freeobj;
465}
466
467static inline void set_freeobj(struct zspage *zspage, unsigned long obj)
468{
469 zspage->freeobj = (void *)obj;
470}
471
472static void get_zspage_mapping(struct zspage *zspage,
473 unsigned int *class_idx,
474 enum fullness_group *fullness)
475{
476 *fullness = zspage->fullness;
477 *class_idx = zspage->class;
478}
479
480static void set_zspage_mapping(struct zspage *zspage,
481 unsigned int class_idx,
482 enum fullness_group fullness)
483{
484 zspage->class = class_idx;
485 zspage->fullness = fullness;
486}
487
488/*
489 * zsmalloc divides the pool into various size classes where each
490 * class maintains a list of zspages where each zspage is divided
491 * into equal sized chunks. Each allocation falls into one of these
492 * classes depending on its size. This function returns index of the
493 * size class which has chunk size big enough to hold the give size.
494 */
495static int get_size_class_index(int size)
496{
497 int idx = 0;
498
499 if (likely(size > ZS_MIN_ALLOC_SIZE))
500 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
501 ZS_SIZE_CLASS_DELTA);
502
503 return min(zs_size_classes - 1, idx);
504}
505
506static inline void zs_stat_inc(struct size_class *class,
507 enum zs_stat_type type, unsigned long cnt)
508{
509 if (type < NR_ZS_STAT_TYPE)
510 class->stats.objs[type] += cnt;
511}
512
513static inline void zs_stat_dec(struct size_class *class,
514 enum zs_stat_type type, unsigned long cnt)
515{
516 if (type < NR_ZS_STAT_TYPE)
517 class->stats.objs[type] -= cnt;
518}
519
520static inline unsigned long zs_stat_get(struct size_class *class,
521 enum zs_stat_type type)
522{
523 if (type < NR_ZS_STAT_TYPE)
524 return class->stats.objs[type];
525 return 0;
526}
527
528#ifdef CONFIG_ZSMALLOC_STAT
529
530static void __init zs_stat_init(void)
531{
532 if (!debugfs_initialized()) {
533 pr_warn("debugfs not available, stat dir not created\n");
534 return;
535 }
536
537 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
538 if (!zs_stat_root)
539 pr_warn("debugfs 'zsmalloc' stat dir creation failed\n");
540}
541
542static void __exit zs_stat_exit(void)
543{
544 debugfs_remove_recursive(zs_stat_root);
545}
546
547static unsigned long zs_can_compact(struct size_class *class);
548
549static int zs_stats_size_show(struct seq_file *s, void *v)
550{
551 int i;
552 struct zs_pool *pool = s->private;
553 struct size_class *class;
554 int objs_per_zspage;
555 unsigned long class_almost_full, class_almost_empty;
556 unsigned long obj_allocated, obj_used, pages_used, freeable;
557 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
558 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
559 unsigned long total_freeable = 0;
560
561 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
562 "class", "size", "almost_full", "almost_empty",
563 "obj_allocated", "obj_used", "pages_used",
564 "pages_per_zspage", "freeable");
565
566 for (i = 0; i < zs_size_classes; i++) {
567 class = pool->size_class[i];
568
569 if (class->index != i)
570 continue;
571
572 spin_lock(&class->lock);
573 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
574 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
575 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
576 obj_used = zs_stat_get(class, OBJ_USED);
577 freeable = zs_can_compact(class);
578 spin_unlock(&class->lock);
579
580 objs_per_zspage = get_maxobj_per_zspage(class->size,
581 class->pages_per_zspage);
582 pages_used = obj_allocated / objs_per_zspage *
583 class->pages_per_zspage;
584
585 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
586 " %10lu %10lu %16d %8lu\n",
587 i, class->size, class_almost_full, class_almost_empty,
588 obj_allocated, obj_used, pages_used,
589 class->pages_per_zspage, freeable);
590
591 total_class_almost_full += class_almost_full;
592 total_class_almost_empty += class_almost_empty;
593 total_objs += obj_allocated;
594 total_used_objs += obj_used;
595 total_pages += pages_used;
596 total_freeable += freeable;
597 }
598
599 seq_puts(s, "\n");
600 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
601 "Total", "", total_class_almost_full,
602 total_class_almost_empty, total_objs,
603 total_used_objs, total_pages, "", total_freeable);
604
605 return 0;
606}
607
608static int zs_stats_size_open(struct inode *inode, struct file *file)
609{
610 return single_open(file, zs_stats_size_show, inode->i_private);
611}
612
613static const struct file_operations zs_stat_size_ops = {
614 .open = zs_stats_size_open,
615 .read = seq_read,
616 .llseek = seq_lseek,
617 .release = single_release,
618};
619
620static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
621{
622 struct dentry *entry;
623
624 if (!zs_stat_root) {
625 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
626 return;
627 }
628
629 entry = debugfs_create_dir(name, zs_stat_root);
630 if (!entry) {
631 pr_warn("debugfs dir <%s> creation failed\n", name);
632 return;
633 }
634 pool->stat_dentry = entry;
635
636 entry = debugfs_create_file("classes", S_IFREG | S_IRUGO,
637 pool->stat_dentry, pool, &zs_stat_size_ops);
638 if (!entry) {
639 pr_warn("%s: debugfs file entry <%s> creation failed\n",
640 name, "classes");
641 debugfs_remove_recursive(pool->stat_dentry);
642 pool->stat_dentry = NULL;
643 }
644}
645
646static void zs_pool_stat_destroy(struct zs_pool *pool)
647{
648 debugfs_remove_recursive(pool->stat_dentry);
649}
650
651#else /* CONFIG_ZSMALLOC_STAT */
652static void __init zs_stat_init(void)
653{
654}
655
656static void __exit zs_stat_exit(void)
657{
658}
659
660static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
661{
662}
663
664static inline void zs_pool_stat_destroy(struct zs_pool *pool)
665{
666}
667#endif
668
669/*
670 * For each size class, zspages are divided into different groups
671 * depending on how "full" they are. This was done so that we could
672 * easily find empty or nearly empty zspages when we try to shrink
673 * the pool (not yet implemented). This function returns fullness
674 * status of the given page.
675 */
676static enum fullness_group get_fullness_group(struct size_class *class,
677 struct zspage *zspage)
678{
679 int inuse, objs_per_zspage;
680 enum fullness_group fg;
681
682 inuse = get_zspage_inuse(zspage);
683 objs_per_zspage = class->objs_per_zspage;
684
685 if (inuse == 0)
686 fg = ZS_EMPTY;
687 else if (inuse == objs_per_zspage)
688 fg = ZS_FULL;
689 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
690 fg = ZS_ALMOST_EMPTY;
691 else
692 fg = ZS_ALMOST_FULL;
693
694 return fg;
695}
696
697/*
698 * Each size class maintains various freelists and zspages are assigned
699 * to one of these freelists based on the number of live objects they
700 * have. This functions inserts the given zspage into the freelist
701 * identified by <class, fullness_group>.
702 */
703static void insert_zspage(struct size_class *class,
704 struct zspage *zspage,
705 enum fullness_group fullness)
706{
707 struct zspage *head;
708
709 if (fullness >= ZS_EMPTY)
710 return;
711
712 head = list_first_entry_or_null(&class->fullness_list[fullness],
713 struct zspage, list);
714
715 zs_stat_inc(class, fullness == ZS_ALMOST_EMPTY ?
716 CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1);
717
718 /*
719 * We want to see more ZS_FULL pages and less almost empty/full.
720 * Put pages with higher ->inuse first.
721 */
722 if (head) {
723 if (get_zspage_inuse(zspage) < get_zspage_inuse(head)) {
724 list_add(&zspage->list, &head->list);
725 return;
726 }
727 }
728 list_add(&zspage->list, &class->fullness_list[fullness]);
729}
730
731/*
732 * This function removes the given zspage from the freelist identified
733 * by <class, fullness_group>.
734 */
735static void remove_zspage(struct size_class *class,
736 struct zspage *zspage,
737 enum fullness_group fullness)
738{
739 if (fullness >= ZS_EMPTY)
740 return;
741
742 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
743
744 list_del_init(&zspage->list);
745 zs_stat_dec(class, fullness == ZS_ALMOST_EMPTY ?
746 CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1);
747}
748
749/*
750 * Each size class maintains zspages in different fullness groups depending
751 * on the number of live objects they contain. When allocating or freeing
752 * objects, the fullness status of the page can change, say, from ALMOST_FULL
753 * to ALMOST_EMPTY when freeing an object. This function checks if such
754 * a status change has occurred for the given page and accordingly moves the
755 * page from the freelist of the old fullness group to that of the new
756 * fullness group.
757 */
758static enum fullness_group fix_fullness_group(struct size_class *class,
759 struct zspage *zspage)
760{
761 int class_idx;
762 enum fullness_group currfg, newfg;
763
764 get_zspage_mapping(zspage, &class_idx, &currfg);
765 newfg = get_fullness_group(class, zspage);
766 if (newfg == currfg)
767 goto out;
768
769 remove_zspage(class, zspage, currfg);
770 insert_zspage(class, zspage, newfg);
771 set_zspage_mapping(zspage, class_idx, newfg);
772
773out:
774 return newfg;
775}
776
777/*
778 * We have to decide on how many pages to link together
779 * to form a zspage for each size class. This is important
780 * to reduce wastage due to unusable space left at end of
781 * each zspage which is given as:
782 * wastage = Zp % class_size
783 * usage = Zp - wastage
784 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
785 *
786 * For example, for size class of 3/8 * PAGE_SIZE, we should
787 * link together 3 PAGE_SIZE sized pages to form a zspage
788 * since then we can perfectly fit in 8 such objects.
789 */
790static int get_pages_per_zspage(int class_size)
791{
792 int i, max_usedpc = 0;
793 /* zspage order which gives maximum used size per KB */
794 int max_usedpc_order = 1;
795
796 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
797 int zspage_size;
798 int waste, usedpc;
799
800 zspage_size = i * PAGE_SIZE;
801 waste = zspage_size % class_size;
802 usedpc = (zspage_size - waste) * 100 / zspage_size;
803
804 if (usedpc > max_usedpc) {
805 max_usedpc = usedpc;
806 max_usedpc_order = i;
807 }
808 }
809
810 return max_usedpc_order;
811}
812
813
814static struct zspage *get_zspage(struct page *page)
815{
816 return (struct zspage *)page->private;
817}
818
819static struct page *get_next_page(struct page *page)
820{
821 return page->next;
822}
823
824/*
825 * Encode <page, obj_idx> as a single handle value.
826 * We use the least bit of handle for tagging.
827 */
828static void *location_to_obj(struct page *page, unsigned long obj_idx)
829{
830 unsigned long obj;
831
832 if (!page) {
833 VM_BUG_ON(obj_idx);
834 return NULL;
835 }
836
837 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
838 obj |= ((obj_idx) & OBJ_INDEX_MASK);
839 obj <<= OBJ_TAG_BITS;
840
841 return (void *)obj;
842}
843
844/*
845 * Decode <page, obj_idx> pair from the given object handle. We adjust the
846 * decoded obj_idx back to its original value since it was adjusted in
847 * location_to_obj().
848 */
849static void obj_to_location(unsigned long obj, struct page **page,
850 unsigned long *obj_idx)
851{
852 obj >>= OBJ_TAG_BITS;
853 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
854 *obj_idx = (obj & OBJ_INDEX_MASK);
855}
856
857static unsigned long handle_to_obj(unsigned long handle)
858{
859 return *(unsigned long *)handle;
860}
861
862static unsigned long obj_to_head(struct size_class *class, struct page *page,
863 void *obj)
864{
865 if (class->huge) {
866 VM_BUG_ON_PAGE(!is_first_page(page), page);
867 return page->index;
868 } else
869 return *(unsigned long *)obj;
870}
871
872static unsigned long obj_idx_to_offset(struct page *page,
873 unsigned long obj_idx, int class_size)
874{
875 unsigned long off;
876
877 off = get_first_obj_offset(page);
878
879 return off + obj_idx * class_size;
880}
881
882static inline int trypin_tag(unsigned long handle)
883{
884 return bit_spin_trylock(HANDLE_PIN_BIT, (unsigned long *)handle);
885}
886
887static void pin_tag(unsigned long handle)
888{
889 bit_spin_lock(HANDLE_PIN_BIT, (unsigned long *)handle);
890}
891
892static void unpin_tag(unsigned long handle)
893{
894 bit_spin_unlock(HANDLE_PIN_BIT, (unsigned long *)handle);
895}
896
897static void reset_page(struct page *page)
898{
899 clear_bit(PG_private, &page->flags);
900 clear_bit(PG_private_2, &page->flags);
901 set_page_private(page, 0);
902 page->index = 0;
903}
904
905static void free_zspage(struct zs_pool *pool, struct zspage *zspage)
906{
907 struct page *page, *next;
908
909 VM_BUG_ON(get_zspage_inuse(zspage));
910
911 next = page = zspage->first_page;
912 do {
913 next = page->next;
914 reset_page(page);
915 put_page(page);
916 page = next;
917 } while (page != NULL);
918
919 cache_free_zspage(pool, zspage);
920}
921
922/* Initialize a newly allocated zspage */
923static void init_zspage(struct size_class *class, struct zspage *zspage)
924{
925 unsigned long off = 0;
926 struct page *page = zspage->first_page;
927
928 while (page) {
929 struct page *next_page;
930 struct link_free *link;
931 unsigned int i = 1;
932 void *vaddr;
933
934 set_first_obj_offset(page, off);
935
936 vaddr = kmap_atomic(page);
937 link = (struct link_free *)vaddr + off / sizeof(*link);
938
939 while ((off += class->size) < PAGE_SIZE) {
940 link->next = location_to_obj(page, i++);
941 link += class->size / sizeof(*link);
942 }
943
944 /*
945 * We now come to the last (full or partial) object on this
946 * page, which must point to the first object on the next
947 * page (if present)
948 */
949 next_page = get_next_page(page);
950 link->next = location_to_obj(next_page, 0);
951 kunmap_atomic(vaddr);
952 page = next_page;
953 off %= PAGE_SIZE;
954 }
955
956 set_freeobj(zspage,
957 (unsigned long)location_to_obj(zspage->first_page, 0));
958}
959
960static void create_page_chain(struct zspage *zspage, struct page *pages[],
961 int nr_pages)
962{
963 int i;
964 struct page *page;
965 struct page *prev_page = NULL;
966
967 /*
968 * Allocate individual pages and link them together as:
969 * 1. all pages are linked together using page->next
970 * 2. each sub-page point to zspage using page->private
971 *
972 * we set PG_private to identify the first page (i.e. no other sub-page
973 * has this flag set) and PG_private_2 to identify the last page.
974 */
975 for (i = 0; i < nr_pages; i++) {
976 page = pages[i];
977 set_page_private(page, (unsigned long)zspage);
978 if (i == 0) {
979 zspage->first_page = page;
980 SetPagePrivate(page);
981 } else {
982 prev_page->next = page;
983 }
984 if (i == nr_pages - 1) {
985 SetPagePrivate2(page);
986 page->next = NULL;
987 }
988 prev_page = page;
989 }
990}
991
992/*
993 * Allocate a zspage for the given size class
994 */
995static struct zspage *alloc_zspage(struct zs_pool *pool,
996 struct size_class *class,
997 gfp_t gfp)
998{
999 int i;
1000 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1001 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1002
1003 if (!zspage)
1004 return NULL;
1005
1006 memset(zspage, 0, sizeof(struct zspage));
1007
1008 for (i = 0; i < class->pages_per_zspage; i++) {
1009 struct page *page;
1010
1011 page = alloc_page(gfp);
1012 if (!page) {
1013 while (--i >= 0)
1014 __free_page(pages[i]);
1015 cache_free_zspage(pool, zspage);
1016 return NULL;
1017 }
1018 pages[i] = page;
1019 }
1020
1021 create_page_chain(zspage, pages, class->pages_per_zspage);
1022 init_zspage(class, zspage);
1023
1024 return zspage;
1025}
1026
1027static struct zspage *find_get_zspage(struct size_class *class)
1028{
1029 int i;
1030 struct zspage *zspage;
1031
1032 for (i = ZS_ALMOST_FULL; i <= ZS_ALMOST_EMPTY; i++) {
1033 zspage = list_first_entry_or_null(&class->fullness_list[i],
1034 struct zspage, list);
1035 if (zspage)
1036 break;
1037 }
1038
1039 return zspage;
1040}
1041
1042#ifdef CONFIG_PGTABLE_MAPPING
1043static inline int __zs_cpu_up(struct mapping_area *area)
1044{
1045 /*
1046 * Make sure we don't leak memory if a cpu UP notification
1047 * and zs_init() race and both call zs_cpu_up() on the same cpu
1048 */
1049 if (area->vm)
1050 return 0;
1051 area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
1052 if (!area->vm)
1053 return -ENOMEM;
1054 return 0;
1055}
1056
1057static inline void __zs_cpu_down(struct mapping_area *area)
1058{
1059 if (area->vm)
1060 free_vm_area(area->vm);
1061 area->vm = NULL;
1062}
1063
1064static inline void *__zs_map_object(struct mapping_area *area,
1065 struct page *pages[2], int off, int size)
1066{
1067 BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1068 area->vm_addr = area->vm->addr;
1069 return area->vm_addr + off;
1070}
1071
1072static inline void __zs_unmap_object(struct mapping_area *area,
1073 struct page *pages[2], int off, int size)
1074{
1075 unsigned long addr = (unsigned long)area->vm_addr;
1076
1077 unmap_kernel_range(addr, PAGE_SIZE * 2);
1078}
1079
1080#else /* CONFIG_PGTABLE_MAPPING */
1081
1082static inline int __zs_cpu_up(struct mapping_area *area)
1083{
1084 /*
1085 * Make sure we don't leak memory if a cpu UP notification
1086 * and zs_init() race and both call zs_cpu_up() on the same cpu
1087 */
1088 if (area->vm_buf)
1089 return 0;
1090 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1091 if (!area->vm_buf)
1092 return -ENOMEM;
1093 return 0;
1094}
1095
1096static inline void __zs_cpu_down(struct mapping_area *area)
1097{
1098 kfree(area->vm_buf);
1099 area->vm_buf = NULL;
1100}
1101
1102static void *__zs_map_object(struct mapping_area *area,
1103 struct page *pages[2], int off, int size)
1104{
1105 int sizes[2];
1106 void *addr;
1107 char *buf = area->vm_buf;
1108
1109 /* disable page faults to match kmap_atomic() return conditions */
1110 pagefault_disable();
1111
1112 /* no read fastpath */
1113 if (area->vm_mm == ZS_MM_WO)
1114 goto out;
1115
1116 sizes[0] = PAGE_SIZE - off;
1117 sizes[1] = size - sizes[0];
1118
1119 /* copy object to per-cpu buffer */
1120 addr = kmap_atomic(pages[0]);
1121 memcpy(buf, addr + off, sizes[0]);
1122 kunmap_atomic(addr);
1123 addr = kmap_atomic(pages[1]);
1124 memcpy(buf + sizes[0], addr, sizes[1]);
1125 kunmap_atomic(addr);
1126out:
1127 return area->vm_buf;
1128}
1129
1130static void __zs_unmap_object(struct mapping_area *area,
1131 struct page *pages[2], int off, int size)
1132{
1133 int sizes[2];
1134 void *addr;
1135 char *buf;
1136
1137 /* no write fastpath */
1138 if (area->vm_mm == ZS_MM_RO)
1139 goto out;
1140
1141 buf = area->vm_buf;
1142 buf = buf + ZS_HANDLE_SIZE;
1143 size -= ZS_HANDLE_SIZE;
1144 off += ZS_HANDLE_SIZE;
1145
1146 sizes[0] = PAGE_SIZE - off;
1147 sizes[1] = size - sizes[0];
1148
1149 /* copy per-cpu buffer to object */
1150 addr = kmap_atomic(pages[0]);
1151 memcpy(addr + off, buf, sizes[0]);
1152 kunmap_atomic(addr);
1153 addr = kmap_atomic(pages[1]);
1154 memcpy(addr, buf + sizes[0], sizes[1]);
1155 kunmap_atomic(addr);
1156
1157out:
1158 /* enable page faults to match kunmap_atomic() return conditions */
1159 pagefault_enable();
1160}
1161
1162#endif /* CONFIG_PGTABLE_MAPPING */
1163
1164static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
1165 void *pcpu)
1166{
1167 int ret, cpu = (long)pcpu;
1168 struct mapping_area *area;
1169
1170 switch (action) {
1171 case CPU_UP_PREPARE:
1172 area = &per_cpu(zs_map_area, cpu);
1173 ret = __zs_cpu_up(area);
1174 if (ret)
1175 return notifier_from_errno(ret);
1176 break;
1177 case CPU_DEAD:
1178 case CPU_UP_CANCELED:
1179 area = &per_cpu(zs_map_area, cpu);
1180 __zs_cpu_down(area);
1181 break;
1182 }
1183
1184 return NOTIFY_OK;
1185}
1186
1187static struct notifier_block zs_cpu_nb = {
1188 .notifier_call = zs_cpu_notifier
1189};
1190
1191static int zs_register_cpu_notifier(void)
1192{
1193 int cpu, uninitialized_var(ret);
1194
1195 cpu_notifier_register_begin();
1196
1197 __register_cpu_notifier(&zs_cpu_nb);
1198 for_each_online_cpu(cpu) {
1199 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
1200 if (notifier_to_errno(ret))
1201 break;
1202 }
1203
1204 cpu_notifier_register_done();
1205 return notifier_to_errno(ret);
1206}
1207
1208static void zs_unregister_cpu_notifier(void)
1209{
1210 int cpu;
1211
1212 cpu_notifier_register_begin();
1213
1214 for_each_online_cpu(cpu)
1215 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
1216 __unregister_cpu_notifier(&zs_cpu_nb);
1217
1218 cpu_notifier_register_done();
1219}
1220
1221static void init_zs_size_classes(void)
1222{
1223 int nr;
1224
1225 nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
1226 if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
1227 nr += 1;
1228
1229 zs_size_classes = nr;
1230}
1231
1232static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
1233{
1234 if (prev->pages_per_zspage != pages_per_zspage)
1235 return false;
1236
1237 if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
1238 != get_maxobj_per_zspage(size, pages_per_zspage))
1239 return false;
1240
1241 return true;
1242}
1243
1244static bool zspage_full(struct size_class *class, struct zspage *zspage)
1245{
1246 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1247}
1248
1249unsigned long zs_get_total_pages(struct zs_pool *pool)
1250{
1251 return atomic_long_read(&pool->pages_allocated);
1252}
1253EXPORT_SYMBOL_GPL(zs_get_total_pages);
1254
1255/**
1256 * zs_map_object - get address of allocated object from handle.
1257 * @pool: pool from which the object was allocated
1258 * @handle: handle returned from zs_malloc
1259 *
1260 * Before using an object allocated from zs_malloc, it must be mapped using
1261 * this function. When done with the object, it must be unmapped using
1262 * zs_unmap_object.
1263 *
1264 * Only one object can be mapped per cpu at a time. There is no protection
1265 * against nested mappings.
1266 *
1267 * This function returns with preemption and page faults disabled.
1268 */
1269void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1270 enum zs_mapmode mm)
1271{
1272 struct zspage *zspage;
1273 struct page *page;
1274 unsigned long obj, obj_idx, off;
1275
1276 unsigned int class_idx;
1277 enum fullness_group fg;
1278 struct size_class *class;
1279 struct mapping_area *area;
1280 struct page *pages[2];
1281 void *ret;
1282
1283 /*
1284 * Because we use per-cpu mapping areas shared among the
1285 * pools/users, we can't allow mapping in interrupt context
1286 * because it can corrupt another users mappings.
1287 */
1288 WARN_ON_ONCE(in_interrupt());
1289
1290 /* From now on, migration cannot move the object */
1291 pin_tag(handle);
1292
1293 obj = handle_to_obj(handle);
1294 obj_to_location(obj, &page, &obj_idx);
1295 zspage = get_zspage(page);
1296 get_zspage_mapping(zspage, &class_idx, &fg);
1297 class = pool->size_class[class_idx];
1298 off = obj_idx_to_offset(page, obj_idx, class->size);
1299
1300 area = &get_cpu_var(zs_map_area);
1301 area->vm_mm = mm;
1302 if (off + class->size <= PAGE_SIZE) {
1303 /* this object is contained entirely within a page */
1304 area->vm_addr = kmap_atomic(page);
1305 ret = area->vm_addr + off;
1306 goto out;
1307 }
1308
1309 /* this object spans two pages */
1310 pages[0] = page;
1311 pages[1] = get_next_page(page);
1312 BUG_ON(!pages[1]);
1313
1314 ret = __zs_map_object(area, pages, off, class->size);
1315out:
1316 if (!class->huge)
1317 ret += ZS_HANDLE_SIZE;
1318
1319 return ret;
1320}
1321EXPORT_SYMBOL_GPL(zs_map_object);
1322
1323void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1324{
1325 struct zspage *zspage;
1326 struct page *page;
1327 unsigned long obj, obj_idx, off;
1328
1329 unsigned int class_idx;
1330 enum fullness_group fg;
1331 struct size_class *class;
1332 struct mapping_area *area;
1333
1334 obj = handle_to_obj(handle);
1335 obj_to_location(obj, &page, &obj_idx);
1336 zspage = get_zspage(page);
1337 get_zspage_mapping(zspage, &class_idx, &fg);
1338 class = pool->size_class[class_idx];
1339 off = obj_idx_to_offset(page, obj_idx, class->size);
1340
1341 area = this_cpu_ptr(&zs_map_area);
1342 if (off + class->size <= PAGE_SIZE)
1343 kunmap_atomic(area->vm_addr);
1344 else {
1345 struct page *pages[2];
1346
1347 pages[0] = page;
1348 pages[1] = get_next_page(page);
1349 BUG_ON(!pages[1]);
1350
1351 __zs_unmap_object(area, pages, off, class->size);
1352 }
1353 put_cpu_var(zs_map_area);
1354 unpin_tag(handle);
1355}
1356EXPORT_SYMBOL_GPL(zs_unmap_object);
1357
1358static unsigned long obj_malloc(struct size_class *class,
1359 struct zspage *zspage, unsigned long handle)
1360{
1361 unsigned long obj;
1362 struct link_free *link;
1363
1364 struct page *m_page;
1365 unsigned long m_objidx, m_offset;
1366 void *vaddr;
1367
1368 handle |= OBJ_ALLOCATED_TAG;
1369 obj = get_freeobj(zspage);
1370 obj_to_location(obj, &m_page, &m_objidx);
1371 m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
1372
1373 vaddr = kmap_atomic(m_page);
1374 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1375 set_freeobj(zspage, (unsigned long)link->next);
1376 if (!class->huge)
1377 /* record handle in the header of allocated chunk */
1378 link->handle = handle;
1379 else
1380 /* record handle to page->index */
1381 zspage->first_page->index = handle;
1382
1383 kunmap_atomic(vaddr);
1384 mod_zspage_inuse(zspage, 1);
1385 zs_stat_inc(class, OBJ_USED, 1);
1386
1387 return obj;
1388}
1389
1390
1391/**
1392 * zs_malloc - Allocate block of given size from pool.
1393 * @pool: pool to allocate from
1394 * @size: size of block to allocate
1395 *
1396 * On success, handle to the allocated object is returned,
1397 * otherwise 0.
1398 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1399 */
1400unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1401{
1402 unsigned long handle, obj;
1403 struct size_class *class;
1404 struct zspage *zspage;
1405
1406 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1407 return 0;
1408
1409 handle = cache_alloc_handle(pool, gfp);
1410 if (!handle)
1411 return 0;
1412
1413 /* extra space in chunk to keep the handle */
1414 size += ZS_HANDLE_SIZE;
1415 class = pool->size_class[get_size_class_index(size)];
1416
1417 spin_lock(&class->lock);
1418 zspage = find_get_zspage(class);
1419
1420 if (!zspage) {
1421 spin_unlock(&class->lock);
1422 zspage = alloc_zspage(pool, class, gfp);
1423 if (unlikely(!zspage)) {
1424 cache_free_handle(pool, handle);
1425 return 0;
1426 }
1427
1428 set_zspage_mapping(zspage, class->index, ZS_EMPTY);
1429 atomic_long_add(class->pages_per_zspage,
1430 &pool->pages_allocated);
1431
1432 spin_lock(&class->lock);
1433 zs_stat_inc(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1434 class->size, class->pages_per_zspage));
1435 }
1436
1437 obj = obj_malloc(class, zspage, handle);
1438 /* Now move the zspage to another fullness group, if required */
1439 fix_fullness_group(class, zspage);
1440 record_obj(handle, obj);
1441 spin_unlock(&class->lock);
1442
1443 return handle;
1444}
1445EXPORT_SYMBOL_GPL(zs_malloc);
1446
1447static void obj_free(struct size_class *class, unsigned long obj)
1448{
1449 struct link_free *link;
1450 struct zspage *zspage;
1451 struct page *f_page;
1452 unsigned long f_objidx, f_offset;
1453 void *vaddr;
1454
1455 obj &= ~OBJ_ALLOCATED_TAG;
1456 obj_to_location(obj, &f_page, &f_objidx);
1457 zspage = get_zspage(f_page);
1458
1459 f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1460
1461 vaddr = kmap_atomic(f_page);
1462
1463 /* Insert this object in containing zspage's freelist */
1464 link = (struct link_free *)(vaddr + f_offset);
1465 link->next = (void *)get_freeobj(zspage);
1466 kunmap_atomic(vaddr);
1467 set_freeobj(zspage, obj);
1468 mod_zspage_inuse(zspage, -1);
1469 zs_stat_dec(class, OBJ_USED, 1);
1470}
1471
1472void zs_free(struct zs_pool *pool, unsigned long handle)
1473{
1474 struct zspage *zspage;
1475 struct page *f_page;
1476 unsigned long obj, f_objidx;
1477 int class_idx;
1478 struct size_class *class;
1479 enum fullness_group fullness;
1480
1481 if (unlikely(!handle))
1482 return;
1483
1484 pin_tag(handle);
1485 obj = handle_to_obj(handle);
1486 obj_to_location(obj, &f_page, &f_objidx);
1487 zspage = get_zspage(f_page);
1488
1489 get_zspage_mapping(zspage, &class_idx, &fullness);
1490 class = pool->size_class[class_idx];
1491
1492 spin_lock(&class->lock);
1493 obj_free(class, obj);
1494 fullness = fix_fullness_group(class, zspage);
1495 if (fullness == ZS_EMPTY) {
1496 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1497 class->size, class->pages_per_zspage));
1498 atomic_long_sub(class->pages_per_zspage,
1499 &pool->pages_allocated);
1500 free_zspage(pool, zspage);
1501 }
1502 spin_unlock(&class->lock);
1503 unpin_tag(handle);
1504
1505 cache_free_handle(pool, handle);
1506}
1507EXPORT_SYMBOL_GPL(zs_free);
1508
1509static void zs_object_copy(struct size_class *class, unsigned long dst,
1510 unsigned long src)
1511{
1512 struct page *s_page, *d_page;
1513 unsigned long s_objidx, d_objidx;
1514 unsigned long s_off, d_off;
1515 void *s_addr, *d_addr;
1516 int s_size, d_size, size;
1517 int written = 0;
1518
1519 s_size = d_size = class->size;
1520
1521 obj_to_location(src, &s_page, &s_objidx);
1522 obj_to_location(dst, &d_page, &d_objidx);
1523
1524 s_off = obj_idx_to_offset(s_page, s_objidx, class->size);
1525 d_off = obj_idx_to_offset(d_page, d_objidx, class->size);
1526
1527 if (s_off + class->size > PAGE_SIZE)
1528 s_size = PAGE_SIZE - s_off;
1529
1530 if (d_off + class->size > PAGE_SIZE)
1531 d_size = PAGE_SIZE - d_off;
1532
1533 s_addr = kmap_atomic(s_page);
1534 d_addr = kmap_atomic(d_page);
1535
1536 while (1) {
1537 size = min(s_size, d_size);
1538 memcpy(d_addr + d_off, s_addr + s_off, size);
1539 written += size;
1540
1541 if (written == class->size)
1542 break;
1543
1544 s_off += size;
1545 s_size -= size;
1546 d_off += size;
1547 d_size -= size;
1548
1549 if (s_off >= PAGE_SIZE) {
1550 kunmap_atomic(d_addr);
1551 kunmap_atomic(s_addr);
1552 s_page = get_next_page(s_page);
1553 s_addr = kmap_atomic(s_page);
1554 d_addr = kmap_atomic(d_page);
1555 s_size = class->size - written;
1556 s_off = 0;
1557 }
1558
1559 if (d_off >= PAGE_SIZE) {
1560 kunmap_atomic(d_addr);
1561 d_page = get_next_page(d_page);
1562 d_addr = kmap_atomic(d_page);
1563 d_size = class->size - written;
1564 d_off = 0;
1565 }
1566 }
1567
1568 kunmap_atomic(d_addr);
1569 kunmap_atomic(s_addr);
1570}
1571
1572/*
1573 * Find alloced object in zspage from index object and
1574 * return handle.
1575 */
1576static unsigned long find_alloced_obj(struct size_class *class,
1577 struct page *page, int index)
1578{
1579 unsigned long head;
1580 int offset = 0;
1581 unsigned long handle = 0;
1582 void *addr = kmap_atomic(page);
1583
1584 offset = get_first_obj_offset(page);
1585 offset += class->size * index;
1586
1587 while (offset < PAGE_SIZE) {
1588 head = obj_to_head(class, page, addr + offset);
1589 if (head & OBJ_ALLOCATED_TAG) {
1590 handle = head & ~OBJ_ALLOCATED_TAG;
1591 if (trypin_tag(handle))
1592 break;
1593 handle = 0;
1594 }
1595
1596 offset += class->size;
1597 index++;
1598 }
1599
1600 kunmap_atomic(addr);
1601 return handle;
1602}
1603
1604struct zs_compact_control {
1605 /* Source spage for migration which could be a subpage of zspage */
1606 struct page *s_page;
1607 /* Destination page for migration which should be a first page
1608 * of zspage. */
1609 struct page *d_page;
1610 /* Starting object index within @s_page which used for live object
1611 * in the subpage. */
1612 int index;
1613};
1614
1615static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1616 struct zs_compact_control *cc)
1617{
1618 unsigned long used_obj, free_obj;
1619 unsigned long handle;
1620 struct page *s_page = cc->s_page;
1621 struct page *d_page = cc->d_page;
1622 unsigned long index = cc->index;
1623 int ret = 0;
1624
1625 while (1) {
1626 handle = find_alloced_obj(class, s_page, index);
1627 if (!handle) {
1628 s_page = get_next_page(s_page);
1629 if (!s_page)
1630 break;
1631 index = 0;
1632 continue;
1633 }
1634
1635 /* Stop if there is no more space */
1636 if (zspage_full(class, get_zspage(d_page))) {
1637 unpin_tag(handle);
1638 ret = -ENOMEM;
1639 break;
1640 }
1641
1642 used_obj = handle_to_obj(handle);
1643 free_obj = obj_malloc(class, get_zspage(d_page), handle);
1644 zs_object_copy(class, free_obj, used_obj);
1645 index++;
1646 /*
1647 * record_obj updates handle's value to free_obj and it will
1648 * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
1649 * breaks synchronization using pin_tag(e,g, zs_free) so
1650 * let's keep the lock bit.
1651 */
1652 free_obj |= BIT(HANDLE_PIN_BIT);
1653 record_obj(handle, free_obj);
1654 unpin_tag(handle);
1655 obj_free(class, used_obj);
1656 }
1657
1658 /* Remember last position in this iteration */
1659 cc->s_page = s_page;
1660 cc->index = index;
1661
1662 return ret;
1663}
1664
1665static struct zspage *isolate_zspage(struct size_class *class, bool source)
1666{
1667 int i;
1668 struct zspage *zspage;
1669 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1670
1671 if (!source) {
1672 fg[0] = ZS_ALMOST_FULL;
1673 fg[1] = ZS_ALMOST_EMPTY;
1674 }
1675
1676 for (i = 0; i < 2; i++) {
1677 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1678 struct zspage, list);
1679 if (zspage) {
1680 remove_zspage(class, zspage, fg[i]);
1681 return zspage;
1682 }
1683 }
1684
1685 return zspage;
1686}
1687
1688/*
1689 * putback_zspage - add @zspage into right class's fullness list
1690 * @pool: target pool
1691 * @class: destination class
1692 * @zspage: target page
1693 *
1694 * Return @zspage's fullness_group
1695 */
1696static enum fullness_group putback_zspage(struct zs_pool *pool,
1697 struct size_class *class,
1698 struct zspage *zspage)
1699{
1700 enum fullness_group fullness;
1701
1702 fullness = get_fullness_group(class, zspage);
1703 insert_zspage(class, zspage, fullness);
1704 set_zspage_mapping(zspage, class->index, fullness);
1705
1706 if (fullness == ZS_EMPTY) {
1707 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1708 class->size, class->pages_per_zspage));
1709 atomic_long_sub(class->pages_per_zspage,
1710 &pool->pages_allocated);
1711
1712 free_zspage(pool, zspage);
1713 }
1714
1715 return fullness;
1716}
1717
1718/*
1719 *
1720 * Based on the number of unused allocated objects calculate
1721 * and return the number of pages that we can free.
1722 */
1723static unsigned long zs_can_compact(struct size_class *class)
1724{
1725 unsigned long obj_wasted;
1726 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
1727 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
1728
1729 if (obj_allocated <= obj_used)
1730 return 0;
1731
1732 obj_wasted = obj_allocated - obj_used;
1733 obj_wasted /= get_maxobj_per_zspage(class->size,
1734 class->pages_per_zspage);
1735
1736 return obj_wasted * class->pages_per_zspage;
1737}
1738
1739static void __zs_compact(struct zs_pool *pool, struct size_class *class)
1740{
1741 struct zs_compact_control cc;
1742 struct zspage *src_zspage;
1743 struct zspage *dst_zspage = NULL;
1744
1745 spin_lock(&class->lock);
1746 while ((src_zspage = isolate_zspage(class, true))) {
1747
1748 if (!zs_can_compact(class))
1749 break;
1750
1751 cc.index = 0;
1752 cc.s_page = src_zspage->first_page;
1753
1754 while ((dst_zspage = isolate_zspage(class, false))) {
1755 cc.d_page = dst_zspage->first_page;
1756 /*
1757 * If there is no more space in dst_page, resched
1758 * and see if anyone had allocated another zspage.
1759 */
1760 if (!migrate_zspage(pool, class, &cc))
1761 break;
1762
1763 putback_zspage(pool, class, dst_zspage);
1764 }
1765
1766 /* Stop if we couldn't find slot */
1767 if (dst_zspage == NULL)
1768 break;
1769
1770 putback_zspage(pool, class, dst_zspage);
1771 if (putback_zspage(pool, class, src_zspage) == ZS_EMPTY)
1772 pool->stats.pages_compacted += class->pages_per_zspage;
1773 spin_unlock(&class->lock);
1774 cond_resched();
1775 spin_lock(&class->lock);
1776 }
1777
1778 if (src_zspage)
1779 putback_zspage(pool, class, src_zspage);
1780
1781 spin_unlock(&class->lock);
1782}
1783
1784unsigned long zs_compact(struct zs_pool *pool)
1785{
1786 int i;
1787 struct size_class *class;
1788
1789 for (i = zs_size_classes - 1; i >= 0; i--) {
1790 class = pool->size_class[i];
1791 if (!class)
1792 continue;
1793 if (class->index != i)
1794 continue;
1795 __zs_compact(pool, class);
1796 }
1797
1798 return pool->stats.pages_compacted;
1799}
1800EXPORT_SYMBOL_GPL(zs_compact);
1801
1802void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
1803{
1804 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
1805}
1806EXPORT_SYMBOL_GPL(zs_pool_stats);
1807
1808static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
1809 struct shrink_control *sc)
1810{
1811 unsigned long pages_freed;
1812 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
1813 shrinker);
1814
1815 pages_freed = pool->stats.pages_compacted;
1816 /*
1817 * Compact classes and calculate compaction delta.
1818 * Can run concurrently with a manually triggered
1819 * (by user) compaction.
1820 */
1821 pages_freed = zs_compact(pool) - pages_freed;
1822
1823 return pages_freed ? pages_freed : SHRINK_STOP;
1824}
1825
1826static unsigned long zs_shrinker_count(struct shrinker *shrinker,
1827 struct shrink_control *sc)
1828{
1829 int i;
1830 struct size_class *class;
1831 unsigned long pages_to_free = 0;
1832 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
1833 shrinker);
1834
1835 for (i = zs_size_classes - 1; i >= 0; i--) {
1836 class = pool->size_class[i];
1837 if (!class)
1838 continue;
1839 if (class->index != i)
1840 continue;
1841
1842 pages_to_free += zs_can_compact(class);
1843 }
1844
1845 return pages_to_free;
1846}
1847
1848static void zs_unregister_shrinker(struct zs_pool *pool)
1849{
1850 if (pool->shrinker_enabled) {
1851 unregister_shrinker(&pool->shrinker);
1852 pool->shrinker_enabled = false;
1853 }
1854}
1855
1856static int zs_register_shrinker(struct zs_pool *pool)
1857{
1858 pool->shrinker.scan_objects = zs_shrinker_scan;
1859 pool->shrinker.count_objects = zs_shrinker_count;
1860 pool->shrinker.batch = 0;
1861 pool->shrinker.seeks = DEFAULT_SEEKS;
1862
1863 return register_shrinker(&pool->shrinker);
1864}
1865
1866/**
1867 * zs_create_pool - Creates an allocation pool to work from.
1868 * @flags: allocation flags used to allocate pool metadata
1869 *
1870 * This function must be called before anything when using
1871 * the zsmalloc allocator.
1872 *
1873 * On success, a pointer to the newly created pool is returned,
1874 * otherwise NULL.
1875 */
1876struct zs_pool *zs_create_pool(const char *name)
1877{
1878 int i;
1879 struct zs_pool *pool;
1880 struct size_class *prev_class = NULL;
1881
1882 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
1883 if (!pool)
1884 return NULL;
1885
1886 pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
1887 GFP_KERNEL);
1888 if (!pool->size_class) {
1889 kfree(pool);
1890 return NULL;
1891 }
1892
1893 pool->name = kstrdup(name, GFP_KERNEL);
1894 if (!pool->name)
1895 goto err;
1896
1897 if (create_cache(pool))
1898 goto err;
1899
1900 /*
1901 * Iterate reversly, because, size of size_class that we want to use
1902 * for merging should be larger or equal to current size.
1903 */
1904 for (i = zs_size_classes - 1; i >= 0; i--) {
1905 int size;
1906 int pages_per_zspage;
1907 struct size_class *class;
1908 int fullness = 0;
1909
1910 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
1911 if (size > ZS_MAX_ALLOC_SIZE)
1912 size = ZS_MAX_ALLOC_SIZE;
1913 pages_per_zspage = get_pages_per_zspage(size);
1914
1915 /*
1916 * size_class is used for normal zsmalloc operation such
1917 * as alloc/free for that size. Although it is natural that we
1918 * have one size_class for each size, there is a chance that we
1919 * can get more memory utilization if we use one size_class for
1920 * many different sizes whose size_class have same
1921 * characteristics. So, we makes size_class point to
1922 * previous size_class if possible.
1923 */
1924 if (prev_class) {
1925 if (can_merge(prev_class, size, pages_per_zspage)) {
1926 pool->size_class[i] = prev_class;
1927 continue;
1928 }
1929 }
1930
1931 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
1932 if (!class)
1933 goto err;
1934
1935 class->size = size;
1936 class->index = i;
1937 class->pages_per_zspage = pages_per_zspage;
1938 class->objs_per_zspage = class->pages_per_zspage *
1939 PAGE_SIZE / class->size;
1940 if (pages_per_zspage == 1 && class->objs_per_zspage == 1)
1941 class->huge = true;
1942 spin_lock_init(&class->lock);
1943 pool->size_class[i] = class;
1944 for (fullness = ZS_ALMOST_FULL; fullness <= ZS_ALMOST_EMPTY;
1945 fullness++)
1946 INIT_LIST_HEAD(&class->fullness_list[fullness]);
1947
1948 prev_class = class;
1949 }
1950
1951 /* debug only, don't abort if it fails */
1952 zs_pool_stat_create(pool, name);
1953
1954 /*
1955 * Not critical, we still can use the pool
1956 * and user can trigger compaction manually.
1957 */
1958 if (zs_register_shrinker(pool) == 0)
1959 pool->shrinker_enabled = true;
1960 return pool;
1961
1962err:
1963 zs_destroy_pool(pool);
1964 return NULL;
1965}
1966EXPORT_SYMBOL_GPL(zs_create_pool);
1967
1968void zs_destroy_pool(struct zs_pool *pool)
1969{
1970 int i;
1971
1972 zs_unregister_shrinker(pool);
1973 zs_pool_stat_destroy(pool);
1974
1975 for (i = 0; i < zs_size_classes; i++) {
1976 int fg;
1977 struct size_class *class = pool->size_class[i];
1978
1979 if (!class)
1980 continue;
1981
1982 if (class->index != i)
1983 continue;
1984
1985 for (fg = ZS_ALMOST_FULL; fg <= ZS_ALMOST_EMPTY; fg++) {
1986 if (!list_empty(&class->fullness_list[fg])) {
1987 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
1988 class->size, fg);
1989 }
1990 }
1991 kfree(class);
1992 }
1993
1994 destroy_cache(pool);
1995 kfree(pool->size_class);
1996 kfree(pool->name);
1997 kfree(pool);
1998}
1999EXPORT_SYMBOL_GPL(zs_destroy_pool);
2000
2001static int __init zs_init(void)
2002{
2003 int ret = zs_register_cpu_notifier();
2004
2005 if (ret)
2006 goto notifier_fail;
2007
2008 init_zs_size_classes();
2009
2010#ifdef CONFIG_ZPOOL
2011 zpool_register_driver(&zs_zpool_driver);
2012#endif
2013
2014 zs_stat_init();
2015
2016 return 0;
2017
2018notifier_fail:
2019 zs_unregister_cpu_notifier();
2020
2021 return ret;
2022}
2023
2024static void __exit zs_exit(void)
2025{
2026#ifdef CONFIG_ZPOOL
2027 zpool_unregister_driver(&zs_zpool_driver);
2028#endif
2029 zs_unregister_cpu_notifier();
2030
2031 zs_stat_exit();
2032}
2033
2034module_init(zs_init);
2035module_exit(zs_exit);
2036
2037MODULE_LICENSE("Dual BSD/GPL");
2038MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");