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