xref: /openbmc/linux/mm/zsmalloc.c (revision 06ba8020)
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: links together all component pages of a zspage
21  *		For the huge page, this is always 0, so we use this field
22  *		to store handle.
23  *	page->page_type: first object offset in a subpage of zspage
24  *
25  * Usage of struct page flags:
26  *	PG_private: identifies the first component page
27  *	PG_owner_priv_1: identifies the huge component page
28  *
29  */
30 
31 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
32 
33 /*
34  * lock ordering:
35  *	page_lock
36  *	pool->lock
37  *	zspage->lock
38  */
39 
40 #include <linux/module.h>
41 #include <linux/kernel.h>
42 #include <linux/sched.h>
43 #include <linux/bitops.h>
44 #include <linux/errno.h>
45 #include <linux/highmem.h>
46 #include <linux/string.h>
47 #include <linux/slab.h>
48 #include <linux/pgtable.h>
49 #include <asm/tlbflush.h>
50 #include <linux/cpumask.h>
51 #include <linux/cpu.h>
52 #include <linux/vmalloc.h>
53 #include <linux/preempt.h>
54 #include <linux/spinlock.h>
55 #include <linux/shrinker.h>
56 #include <linux/types.h>
57 #include <linux/debugfs.h>
58 #include <linux/zsmalloc.h>
59 #include <linux/zpool.h>
60 #include <linux/migrate.h>
61 #include <linux/wait.h>
62 #include <linux/pagemap.h>
63 #include <linux/fs.h>
64 #include <linux/local_lock.h>
65 
66 #define ZSPAGE_MAGIC	0x58
67 
68 /*
69  * This must be power of 2 and greater than or equal to sizeof(link_free).
70  * These two conditions ensure that any 'struct link_free' itself doesn't
71  * span more than 1 page which avoids complex case of mapping 2 pages simply
72  * to restore link_free pointer values.
73  */
74 #define ZS_ALIGN		8
75 
76 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
77 
78 /*
79  * Object location (<PFN>, <obj_idx>) is encoded as
80  * a single (unsigned long) handle value.
81  *
82  * Note that object index <obj_idx> starts from 0.
83  *
84  * This is made more complicated by various memory models and PAE.
85  */
86 
87 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
88 #ifdef MAX_PHYSMEM_BITS
89 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
90 #else
91 /*
92  * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
93  * be PAGE_SHIFT
94  */
95 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
96 #endif
97 #endif
98 
99 #define _PFN_BITS		(MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
100 
101 /*
102  * Head in allocated object should have OBJ_ALLOCATED_TAG
103  * to identify the object was allocated or not.
104  * It's okay to add the status bit in the least bit because
105  * header keeps handle which is 4byte-aligned address so we
106  * have room for two bit at least.
107  */
108 #define OBJ_ALLOCATED_TAG 1
109 
110 #ifdef CONFIG_ZPOOL
111 /*
112  * The second least-significant bit in the object's header identifies if the
113  * value stored at the header is a deferred handle from the last reclaim
114  * attempt.
115  *
116  * As noted above, this is valid because we have room for two bits.
117  */
118 #define OBJ_DEFERRED_HANDLE_TAG	2
119 #define OBJ_TAG_BITS	2
120 #define OBJ_TAG_MASK	(OBJ_ALLOCATED_TAG | OBJ_DEFERRED_HANDLE_TAG)
121 #else
122 #define OBJ_TAG_BITS	1
123 #define OBJ_TAG_MASK	OBJ_ALLOCATED_TAG
124 #endif /* CONFIG_ZPOOL */
125 
126 #define OBJ_INDEX_BITS	(BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
127 #define OBJ_INDEX_MASK	((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
128 
129 #define HUGE_BITS	1
130 #define FULLNESS_BITS	4
131 #define CLASS_BITS	8
132 #define ISOLATED_BITS	5
133 #define MAGIC_VAL_BITS	8
134 
135 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
136 
137 #define ZS_MAX_PAGES_PER_ZSPAGE	(_AC(CONFIG_ZSMALLOC_CHAIN_SIZE, UL))
138 
139 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
140 #define ZS_MIN_ALLOC_SIZE \
141 	MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
142 /* each chunk includes extra space to keep handle */
143 #define ZS_MAX_ALLOC_SIZE	PAGE_SIZE
144 
145 /*
146  * On systems with 4K page size, this gives 255 size classes! There is a
147  * trader-off here:
148  *  - Large number of size classes is potentially wasteful as free page are
149  *    spread across these classes
150  *  - Small number of size classes causes large internal fragmentation
151  *  - Probably its better to use specific size classes (empirically
152  *    determined). NOTE: all those class sizes must be set as multiple of
153  *    ZS_ALIGN to make sure link_free itself never has to span 2 pages.
154  *
155  *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
156  *  (reason above)
157  */
158 #define ZS_SIZE_CLASS_DELTA	(PAGE_SIZE >> CLASS_BITS)
159 #define ZS_SIZE_CLASSES	(DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
160 				      ZS_SIZE_CLASS_DELTA) + 1)
161 
162 /*
163  * Pages are distinguished by the ratio of used memory (that is the ratio
164  * of ->inuse objects to all objects that page can store). For example,
165  * INUSE_RATIO_10 means that the ratio of used objects is > 0% and <= 10%.
166  *
167  * The number of fullness groups is not random. It allows us to keep
168  * difference between the least busy page in the group (minimum permitted
169  * number of ->inuse objects) and the most busy page (maximum permitted
170  * number of ->inuse objects) at a reasonable value.
171  */
172 enum fullness_group {
173 	ZS_INUSE_RATIO_0,
174 	ZS_INUSE_RATIO_10,
175 	/* NOTE: 8 more fullness groups here */
176 	ZS_INUSE_RATIO_99       = 10,
177 	ZS_INUSE_RATIO_100,
178 	NR_FULLNESS_GROUPS,
179 };
180 
181 enum class_stat_type {
182 	/* NOTE: stats for 12 fullness groups here: from inuse 0 to 100 */
183 	ZS_OBJS_ALLOCATED       = NR_FULLNESS_GROUPS,
184 	ZS_OBJS_INUSE,
185 	NR_CLASS_STAT_TYPES,
186 };
187 
188 struct zs_size_stat {
189 	unsigned long objs[NR_CLASS_STAT_TYPES];
190 };
191 
192 #ifdef CONFIG_ZSMALLOC_STAT
193 static struct dentry *zs_stat_root;
194 #endif
195 
196 static size_t huge_class_size;
197 
198 struct size_class {
199 	struct list_head fullness_list[NR_FULLNESS_GROUPS];
200 	/*
201 	 * Size of objects stored in this class. Must be multiple
202 	 * of ZS_ALIGN.
203 	 */
204 	int size;
205 	int objs_per_zspage;
206 	/* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
207 	int pages_per_zspage;
208 
209 	unsigned int index;
210 	struct zs_size_stat stats;
211 };
212 
213 /*
214  * Placed within free objects to form a singly linked list.
215  * For every zspage, zspage->freeobj gives head of this list.
216  *
217  * This must be power of 2 and less than or equal to ZS_ALIGN
218  */
219 struct link_free {
220 	union {
221 		/*
222 		 * Free object index;
223 		 * It's valid for non-allocated object
224 		 */
225 		unsigned long next;
226 		/*
227 		 * Handle of allocated object.
228 		 */
229 		unsigned long handle;
230 #ifdef CONFIG_ZPOOL
231 		/*
232 		 * Deferred handle of a reclaimed object.
233 		 */
234 		unsigned long deferred_handle;
235 #endif
236 	};
237 };
238 
239 struct zs_pool {
240 	const char *name;
241 
242 	struct size_class *size_class[ZS_SIZE_CLASSES];
243 	struct kmem_cache *handle_cachep;
244 	struct kmem_cache *zspage_cachep;
245 
246 	atomic_long_t pages_allocated;
247 
248 	struct zs_pool_stats stats;
249 
250 	/* Compact classes */
251 	struct shrinker shrinker;
252 
253 #ifdef CONFIG_ZPOOL
254 	/* List tracking the zspages in LRU order by most recently added object */
255 	struct list_head lru;
256 	struct zpool *zpool;
257 	const struct zpool_ops *zpool_ops;
258 #endif
259 
260 #ifdef CONFIG_ZSMALLOC_STAT
261 	struct dentry *stat_dentry;
262 #endif
263 #ifdef CONFIG_COMPACTION
264 	struct work_struct free_work;
265 #endif
266 	spinlock_t lock;
267 	atomic_t compaction_in_progress;
268 };
269 
270 struct zspage {
271 	struct {
272 		unsigned int huge:HUGE_BITS;
273 		unsigned int fullness:FULLNESS_BITS;
274 		unsigned int class:CLASS_BITS + 1;
275 		unsigned int isolated:ISOLATED_BITS;
276 		unsigned int magic:MAGIC_VAL_BITS;
277 	};
278 	unsigned int inuse;
279 	unsigned int freeobj;
280 	struct page *first_page;
281 	struct list_head list; /* fullness list */
282 
283 #ifdef CONFIG_ZPOOL
284 	/* links the zspage to the lru list in the pool */
285 	struct list_head lru;
286 	bool under_reclaim;
287 #endif
288 
289 	struct zs_pool *pool;
290 	rwlock_t lock;
291 };
292 
293 struct mapping_area {
294 	local_lock_t lock;
295 	char *vm_buf; /* copy buffer for objects that span pages */
296 	char *vm_addr; /* address of kmap_atomic()'ed pages */
297 	enum zs_mapmode vm_mm; /* mapping mode */
298 };
299 
300 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
301 static void SetZsHugePage(struct zspage *zspage)
302 {
303 	zspage->huge = 1;
304 }
305 
306 static bool ZsHugePage(struct zspage *zspage)
307 {
308 	return zspage->huge;
309 }
310 
311 static void migrate_lock_init(struct zspage *zspage);
312 static void migrate_read_lock(struct zspage *zspage);
313 static void migrate_read_unlock(struct zspage *zspage);
314 
315 #ifdef CONFIG_COMPACTION
316 static void migrate_write_lock(struct zspage *zspage);
317 static void migrate_write_lock_nested(struct zspage *zspage);
318 static void migrate_write_unlock(struct zspage *zspage);
319 static void kick_deferred_free(struct zs_pool *pool);
320 static void init_deferred_free(struct zs_pool *pool);
321 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
322 #else
323 static void migrate_write_lock(struct zspage *zspage) {}
324 static void migrate_write_lock_nested(struct zspage *zspage) {}
325 static void migrate_write_unlock(struct zspage *zspage) {}
326 static void kick_deferred_free(struct zs_pool *pool) {}
327 static void init_deferred_free(struct zs_pool *pool) {}
328 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
329 #endif
330 
331 static int create_cache(struct zs_pool *pool)
332 {
333 	pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
334 					0, 0, NULL);
335 	if (!pool->handle_cachep)
336 		return 1;
337 
338 	pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
339 					0, 0, NULL);
340 	if (!pool->zspage_cachep) {
341 		kmem_cache_destroy(pool->handle_cachep);
342 		pool->handle_cachep = NULL;
343 		return 1;
344 	}
345 
346 	return 0;
347 }
348 
349 static void destroy_cache(struct zs_pool *pool)
350 {
351 	kmem_cache_destroy(pool->handle_cachep);
352 	kmem_cache_destroy(pool->zspage_cachep);
353 }
354 
355 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
356 {
357 	return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
358 			gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
359 }
360 
361 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
362 {
363 	kmem_cache_free(pool->handle_cachep, (void *)handle);
364 }
365 
366 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
367 {
368 	return kmem_cache_zalloc(pool->zspage_cachep,
369 			flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
370 }
371 
372 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
373 {
374 	kmem_cache_free(pool->zspage_cachep, zspage);
375 }
376 
377 /* pool->lock(which owns the handle) synchronizes races */
378 static void record_obj(unsigned long handle, unsigned long obj)
379 {
380 	*(unsigned long *)handle = obj;
381 }
382 
383 /* zpool driver */
384 
385 #ifdef CONFIG_ZPOOL
386 
387 static void *zs_zpool_create(const char *name, gfp_t gfp,
388 			     const struct zpool_ops *zpool_ops,
389 			     struct zpool *zpool)
390 {
391 	/*
392 	 * Ignore global gfp flags: zs_malloc() may be invoked from
393 	 * different contexts and its caller must provide a valid
394 	 * gfp mask.
395 	 */
396 	struct zs_pool *pool = zs_create_pool(name);
397 
398 	if (pool) {
399 		pool->zpool = zpool;
400 		pool->zpool_ops = zpool_ops;
401 	}
402 
403 	return pool;
404 }
405 
406 static void zs_zpool_destroy(void *pool)
407 {
408 	zs_destroy_pool(pool);
409 }
410 
411 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
412 			unsigned long *handle)
413 {
414 	*handle = zs_malloc(pool, size, gfp);
415 
416 	if (IS_ERR_VALUE(*handle))
417 		return PTR_ERR((void *)*handle);
418 	return 0;
419 }
420 static void zs_zpool_free(void *pool, unsigned long handle)
421 {
422 	zs_free(pool, handle);
423 }
424 
425 static int zs_reclaim_page(struct zs_pool *pool, unsigned int retries);
426 
427 static int zs_zpool_shrink(void *pool, unsigned int pages,
428 			unsigned int *reclaimed)
429 {
430 	unsigned int total = 0;
431 	int ret = -EINVAL;
432 
433 	while (total < pages) {
434 		ret = zs_reclaim_page(pool, 8);
435 		if (ret < 0)
436 			break;
437 		total++;
438 	}
439 
440 	if (reclaimed)
441 		*reclaimed = total;
442 
443 	return ret;
444 }
445 
446 static void *zs_zpool_map(void *pool, unsigned long handle,
447 			enum zpool_mapmode mm)
448 {
449 	enum zs_mapmode zs_mm;
450 
451 	switch (mm) {
452 	case ZPOOL_MM_RO:
453 		zs_mm = ZS_MM_RO;
454 		break;
455 	case ZPOOL_MM_WO:
456 		zs_mm = ZS_MM_WO;
457 		break;
458 	case ZPOOL_MM_RW:
459 	default:
460 		zs_mm = ZS_MM_RW;
461 		break;
462 	}
463 
464 	return zs_map_object(pool, handle, zs_mm);
465 }
466 static void zs_zpool_unmap(void *pool, unsigned long handle)
467 {
468 	zs_unmap_object(pool, handle);
469 }
470 
471 static u64 zs_zpool_total_size(void *pool)
472 {
473 	return zs_get_total_pages(pool) << PAGE_SHIFT;
474 }
475 
476 static struct zpool_driver zs_zpool_driver = {
477 	.type =			  "zsmalloc",
478 	.owner =		  THIS_MODULE,
479 	.create =		  zs_zpool_create,
480 	.destroy =		  zs_zpool_destroy,
481 	.malloc_support_movable = true,
482 	.malloc =		  zs_zpool_malloc,
483 	.free =			  zs_zpool_free,
484 	.shrink =		  zs_zpool_shrink,
485 	.map =			  zs_zpool_map,
486 	.unmap =		  zs_zpool_unmap,
487 	.total_size =		  zs_zpool_total_size,
488 };
489 
490 MODULE_ALIAS("zpool-zsmalloc");
491 #endif /* CONFIG_ZPOOL */
492 
493 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
494 static DEFINE_PER_CPU(struct mapping_area, zs_map_area) = {
495 	.lock	= INIT_LOCAL_LOCK(lock),
496 };
497 
498 static __maybe_unused int is_first_page(struct page *page)
499 {
500 	return PagePrivate(page);
501 }
502 
503 /* Protected by pool->lock */
504 static inline int get_zspage_inuse(struct zspage *zspage)
505 {
506 	return zspage->inuse;
507 }
508 
509 
510 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
511 {
512 	zspage->inuse += val;
513 }
514 
515 static inline struct page *get_first_page(struct zspage *zspage)
516 {
517 	struct page *first_page = zspage->first_page;
518 
519 	VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
520 	return first_page;
521 }
522 
523 static inline unsigned int get_first_obj_offset(struct page *page)
524 {
525 	return page->page_type;
526 }
527 
528 static inline void set_first_obj_offset(struct page *page, unsigned int offset)
529 {
530 	page->page_type = offset;
531 }
532 
533 static inline unsigned int get_freeobj(struct zspage *zspage)
534 {
535 	return zspage->freeobj;
536 }
537 
538 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
539 {
540 	zspage->freeobj = obj;
541 }
542 
543 static void get_zspage_mapping(struct zspage *zspage,
544 			       unsigned int *class_idx,
545 			       int *fullness)
546 {
547 	BUG_ON(zspage->magic != ZSPAGE_MAGIC);
548 
549 	*fullness = zspage->fullness;
550 	*class_idx = zspage->class;
551 }
552 
553 static struct size_class *zspage_class(struct zs_pool *pool,
554 				       struct zspage *zspage)
555 {
556 	return pool->size_class[zspage->class];
557 }
558 
559 static void set_zspage_mapping(struct zspage *zspage,
560 			       unsigned int class_idx,
561 			       int fullness)
562 {
563 	zspage->class = class_idx;
564 	zspage->fullness = fullness;
565 }
566 
567 /*
568  * zsmalloc divides the pool into various size classes where each
569  * class maintains a list of zspages where each zspage is divided
570  * into equal sized chunks. Each allocation falls into one of these
571  * classes depending on its size. This function returns index of the
572  * size class which has chunk size big enough to hold the given size.
573  */
574 static int get_size_class_index(int size)
575 {
576 	int idx = 0;
577 
578 	if (likely(size > ZS_MIN_ALLOC_SIZE))
579 		idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
580 				ZS_SIZE_CLASS_DELTA);
581 
582 	return min_t(int, ZS_SIZE_CLASSES - 1, idx);
583 }
584 
585 static inline void class_stat_inc(struct size_class *class,
586 				int type, unsigned long cnt)
587 {
588 	class->stats.objs[type] += cnt;
589 }
590 
591 static inline void class_stat_dec(struct size_class *class,
592 				int type, unsigned long cnt)
593 {
594 	class->stats.objs[type] -= cnt;
595 }
596 
597 static inline unsigned long zs_stat_get(struct size_class *class, int type)
598 {
599 	return class->stats.objs[type];
600 }
601 
602 #ifdef CONFIG_ZSMALLOC_STAT
603 
604 static void __init zs_stat_init(void)
605 {
606 	if (!debugfs_initialized()) {
607 		pr_warn("debugfs not available, stat dir not created\n");
608 		return;
609 	}
610 
611 	zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
612 }
613 
614 static void __exit zs_stat_exit(void)
615 {
616 	debugfs_remove_recursive(zs_stat_root);
617 }
618 
619 static unsigned long zs_can_compact(struct size_class *class);
620 
621 static int zs_stats_size_show(struct seq_file *s, void *v)
622 {
623 	int i, fg;
624 	struct zs_pool *pool = s->private;
625 	struct size_class *class;
626 	int objs_per_zspage;
627 	unsigned long obj_allocated, obj_used, pages_used, freeable;
628 	unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
629 	unsigned long total_freeable = 0;
630 	unsigned long inuse_totals[NR_FULLNESS_GROUPS] = {0, };
631 
632 	seq_printf(s, " %5s %5s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %13s %10s %10s %16s %8s\n",
633 			"class", "size", "10%", "20%", "30%", "40%",
634 			"50%", "60%", "70%", "80%", "90%", "99%", "100%",
635 			"obj_allocated", "obj_used", "pages_used",
636 			"pages_per_zspage", "freeable");
637 
638 	for (i = 0; i < ZS_SIZE_CLASSES; i++) {
639 
640 		class = pool->size_class[i];
641 
642 		if (class->index != i)
643 			continue;
644 
645 		spin_lock(&pool->lock);
646 
647 		seq_printf(s, " %5u %5u ", i, class->size);
648 		for (fg = ZS_INUSE_RATIO_10; fg < NR_FULLNESS_GROUPS; fg++) {
649 			inuse_totals[fg] += zs_stat_get(class, fg);
650 			seq_printf(s, "%9lu ", zs_stat_get(class, fg));
651 		}
652 
653 		obj_allocated = zs_stat_get(class, ZS_OBJS_ALLOCATED);
654 		obj_used = zs_stat_get(class, ZS_OBJS_INUSE);
655 		freeable = zs_can_compact(class);
656 		spin_unlock(&pool->lock);
657 
658 		objs_per_zspage = class->objs_per_zspage;
659 		pages_used = obj_allocated / objs_per_zspage *
660 				class->pages_per_zspage;
661 
662 		seq_printf(s, "%13lu %10lu %10lu %16d %8lu\n",
663 			   obj_allocated, obj_used, pages_used,
664 			   class->pages_per_zspage, freeable);
665 
666 		total_objs += obj_allocated;
667 		total_used_objs += obj_used;
668 		total_pages += pages_used;
669 		total_freeable += freeable;
670 	}
671 
672 	seq_puts(s, "\n");
673 	seq_printf(s, " %5s %5s ", "Total", "");
674 
675 	for (fg = ZS_INUSE_RATIO_10; fg < NR_FULLNESS_GROUPS; fg++)
676 		seq_printf(s, "%9lu ", inuse_totals[fg]);
677 
678 	seq_printf(s, "%13lu %10lu %10lu %16s %8lu\n",
679 		   total_objs, total_used_objs, total_pages, "",
680 		   total_freeable);
681 
682 	return 0;
683 }
684 DEFINE_SHOW_ATTRIBUTE(zs_stats_size);
685 
686 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
687 {
688 	if (!zs_stat_root) {
689 		pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
690 		return;
691 	}
692 
693 	pool->stat_dentry = debugfs_create_dir(name, zs_stat_root);
694 
695 	debugfs_create_file("classes", S_IFREG | 0444, pool->stat_dentry, pool,
696 			    &zs_stats_size_fops);
697 }
698 
699 static void zs_pool_stat_destroy(struct zs_pool *pool)
700 {
701 	debugfs_remove_recursive(pool->stat_dentry);
702 }
703 
704 #else /* CONFIG_ZSMALLOC_STAT */
705 static void __init zs_stat_init(void)
706 {
707 }
708 
709 static void __exit zs_stat_exit(void)
710 {
711 }
712 
713 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
714 {
715 }
716 
717 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
718 {
719 }
720 #endif
721 
722 
723 /*
724  * For each size class, zspages are divided into different groups
725  * depending on their usage ratio. This function returns fullness
726  * status of the given page.
727  */
728 static int get_fullness_group(struct size_class *class, struct zspage *zspage)
729 {
730 	int inuse, objs_per_zspage, ratio;
731 
732 	inuse = get_zspage_inuse(zspage);
733 	objs_per_zspage = class->objs_per_zspage;
734 
735 	if (inuse == 0)
736 		return ZS_INUSE_RATIO_0;
737 	if (inuse == objs_per_zspage)
738 		return ZS_INUSE_RATIO_100;
739 
740 	ratio = 100 * inuse / objs_per_zspage;
741 	/*
742 	 * Take integer division into consideration: a page with one inuse
743 	 * object out of 127 possible, will end up having 0 usage ratio,
744 	 * which is wrong as it belongs in ZS_INUSE_RATIO_10 fullness group.
745 	 */
746 	return ratio / 10 + 1;
747 }
748 
749 /*
750  * Each size class maintains various freelists and zspages are assigned
751  * to one of these freelists based on the number of live objects they
752  * have. This functions inserts the given zspage into the freelist
753  * identified by <class, fullness_group>.
754  */
755 static void insert_zspage(struct size_class *class,
756 				struct zspage *zspage,
757 				int fullness)
758 {
759 	class_stat_inc(class, fullness, 1);
760 	list_add(&zspage->list, &class->fullness_list[fullness]);
761 }
762 
763 /*
764  * This function removes the given zspage from the freelist identified
765  * by <class, fullness_group>.
766  */
767 static void remove_zspage(struct size_class *class,
768 				struct zspage *zspage,
769 				int fullness)
770 {
771 	VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
772 
773 	list_del_init(&zspage->list);
774 	class_stat_dec(class, fullness, 1);
775 }
776 
777 /*
778  * Each size class maintains zspages in different fullness groups depending
779  * on the number of live objects they contain. When allocating or freeing
780  * objects, the fullness status of the page can change, for instance, from
781  * INUSE_RATIO_80 to INUSE_RATIO_70 when freeing an object. This function
782  * checks if such a status change has occurred for the given page and
783  * accordingly moves the page from the list of the old fullness group to that
784  * of the new fullness group.
785  */
786 static int fix_fullness_group(struct size_class *class, struct zspage *zspage)
787 {
788 	int class_idx;
789 	int currfg, newfg;
790 
791 	get_zspage_mapping(zspage, &class_idx, &currfg);
792 	newfg = get_fullness_group(class, zspage);
793 	if (newfg == currfg)
794 		goto out;
795 
796 	remove_zspage(class, zspage, currfg);
797 	insert_zspage(class, zspage, newfg);
798 	set_zspage_mapping(zspage, class_idx, newfg);
799 out:
800 	return newfg;
801 }
802 
803 static struct zspage *get_zspage(struct page *page)
804 {
805 	struct zspage *zspage = (struct zspage *)page_private(page);
806 
807 	BUG_ON(zspage->magic != ZSPAGE_MAGIC);
808 	return zspage;
809 }
810 
811 static struct page *get_next_page(struct page *page)
812 {
813 	struct zspage *zspage = get_zspage(page);
814 
815 	if (unlikely(ZsHugePage(zspage)))
816 		return NULL;
817 
818 	return (struct page *)page->index;
819 }
820 
821 /**
822  * obj_to_location - get (<page>, <obj_idx>) from encoded object value
823  * @obj: the encoded object value
824  * @page: page object resides in zspage
825  * @obj_idx: object index
826  */
827 static void obj_to_location(unsigned long obj, struct page **page,
828 				unsigned int *obj_idx)
829 {
830 	obj >>= OBJ_TAG_BITS;
831 	*page = pfn_to_page(obj >> OBJ_INDEX_BITS);
832 	*obj_idx = (obj & OBJ_INDEX_MASK);
833 }
834 
835 static void obj_to_page(unsigned long obj, struct page **page)
836 {
837 	obj >>= OBJ_TAG_BITS;
838 	*page = pfn_to_page(obj >> OBJ_INDEX_BITS);
839 }
840 
841 /**
842  * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
843  * @page: page object resides in zspage
844  * @obj_idx: object index
845  */
846 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
847 {
848 	unsigned long obj;
849 
850 	obj = page_to_pfn(page) << OBJ_INDEX_BITS;
851 	obj |= obj_idx & OBJ_INDEX_MASK;
852 	obj <<= OBJ_TAG_BITS;
853 
854 	return obj;
855 }
856 
857 static unsigned long handle_to_obj(unsigned long handle)
858 {
859 	return *(unsigned long *)handle;
860 }
861 
862 static bool obj_tagged(struct page *page, void *obj, unsigned long *phandle,
863 		int tag)
864 {
865 	unsigned long handle;
866 	struct zspage *zspage = get_zspage(page);
867 
868 	if (unlikely(ZsHugePage(zspage))) {
869 		VM_BUG_ON_PAGE(!is_first_page(page), page);
870 		handle = page->index;
871 	} else
872 		handle = *(unsigned long *)obj;
873 
874 	if (!(handle & tag))
875 		return false;
876 
877 	/* Clear all tags before returning the handle */
878 	*phandle = handle & ~OBJ_TAG_MASK;
879 	return true;
880 }
881 
882 static inline bool obj_allocated(struct page *page, void *obj, unsigned long *phandle)
883 {
884 	return obj_tagged(page, obj, phandle, OBJ_ALLOCATED_TAG);
885 }
886 
887 #ifdef CONFIG_ZPOOL
888 static bool obj_stores_deferred_handle(struct page *page, void *obj,
889 		unsigned long *phandle)
890 {
891 	return obj_tagged(page, obj, phandle, OBJ_DEFERRED_HANDLE_TAG);
892 }
893 #endif
894 
895 static void reset_page(struct page *page)
896 {
897 	__ClearPageMovable(page);
898 	ClearPagePrivate(page);
899 	set_page_private(page, 0);
900 	page_mapcount_reset(page);
901 	page->index = 0;
902 }
903 
904 static int trylock_zspage(struct zspage *zspage)
905 {
906 	struct page *cursor, *fail;
907 
908 	for (cursor = get_first_page(zspage); cursor != NULL; cursor =
909 					get_next_page(cursor)) {
910 		if (!trylock_page(cursor)) {
911 			fail = cursor;
912 			goto unlock;
913 		}
914 	}
915 
916 	return 1;
917 unlock:
918 	for (cursor = get_first_page(zspage); cursor != fail; cursor =
919 					get_next_page(cursor))
920 		unlock_page(cursor);
921 
922 	return 0;
923 }
924 
925 #ifdef CONFIG_ZPOOL
926 static unsigned long find_deferred_handle_obj(struct size_class *class,
927 		struct page *page, int *obj_idx);
928 
929 /*
930  * Free all the deferred handles whose objects are freed in zs_free.
931  */
932 static void free_handles(struct zs_pool *pool, struct size_class *class,
933 		struct zspage *zspage)
934 {
935 	int obj_idx = 0;
936 	struct page *page = get_first_page(zspage);
937 	unsigned long handle;
938 
939 	while (1) {
940 		handle = find_deferred_handle_obj(class, page, &obj_idx);
941 		if (!handle) {
942 			page = get_next_page(page);
943 			if (!page)
944 				break;
945 			obj_idx = 0;
946 			continue;
947 		}
948 
949 		cache_free_handle(pool, handle);
950 		obj_idx++;
951 	}
952 }
953 #else
954 static inline void free_handles(struct zs_pool *pool, struct size_class *class,
955 		struct zspage *zspage) {}
956 #endif
957 
958 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
959 				struct zspage *zspage)
960 {
961 	struct page *page, *next;
962 	int fg;
963 	unsigned int class_idx;
964 
965 	get_zspage_mapping(zspage, &class_idx, &fg);
966 
967 	assert_spin_locked(&pool->lock);
968 
969 	VM_BUG_ON(get_zspage_inuse(zspage));
970 	VM_BUG_ON(fg != ZS_INUSE_RATIO_0);
971 
972 	/* Free all deferred handles from zs_free */
973 	free_handles(pool, class, zspage);
974 
975 	next = page = get_first_page(zspage);
976 	do {
977 		VM_BUG_ON_PAGE(!PageLocked(page), page);
978 		next = get_next_page(page);
979 		reset_page(page);
980 		unlock_page(page);
981 		dec_zone_page_state(page, NR_ZSPAGES);
982 		put_page(page);
983 		page = next;
984 	} while (page != NULL);
985 
986 	cache_free_zspage(pool, zspage);
987 
988 	class_stat_dec(class, ZS_OBJS_ALLOCATED, class->objs_per_zspage);
989 	atomic_long_sub(class->pages_per_zspage, &pool->pages_allocated);
990 }
991 
992 static void free_zspage(struct zs_pool *pool, struct size_class *class,
993 				struct zspage *zspage)
994 {
995 	VM_BUG_ON(get_zspage_inuse(zspage));
996 	VM_BUG_ON(list_empty(&zspage->list));
997 
998 	/*
999 	 * Since zs_free couldn't be sleepable, this function cannot call
1000 	 * lock_page. The page locks trylock_zspage got will be released
1001 	 * by __free_zspage.
1002 	 */
1003 	if (!trylock_zspage(zspage)) {
1004 		kick_deferred_free(pool);
1005 		return;
1006 	}
1007 
1008 	remove_zspage(class, zspage, ZS_INUSE_RATIO_0);
1009 #ifdef CONFIG_ZPOOL
1010 	list_del(&zspage->lru);
1011 #endif
1012 	__free_zspage(pool, class, zspage);
1013 }
1014 
1015 /* Initialize a newly allocated zspage */
1016 static void init_zspage(struct size_class *class, struct zspage *zspage)
1017 {
1018 	unsigned int freeobj = 1;
1019 	unsigned long off = 0;
1020 	struct page *page = get_first_page(zspage);
1021 
1022 	while (page) {
1023 		struct page *next_page;
1024 		struct link_free *link;
1025 		void *vaddr;
1026 
1027 		set_first_obj_offset(page, off);
1028 
1029 		vaddr = kmap_atomic(page);
1030 		link = (struct link_free *)vaddr + off / sizeof(*link);
1031 
1032 		while ((off += class->size) < PAGE_SIZE) {
1033 			link->next = freeobj++ << OBJ_TAG_BITS;
1034 			link += class->size / sizeof(*link);
1035 		}
1036 
1037 		/*
1038 		 * We now come to the last (full or partial) object on this
1039 		 * page, which must point to the first object on the next
1040 		 * page (if present)
1041 		 */
1042 		next_page = get_next_page(page);
1043 		if (next_page) {
1044 			link->next = freeobj++ << OBJ_TAG_BITS;
1045 		} else {
1046 			/*
1047 			 * Reset OBJ_TAG_BITS bit to last link to tell
1048 			 * whether it's allocated object or not.
1049 			 */
1050 			link->next = -1UL << OBJ_TAG_BITS;
1051 		}
1052 		kunmap_atomic(vaddr);
1053 		page = next_page;
1054 		off %= PAGE_SIZE;
1055 	}
1056 
1057 #ifdef CONFIG_ZPOOL
1058 	INIT_LIST_HEAD(&zspage->lru);
1059 	zspage->under_reclaim = false;
1060 #endif
1061 
1062 	set_freeobj(zspage, 0);
1063 }
1064 
1065 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1066 				struct page *pages[])
1067 {
1068 	int i;
1069 	struct page *page;
1070 	struct page *prev_page = NULL;
1071 	int nr_pages = class->pages_per_zspage;
1072 
1073 	/*
1074 	 * Allocate individual pages and link them together as:
1075 	 * 1. all pages are linked together using page->index
1076 	 * 2. each sub-page point to zspage using page->private
1077 	 *
1078 	 * we set PG_private to identify the first page (i.e. no other sub-page
1079 	 * has this flag set).
1080 	 */
1081 	for (i = 0; i < nr_pages; i++) {
1082 		page = pages[i];
1083 		set_page_private(page, (unsigned long)zspage);
1084 		page->index = 0;
1085 		if (i == 0) {
1086 			zspage->first_page = page;
1087 			SetPagePrivate(page);
1088 			if (unlikely(class->objs_per_zspage == 1 &&
1089 					class->pages_per_zspage == 1))
1090 				SetZsHugePage(zspage);
1091 		} else {
1092 			prev_page->index = (unsigned long)page;
1093 		}
1094 		prev_page = page;
1095 	}
1096 }
1097 
1098 /*
1099  * Allocate a zspage for the given size class
1100  */
1101 static struct zspage *alloc_zspage(struct zs_pool *pool,
1102 					struct size_class *class,
1103 					gfp_t gfp)
1104 {
1105 	int i;
1106 	struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1107 	struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1108 
1109 	if (!zspage)
1110 		return NULL;
1111 
1112 	zspage->magic = ZSPAGE_MAGIC;
1113 	migrate_lock_init(zspage);
1114 
1115 	for (i = 0; i < class->pages_per_zspage; i++) {
1116 		struct page *page;
1117 
1118 		page = alloc_page(gfp);
1119 		if (!page) {
1120 			while (--i >= 0) {
1121 				dec_zone_page_state(pages[i], NR_ZSPAGES);
1122 				__free_page(pages[i]);
1123 			}
1124 			cache_free_zspage(pool, zspage);
1125 			return NULL;
1126 		}
1127 
1128 		inc_zone_page_state(page, NR_ZSPAGES);
1129 		pages[i] = page;
1130 	}
1131 
1132 	create_page_chain(class, zspage, pages);
1133 	init_zspage(class, zspage);
1134 	zspage->pool = pool;
1135 
1136 	return zspage;
1137 }
1138 
1139 static struct zspage *find_get_zspage(struct size_class *class)
1140 {
1141 	int i;
1142 	struct zspage *zspage;
1143 
1144 	for (i = ZS_INUSE_RATIO_99; i >= ZS_INUSE_RATIO_0; i--) {
1145 		zspage = list_first_entry_or_null(&class->fullness_list[i],
1146 						  struct zspage, list);
1147 		if (zspage)
1148 			break;
1149 	}
1150 
1151 	return zspage;
1152 }
1153 
1154 static inline int __zs_cpu_up(struct mapping_area *area)
1155 {
1156 	/*
1157 	 * Make sure we don't leak memory if a cpu UP notification
1158 	 * and zs_init() race and both call zs_cpu_up() on the same cpu
1159 	 */
1160 	if (area->vm_buf)
1161 		return 0;
1162 	area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1163 	if (!area->vm_buf)
1164 		return -ENOMEM;
1165 	return 0;
1166 }
1167 
1168 static inline void __zs_cpu_down(struct mapping_area *area)
1169 {
1170 	kfree(area->vm_buf);
1171 	area->vm_buf = NULL;
1172 }
1173 
1174 static void *__zs_map_object(struct mapping_area *area,
1175 			struct page *pages[2], int off, int size)
1176 {
1177 	int sizes[2];
1178 	void *addr;
1179 	char *buf = area->vm_buf;
1180 
1181 	/* disable page faults to match kmap_atomic() return conditions */
1182 	pagefault_disable();
1183 
1184 	/* no read fastpath */
1185 	if (area->vm_mm == ZS_MM_WO)
1186 		goto out;
1187 
1188 	sizes[0] = PAGE_SIZE - off;
1189 	sizes[1] = size - sizes[0];
1190 
1191 	/* copy object to per-cpu buffer */
1192 	addr = kmap_atomic(pages[0]);
1193 	memcpy(buf, addr + off, sizes[0]);
1194 	kunmap_atomic(addr);
1195 	addr = kmap_atomic(pages[1]);
1196 	memcpy(buf + sizes[0], addr, sizes[1]);
1197 	kunmap_atomic(addr);
1198 out:
1199 	return area->vm_buf;
1200 }
1201 
1202 static void __zs_unmap_object(struct mapping_area *area,
1203 			struct page *pages[2], int off, int size)
1204 {
1205 	int sizes[2];
1206 	void *addr;
1207 	char *buf;
1208 
1209 	/* no write fastpath */
1210 	if (area->vm_mm == ZS_MM_RO)
1211 		goto out;
1212 
1213 	buf = area->vm_buf;
1214 	buf = buf + ZS_HANDLE_SIZE;
1215 	size -= ZS_HANDLE_SIZE;
1216 	off += ZS_HANDLE_SIZE;
1217 
1218 	sizes[0] = PAGE_SIZE - off;
1219 	sizes[1] = size - sizes[0];
1220 
1221 	/* copy per-cpu buffer to object */
1222 	addr = kmap_atomic(pages[0]);
1223 	memcpy(addr + off, buf, sizes[0]);
1224 	kunmap_atomic(addr);
1225 	addr = kmap_atomic(pages[1]);
1226 	memcpy(addr, buf + sizes[0], sizes[1]);
1227 	kunmap_atomic(addr);
1228 
1229 out:
1230 	/* enable page faults to match kunmap_atomic() return conditions */
1231 	pagefault_enable();
1232 }
1233 
1234 static int zs_cpu_prepare(unsigned int cpu)
1235 {
1236 	struct mapping_area *area;
1237 
1238 	area = &per_cpu(zs_map_area, cpu);
1239 	return __zs_cpu_up(area);
1240 }
1241 
1242 static int zs_cpu_dead(unsigned int cpu)
1243 {
1244 	struct mapping_area *area;
1245 
1246 	area = &per_cpu(zs_map_area, cpu);
1247 	__zs_cpu_down(area);
1248 	return 0;
1249 }
1250 
1251 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1252 					int objs_per_zspage)
1253 {
1254 	if (prev->pages_per_zspage == pages_per_zspage &&
1255 		prev->objs_per_zspage == objs_per_zspage)
1256 		return true;
1257 
1258 	return false;
1259 }
1260 
1261 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1262 {
1263 	return get_zspage_inuse(zspage) == class->objs_per_zspage;
1264 }
1265 
1266 /**
1267  * zs_lookup_class_index() - Returns index of the zsmalloc &size_class
1268  * that hold objects of the provided size.
1269  * @pool: zsmalloc pool to use
1270  * @size: object size
1271  *
1272  * Context: Any context.
1273  *
1274  * Return: the index of the zsmalloc &size_class that hold objects of the
1275  * provided size.
1276  */
1277 unsigned int zs_lookup_class_index(struct zs_pool *pool, unsigned int size)
1278 {
1279 	struct size_class *class;
1280 
1281 	class = pool->size_class[get_size_class_index(size)];
1282 
1283 	return class->index;
1284 }
1285 EXPORT_SYMBOL_GPL(zs_lookup_class_index);
1286 
1287 unsigned long zs_get_total_pages(struct zs_pool *pool)
1288 {
1289 	return atomic_long_read(&pool->pages_allocated);
1290 }
1291 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1292 
1293 /**
1294  * zs_map_object - get address of allocated object from handle.
1295  * @pool: pool from which the object was allocated
1296  * @handle: handle returned from zs_malloc
1297  * @mm: mapping mode to use
1298  *
1299  * Before using an object allocated from zs_malloc, it must be mapped using
1300  * this function. When done with the object, it must be unmapped using
1301  * zs_unmap_object.
1302  *
1303  * Only one object can be mapped per cpu at a time. There is no protection
1304  * against nested mappings.
1305  *
1306  * This function returns with preemption and page faults disabled.
1307  */
1308 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1309 			enum zs_mapmode mm)
1310 {
1311 	struct zspage *zspage;
1312 	struct page *page;
1313 	unsigned long obj, off;
1314 	unsigned int obj_idx;
1315 
1316 	struct size_class *class;
1317 	struct mapping_area *area;
1318 	struct page *pages[2];
1319 	void *ret;
1320 
1321 	/*
1322 	 * Because we use per-cpu mapping areas shared among the
1323 	 * pools/users, we can't allow mapping in interrupt context
1324 	 * because it can corrupt another users mappings.
1325 	 */
1326 	BUG_ON(in_interrupt());
1327 
1328 	/* It guarantees it can get zspage from handle safely */
1329 	spin_lock(&pool->lock);
1330 	obj = handle_to_obj(handle);
1331 	obj_to_location(obj, &page, &obj_idx);
1332 	zspage = get_zspage(page);
1333 
1334 #ifdef CONFIG_ZPOOL
1335 	/*
1336 	 * Move the zspage to front of pool's LRU.
1337 	 *
1338 	 * Note that this is swap-specific, so by definition there are no ongoing
1339 	 * accesses to the memory while the page is swapped out that would make
1340 	 * it "hot". A new entry is hot, then ages to the tail until it gets either
1341 	 * written back or swaps back in.
1342 	 *
1343 	 * Furthermore, map is also called during writeback. We must not put an
1344 	 * isolated page on the LRU mid-reclaim.
1345 	 *
1346 	 * As a result, only update the LRU when the page is mapped for write
1347 	 * when it's first instantiated.
1348 	 *
1349 	 * This is a deviation from the other backends, which perform this update
1350 	 * in the allocation function (zbud_alloc, z3fold_alloc).
1351 	 */
1352 	if (mm == ZS_MM_WO) {
1353 		if (!list_empty(&zspage->lru))
1354 			list_del(&zspage->lru);
1355 		list_add(&zspage->lru, &pool->lru);
1356 	}
1357 #endif
1358 
1359 	/*
1360 	 * migration cannot move any zpages in this zspage. Here, pool->lock
1361 	 * is too heavy since callers would take some time until they calls
1362 	 * zs_unmap_object API so delegate the locking from class to zspage
1363 	 * which is smaller granularity.
1364 	 */
1365 	migrate_read_lock(zspage);
1366 	spin_unlock(&pool->lock);
1367 
1368 	class = zspage_class(pool, zspage);
1369 	off = (class->size * obj_idx) & ~PAGE_MASK;
1370 
1371 	local_lock(&zs_map_area.lock);
1372 	area = this_cpu_ptr(&zs_map_area);
1373 	area->vm_mm = mm;
1374 	if (off + class->size <= PAGE_SIZE) {
1375 		/* this object is contained entirely within a page */
1376 		area->vm_addr = kmap_atomic(page);
1377 		ret = area->vm_addr + off;
1378 		goto out;
1379 	}
1380 
1381 	/* this object spans two pages */
1382 	pages[0] = page;
1383 	pages[1] = get_next_page(page);
1384 	BUG_ON(!pages[1]);
1385 
1386 	ret = __zs_map_object(area, pages, off, class->size);
1387 out:
1388 	if (likely(!ZsHugePage(zspage)))
1389 		ret += ZS_HANDLE_SIZE;
1390 
1391 	return ret;
1392 }
1393 EXPORT_SYMBOL_GPL(zs_map_object);
1394 
1395 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1396 {
1397 	struct zspage *zspage;
1398 	struct page *page;
1399 	unsigned long obj, off;
1400 	unsigned int obj_idx;
1401 
1402 	struct size_class *class;
1403 	struct mapping_area *area;
1404 
1405 	obj = handle_to_obj(handle);
1406 	obj_to_location(obj, &page, &obj_idx);
1407 	zspage = get_zspage(page);
1408 	class = zspage_class(pool, zspage);
1409 	off = (class->size * obj_idx) & ~PAGE_MASK;
1410 
1411 	area = this_cpu_ptr(&zs_map_area);
1412 	if (off + class->size <= PAGE_SIZE)
1413 		kunmap_atomic(area->vm_addr);
1414 	else {
1415 		struct page *pages[2];
1416 
1417 		pages[0] = page;
1418 		pages[1] = get_next_page(page);
1419 		BUG_ON(!pages[1]);
1420 
1421 		__zs_unmap_object(area, pages, off, class->size);
1422 	}
1423 	local_unlock(&zs_map_area.lock);
1424 
1425 	migrate_read_unlock(zspage);
1426 }
1427 EXPORT_SYMBOL_GPL(zs_unmap_object);
1428 
1429 /**
1430  * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1431  *                        zsmalloc &size_class.
1432  * @pool: zsmalloc pool to use
1433  *
1434  * The function returns the size of the first huge class - any object of equal
1435  * or bigger size will be stored in zspage consisting of a single physical
1436  * page.
1437  *
1438  * Context: Any context.
1439  *
1440  * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1441  */
1442 size_t zs_huge_class_size(struct zs_pool *pool)
1443 {
1444 	return huge_class_size;
1445 }
1446 EXPORT_SYMBOL_GPL(zs_huge_class_size);
1447 
1448 static unsigned long obj_malloc(struct zs_pool *pool,
1449 				struct zspage *zspage, unsigned long handle)
1450 {
1451 	int i, nr_page, offset;
1452 	unsigned long obj;
1453 	struct link_free *link;
1454 	struct size_class *class;
1455 
1456 	struct page *m_page;
1457 	unsigned long m_offset;
1458 	void *vaddr;
1459 
1460 	class = pool->size_class[zspage->class];
1461 	handle |= OBJ_ALLOCATED_TAG;
1462 	obj = get_freeobj(zspage);
1463 
1464 	offset = obj * class->size;
1465 	nr_page = offset >> PAGE_SHIFT;
1466 	m_offset = offset & ~PAGE_MASK;
1467 	m_page = get_first_page(zspage);
1468 
1469 	for (i = 0; i < nr_page; i++)
1470 		m_page = get_next_page(m_page);
1471 
1472 	vaddr = kmap_atomic(m_page);
1473 	link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1474 	set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1475 	if (likely(!ZsHugePage(zspage)))
1476 		/* record handle in the header of allocated chunk */
1477 		link->handle = handle;
1478 	else
1479 		/* record handle to page->index */
1480 		zspage->first_page->index = handle;
1481 
1482 	kunmap_atomic(vaddr);
1483 	mod_zspage_inuse(zspage, 1);
1484 
1485 	obj = location_to_obj(m_page, obj);
1486 
1487 	return obj;
1488 }
1489 
1490 
1491 /**
1492  * zs_malloc - Allocate block of given size from pool.
1493  * @pool: pool to allocate from
1494  * @size: size of block to allocate
1495  * @gfp: gfp flags when allocating object
1496  *
1497  * On success, handle to the allocated object is returned,
1498  * otherwise an ERR_PTR().
1499  * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1500  */
1501 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1502 {
1503 	unsigned long handle, obj;
1504 	struct size_class *class;
1505 	int newfg;
1506 	struct zspage *zspage;
1507 
1508 	if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1509 		return (unsigned long)ERR_PTR(-EINVAL);
1510 
1511 	handle = cache_alloc_handle(pool, gfp);
1512 	if (!handle)
1513 		return (unsigned long)ERR_PTR(-ENOMEM);
1514 
1515 	/* extra space in chunk to keep the handle */
1516 	size += ZS_HANDLE_SIZE;
1517 	class = pool->size_class[get_size_class_index(size)];
1518 
1519 	/* pool->lock effectively protects the zpage migration */
1520 	spin_lock(&pool->lock);
1521 	zspage = find_get_zspage(class);
1522 	if (likely(zspage)) {
1523 		obj = obj_malloc(pool, zspage, handle);
1524 		/* Now move the zspage to another fullness group, if required */
1525 		fix_fullness_group(class, zspage);
1526 		record_obj(handle, obj);
1527 		class_stat_inc(class, ZS_OBJS_INUSE, 1);
1528 		spin_unlock(&pool->lock);
1529 
1530 		return handle;
1531 	}
1532 
1533 	spin_unlock(&pool->lock);
1534 
1535 	zspage = alloc_zspage(pool, class, gfp);
1536 	if (!zspage) {
1537 		cache_free_handle(pool, handle);
1538 		return (unsigned long)ERR_PTR(-ENOMEM);
1539 	}
1540 
1541 	spin_lock(&pool->lock);
1542 	obj = obj_malloc(pool, zspage, handle);
1543 	newfg = get_fullness_group(class, zspage);
1544 	insert_zspage(class, zspage, newfg);
1545 	set_zspage_mapping(zspage, class->index, newfg);
1546 	record_obj(handle, obj);
1547 	atomic_long_add(class->pages_per_zspage, &pool->pages_allocated);
1548 	class_stat_inc(class, ZS_OBJS_ALLOCATED, class->objs_per_zspage);
1549 	class_stat_inc(class, ZS_OBJS_INUSE, 1);
1550 
1551 	/* We completely set up zspage so mark them as movable */
1552 	SetZsPageMovable(pool, zspage);
1553 	spin_unlock(&pool->lock);
1554 
1555 	return handle;
1556 }
1557 EXPORT_SYMBOL_GPL(zs_malloc);
1558 
1559 static void obj_free(int class_size, unsigned long obj, unsigned long *handle)
1560 {
1561 	struct link_free *link;
1562 	struct zspage *zspage;
1563 	struct page *f_page;
1564 	unsigned long f_offset;
1565 	unsigned int f_objidx;
1566 	void *vaddr;
1567 
1568 	obj_to_location(obj, &f_page, &f_objidx);
1569 	f_offset = (class_size * f_objidx) & ~PAGE_MASK;
1570 	zspage = get_zspage(f_page);
1571 
1572 	vaddr = kmap_atomic(f_page);
1573 	link = (struct link_free *)(vaddr + f_offset);
1574 
1575 	if (handle) {
1576 #ifdef CONFIG_ZPOOL
1577 		/* Stores the (deferred) handle in the object's header */
1578 		*handle |= OBJ_DEFERRED_HANDLE_TAG;
1579 		*handle &= ~OBJ_ALLOCATED_TAG;
1580 
1581 		if (likely(!ZsHugePage(zspage)))
1582 			link->deferred_handle = *handle;
1583 		else
1584 			f_page->index = *handle;
1585 #endif
1586 	} else {
1587 		/* Insert this object in containing zspage's freelist */
1588 		if (likely(!ZsHugePage(zspage)))
1589 			link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1590 		else
1591 			f_page->index = 0;
1592 		set_freeobj(zspage, f_objidx);
1593 	}
1594 
1595 	kunmap_atomic(vaddr);
1596 	mod_zspage_inuse(zspage, -1);
1597 }
1598 
1599 void zs_free(struct zs_pool *pool, unsigned long handle)
1600 {
1601 	struct zspage *zspage;
1602 	struct page *f_page;
1603 	unsigned long obj;
1604 	struct size_class *class;
1605 	int fullness;
1606 
1607 	if (IS_ERR_OR_NULL((void *)handle))
1608 		return;
1609 
1610 	/*
1611 	 * The pool->lock protects the race with zpage's migration
1612 	 * so it's safe to get the page from handle.
1613 	 */
1614 	spin_lock(&pool->lock);
1615 	obj = handle_to_obj(handle);
1616 	obj_to_page(obj, &f_page);
1617 	zspage = get_zspage(f_page);
1618 	class = zspage_class(pool, zspage);
1619 
1620 	class_stat_dec(class, ZS_OBJS_INUSE, 1);
1621 
1622 #ifdef CONFIG_ZPOOL
1623 	if (zspage->under_reclaim) {
1624 		/*
1625 		 * Reclaim needs the handles during writeback. It'll free
1626 		 * them along with the zspage when it's done with them.
1627 		 *
1628 		 * Record current deferred handle in the object's header.
1629 		 */
1630 		obj_free(class->size, obj, &handle);
1631 		spin_unlock(&pool->lock);
1632 		return;
1633 	}
1634 #endif
1635 	obj_free(class->size, obj, NULL);
1636 
1637 	fullness = fix_fullness_group(class, zspage);
1638 	if (fullness == ZS_INUSE_RATIO_0)
1639 		free_zspage(pool, class, zspage);
1640 
1641 	spin_unlock(&pool->lock);
1642 	cache_free_handle(pool, handle);
1643 }
1644 EXPORT_SYMBOL_GPL(zs_free);
1645 
1646 static void zs_object_copy(struct size_class *class, unsigned long dst,
1647 				unsigned long src)
1648 {
1649 	struct page *s_page, *d_page;
1650 	unsigned int s_objidx, d_objidx;
1651 	unsigned long s_off, d_off;
1652 	void *s_addr, *d_addr;
1653 	int s_size, d_size, size;
1654 	int written = 0;
1655 
1656 	s_size = d_size = class->size;
1657 
1658 	obj_to_location(src, &s_page, &s_objidx);
1659 	obj_to_location(dst, &d_page, &d_objidx);
1660 
1661 	s_off = (class->size * s_objidx) & ~PAGE_MASK;
1662 	d_off = (class->size * d_objidx) & ~PAGE_MASK;
1663 
1664 	if (s_off + class->size > PAGE_SIZE)
1665 		s_size = PAGE_SIZE - s_off;
1666 
1667 	if (d_off + class->size > PAGE_SIZE)
1668 		d_size = PAGE_SIZE - d_off;
1669 
1670 	s_addr = kmap_atomic(s_page);
1671 	d_addr = kmap_atomic(d_page);
1672 
1673 	while (1) {
1674 		size = min(s_size, d_size);
1675 		memcpy(d_addr + d_off, s_addr + s_off, size);
1676 		written += size;
1677 
1678 		if (written == class->size)
1679 			break;
1680 
1681 		s_off += size;
1682 		s_size -= size;
1683 		d_off += size;
1684 		d_size -= size;
1685 
1686 		/*
1687 		 * Calling kunmap_atomic(d_addr) is necessary. kunmap_atomic()
1688 		 * calls must occurs in reverse order of calls to kmap_atomic().
1689 		 * So, to call kunmap_atomic(s_addr) we should first call
1690 		 * kunmap_atomic(d_addr). For more details see
1691 		 * Documentation/mm/highmem.rst.
1692 		 */
1693 		if (s_off >= PAGE_SIZE) {
1694 			kunmap_atomic(d_addr);
1695 			kunmap_atomic(s_addr);
1696 			s_page = get_next_page(s_page);
1697 			s_addr = kmap_atomic(s_page);
1698 			d_addr = kmap_atomic(d_page);
1699 			s_size = class->size - written;
1700 			s_off = 0;
1701 		}
1702 
1703 		if (d_off >= PAGE_SIZE) {
1704 			kunmap_atomic(d_addr);
1705 			d_page = get_next_page(d_page);
1706 			d_addr = kmap_atomic(d_page);
1707 			d_size = class->size - written;
1708 			d_off = 0;
1709 		}
1710 	}
1711 
1712 	kunmap_atomic(d_addr);
1713 	kunmap_atomic(s_addr);
1714 }
1715 
1716 /*
1717  * Find object with a certain tag in zspage from index object and
1718  * return handle.
1719  */
1720 static unsigned long find_tagged_obj(struct size_class *class,
1721 					struct page *page, int *obj_idx, int tag)
1722 {
1723 	unsigned int offset;
1724 	int index = *obj_idx;
1725 	unsigned long handle = 0;
1726 	void *addr = kmap_atomic(page);
1727 
1728 	offset = get_first_obj_offset(page);
1729 	offset += class->size * index;
1730 
1731 	while (offset < PAGE_SIZE) {
1732 		if (obj_tagged(page, addr + offset, &handle, tag))
1733 			break;
1734 
1735 		offset += class->size;
1736 		index++;
1737 	}
1738 
1739 	kunmap_atomic(addr);
1740 
1741 	*obj_idx = index;
1742 
1743 	return handle;
1744 }
1745 
1746 /*
1747  * Find alloced object in zspage from index object and
1748  * return handle.
1749  */
1750 static unsigned long find_alloced_obj(struct size_class *class,
1751 					struct page *page, int *obj_idx)
1752 {
1753 	return find_tagged_obj(class, page, obj_idx, OBJ_ALLOCATED_TAG);
1754 }
1755 
1756 #ifdef CONFIG_ZPOOL
1757 /*
1758  * Find object storing a deferred handle in header in zspage from index object
1759  * and return handle.
1760  */
1761 static unsigned long find_deferred_handle_obj(struct size_class *class,
1762 		struct page *page, int *obj_idx)
1763 {
1764 	return find_tagged_obj(class, page, obj_idx, OBJ_DEFERRED_HANDLE_TAG);
1765 }
1766 #endif
1767 
1768 struct zs_compact_control {
1769 	/* Source spage for migration which could be a subpage of zspage */
1770 	struct page *s_page;
1771 	/* Destination page for migration which should be a first page
1772 	 * of zspage. */
1773 	struct page *d_page;
1774 	 /* Starting object index within @s_page which used for live object
1775 	  * in the subpage. */
1776 	int obj_idx;
1777 };
1778 
1779 static void migrate_zspage(struct zs_pool *pool, struct size_class *class,
1780 			   struct zs_compact_control *cc)
1781 {
1782 	unsigned long used_obj, free_obj;
1783 	unsigned long handle;
1784 	struct page *s_page = cc->s_page;
1785 	struct page *d_page = cc->d_page;
1786 	int obj_idx = cc->obj_idx;
1787 
1788 	while (1) {
1789 		handle = find_alloced_obj(class, s_page, &obj_idx);
1790 		if (!handle) {
1791 			s_page = get_next_page(s_page);
1792 			if (!s_page)
1793 				break;
1794 			obj_idx = 0;
1795 			continue;
1796 		}
1797 
1798 		/* Stop if there is no more space */
1799 		if (zspage_full(class, get_zspage(d_page)))
1800 			break;
1801 
1802 		used_obj = handle_to_obj(handle);
1803 		free_obj = obj_malloc(pool, get_zspage(d_page), handle);
1804 		zs_object_copy(class, free_obj, used_obj);
1805 		obj_idx++;
1806 		record_obj(handle, free_obj);
1807 		obj_free(class->size, used_obj, NULL);
1808 	}
1809 
1810 	/* Remember last position in this iteration */
1811 	cc->s_page = s_page;
1812 	cc->obj_idx = obj_idx;
1813 }
1814 
1815 static struct zspage *isolate_src_zspage(struct size_class *class)
1816 {
1817 	struct zspage *zspage;
1818 	int fg;
1819 
1820 	for (fg = ZS_INUSE_RATIO_10; fg <= ZS_INUSE_RATIO_99; fg++) {
1821 		zspage = list_first_entry_or_null(&class->fullness_list[fg],
1822 						  struct zspage, list);
1823 		if (zspage) {
1824 			remove_zspage(class, zspage, fg);
1825 			return zspage;
1826 		}
1827 	}
1828 
1829 	return zspage;
1830 }
1831 
1832 static struct zspage *isolate_dst_zspage(struct size_class *class)
1833 {
1834 	struct zspage *zspage;
1835 	int fg;
1836 
1837 	for (fg = ZS_INUSE_RATIO_99; fg >= ZS_INUSE_RATIO_10; fg--) {
1838 		zspage = list_first_entry_or_null(&class->fullness_list[fg],
1839 						  struct zspage, list);
1840 		if (zspage) {
1841 			remove_zspage(class, zspage, fg);
1842 			return zspage;
1843 		}
1844 	}
1845 
1846 	return zspage;
1847 }
1848 
1849 /*
1850  * putback_zspage - add @zspage into right class's fullness list
1851  * @class: destination class
1852  * @zspage: target page
1853  *
1854  * Return @zspage's fullness status
1855  */
1856 static int putback_zspage(struct size_class *class, struct zspage *zspage)
1857 {
1858 	int fullness;
1859 
1860 	fullness = get_fullness_group(class, zspage);
1861 	insert_zspage(class, zspage, fullness);
1862 	set_zspage_mapping(zspage, class->index, fullness);
1863 
1864 	return fullness;
1865 }
1866 
1867 #if defined(CONFIG_ZPOOL) || defined(CONFIG_COMPACTION)
1868 /*
1869  * To prevent zspage destroy during migration, zspage freeing should
1870  * hold locks of all pages in the zspage.
1871  */
1872 static void lock_zspage(struct zspage *zspage)
1873 {
1874 	struct page *curr_page, *page;
1875 
1876 	/*
1877 	 * Pages we haven't locked yet can be migrated off the list while we're
1878 	 * trying to lock them, so we need to be careful and only attempt to
1879 	 * lock each page under migrate_read_lock(). Otherwise, the page we lock
1880 	 * may no longer belong to the zspage. This means that we may wait for
1881 	 * the wrong page to unlock, so we must take a reference to the page
1882 	 * prior to waiting for it to unlock outside migrate_read_lock().
1883 	 */
1884 	while (1) {
1885 		migrate_read_lock(zspage);
1886 		page = get_first_page(zspage);
1887 		if (trylock_page(page))
1888 			break;
1889 		get_page(page);
1890 		migrate_read_unlock(zspage);
1891 		wait_on_page_locked(page);
1892 		put_page(page);
1893 	}
1894 
1895 	curr_page = page;
1896 	while ((page = get_next_page(curr_page))) {
1897 		if (trylock_page(page)) {
1898 			curr_page = page;
1899 		} else {
1900 			get_page(page);
1901 			migrate_read_unlock(zspage);
1902 			wait_on_page_locked(page);
1903 			put_page(page);
1904 			migrate_read_lock(zspage);
1905 		}
1906 	}
1907 	migrate_read_unlock(zspage);
1908 }
1909 #endif /* defined(CONFIG_ZPOOL) || defined(CONFIG_COMPACTION) */
1910 
1911 #ifdef CONFIG_ZPOOL
1912 /*
1913  * Unlocks all the pages of the zspage.
1914  *
1915  * pool->lock must be held before this function is called
1916  * to prevent the underlying pages from migrating.
1917  */
1918 static void unlock_zspage(struct zspage *zspage)
1919 {
1920 	struct page *page = get_first_page(zspage);
1921 
1922 	do {
1923 		unlock_page(page);
1924 	} while ((page = get_next_page(page)) != NULL);
1925 }
1926 #endif /* CONFIG_ZPOOL */
1927 
1928 static void migrate_lock_init(struct zspage *zspage)
1929 {
1930 	rwlock_init(&zspage->lock);
1931 }
1932 
1933 static void migrate_read_lock(struct zspage *zspage) __acquires(&zspage->lock)
1934 {
1935 	read_lock(&zspage->lock);
1936 }
1937 
1938 static void migrate_read_unlock(struct zspage *zspage) __releases(&zspage->lock)
1939 {
1940 	read_unlock(&zspage->lock);
1941 }
1942 
1943 #ifdef CONFIG_COMPACTION
1944 static void migrate_write_lock(struct zspage *zspage)
1945 {
1946 	write_lock(&zspage->lock);
1947 }
1948 
1949 static void migrate_write_lock_nested(struct zspage *zspage)
1950 {
1951 	write_lock_nested(&zspage->lock, SINGLE_DEPTH_NESTING);
1952 }
1953 
1954 static void migrate_write_unlock(struct zspage *zspage)
1955 {
1956 	write_unlock(&zspage->lock);
1957 }
1958 
1959 /* Number of isolated subpage for *page migration* in this zspage */
1960 static void inc_zspage_isolation(struct zspage *zspage)
1961 {
1962 	zspage->isolated++;
1963 }
1964 
1965 static void dec_zspage_isolation(struct zspage *zspage)
1966 {
1967 	VM_BUG_ON(zspage->isolated == 0);
1968 	zspage->isolated--;
1969 }
1970 
1971 static const struct movable_operations zsmalloc_mops;
1972 
1973 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1974 				struct page *newpage, struct page *oldpage)
1975 {
1976 	struct page *page;
1977 	struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1978 	int idx = 0;
1979 
1980 	page = get_first_page(zspage);
1981 	do {
1982 		if (page == oldpage)
1983 			pages[idx] = newpage;
1984 		else
1985 			pages[idx] = page;
1986 		idx++;
1987 	} while ((page = get_next_page(page)) != NULL);
1988 
1989 	create_page_chain(class, zspage, pages);
1990 	set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1991 	if (unlikely(ZsHugePage(zspage)))
1992 		newpage->index = oldpage->index;
1993 	__SetPageMovable(newpage, &zsmalloc_mops);
1994 }
1995 
1996 static bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1997 {
1998 	struct zspage *zspage;
1999 
2000 	/*
2001 	 * Page is locked so zspage couldn't be destroyed. For detail, look at
2002 	 * lock_zspage in free_zspage.
2003 	 */
2004 	VM_BUG_ON_PAGE(PageIsolated(page), page);
2005 
2006 	zspage = get_zspage(page);
2007 	migrate_write_lock(zspage);
2008 	inc_zspage_isolation(zspage);
2009 	migrate_write_unlock(zspage);
2010 
2011 	return true;
2012 }
2013 
2014 static int zs_page_migrate(struct page *newpage, struct page *page,
2015 		enum migrate_mode mode)
2016 {
2017 	struct zs_pool *pool;
2018 	struct size_class *class;
2019 	struct zspage *zspage;
2020 	struct page *dummy;
2021 	void *s_addr, *d_addr, *addr;
2022 	unsigned int offset;
2023 	unsigned long handle;
2024 	unsigned long old_obj, new_obj;
2025 	unsigned int obj_idx;
2026 
2027 	/*
2028 	 * We cannot support the _NO_COPY case here, because copy needs to
2029 	 * happen under the zs lock, which does not work with
2030 	 * MIGRATE_SYNC_NO_COPY workflow.
2031 	 */
2032 	if (mode == MIGRATE_SYNC_NO_COPY)
2033 		return -EINVAL;
2034 
2035 	VM_BUG_ON_PAGE(!PageIsolated(page), page);
2036 
2037 	/* The page is locked, so this pointer must remain valid */
2038 	zspage = get_zspage(page);
2039 	pool = zspage->pool;
2040 
2041 	/*
2042 	 * The pool's lock protects the race between zpage migration
2043 	 * and zs_free.
2044 	 */
2045 	spin_lock(&pool->lock);
2046 	class = zspage_class(pool, zspage);
2047 
2048 	/* the migrate_write_lock protects zpage access via zs_map_object */
2049 	migrate_write_lock(zspage);
2050 
2051 	offset = get_first_obj_offset(page);
2052 	s_addr = kmap_atomic(page);
2053 
2054 	/*
2055 	 * Here, any user cannot access all objects in the zspage so let's move.
2056 	 */
2057 	d_addr = kmap_atomic(newpage);
2058 	memcpy(d_addr, s_addr, PAGE_SIZE);
2059 	kunmap_atomic(d_addr);
2060 
2061 	for (addr = s_addr + offset; addr < s_addr + PAGE_SIZE;
2062 					addr += class->size) {
2063 		if (obj_allocated(page, addr, &handle)) {
2064 
2065 			old_obj = handle_to_obj(handle);
2066 			obj_to_location(old_obj, &dummy, &obj_idx);
2067 			new_obj = (unsigned long)location_to_obj(newpage,
2068 								obj_idx);
2069 			record_obj(handle, new_obj);
2070 		}
2071 	}
2072 	kunmap_atomic(s_addr);
2073 
2074 	replace_sub_page(class, zspage, newpage, page);
2075 	/*
2076 	 * Since we complete the data copy and set up new zspage structure,
2077 	 * it's okay to release the pool's lock.
2078 	 */
2079 	spin_unlock(&pool->lock);
2080 	dec_zspage_isolation(zspage);
2081 	migrate_write_unlock(zspage);
2082 
2083 	get_page(newpage);
2084 	if (page_zone(newpage) != page_zone(page)) {
2085 		dec_zone_page_state(page, NR_ZSPAGES);
2086 		inc_zone_page_state(newpage, NR_ZSPAGES);
2087 	}
2088 
2089 	reset_page(page);
2090 	put_page(page);
2091 
2092 	return MIGRATEPAGE_SUCCESS;
2093 }
2094 
2095 static void zs_page_putback(struct page *page)
2096 {
2097 	struct zspage *zspage;
2098 
2099 	VM_BUG_ON_PAGE(!PageIsolated(page), page);
2100 
2101 	zspage = get_zspage(page);
2102 	migrate_write_lock(zspage);
2103 	dec_zspage_isolation(zspage);
2104 	migrate_write_unlock(zspage);
2105 }
2106 
2107 static const struct movable_operations zsmalloc_mops = {
2108 	.isolate_page = zs_page_isolate,
2109 	.migrate_page = zs_page_migrate,
2110 	.putback_page = zs_page_putback,
2111 };
2112 
2113 /*
2114  * Caller should hold page_lock of all pages in the zspage
2115  * In here, we cannot use zspage meta data.
2116  */
2117 static void async_free_zspage(struct work_struct *work)
2118 {
2119 	int i;
2120 	struct size_class *class;
2121 	unsigned int class_idx;
2122 	int fullness;
2123 	struct zspage *zspage, *tmp;
2124 	LIST_HEAD(free_pages);
2125 	struct zs_pool *pool = container_of(work, struct zs_pool,
2126 					free_work);
2127 
2128 	for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2129 		class = pool->size_class[i];
2130 		if (class->index != i)
2131 			continue;
2132 
2133 		spin_lock(&pool->lock);
2134 		list_splice_init(&class->fullness_list[ZS_INUSE_RATIO_0],
2135 				 &free_pages);
2136 		spin_unlock(&pool->lock);
2137 	}
2138 
2139 	list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2140 		list_del(&zspage->list);
2141 		lock_zspage(zspage);
2142 
2143 		get_zspage_mapping(zspage, &class_idx, &fullness);
2144 		VM_BUG_ON(fullness != ZS_INUSE_RATIO_0);
2145 		class = pool->size_class[class_idx];
2146 		spin_lock(&pool->lock);
2147 #ifdef CONFIG_ZPOOL
2148 		list_del(&zspage->lru);
2149 #endif
2150 		__free_zspage(pool, class, zspage);
2151 		spin_unlock(&pool->lock);
2152 	}
2153 };
2154 
2155 static void kick_deferred_free(struct zs_pool *pool)
2156 {
2157 	schedule_work(&pool->free_work);
2158 }
2159 
2160 static void zs_flush_migration(struct zs_pool *pool)
2161 {
2162 	flush_work(&pool->free_work);
2163 }
2164 
2165 static void init_deferred_free(struct zs_pool *pool)
2166 {
2167 	INIT_WORK(&pool->free_work, async_free_zspage);
2168 }
2169 
2170 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2171 {
2172 	struct page *page = get_first_page(zspage);
2173 
2174 	do {
2175 		WARN_ON(!trylock_page(page));
2176 		__SetPageMovable(page, &zsmalloc_mops);
2177 		unlock_page(page);
2178 	} while ((page = get_next_page(page)) != NULL);
2179 }
2180 #else
2181 static inline void zs_flush_migration(struct zs_pool *pool) { }
2182 #endif
2183 
2184 /*
2185  *
2186  * Based on the number of unused allocated objects calculate
2187  * and return the number of pages that we can free.
2188  */
2189 static unsigned long zs_can_compact(struct size_class *class)
2190 {
2191 	unsigned long obj_wasted;
2192 	unsigned long obj_allocated = zs_stat_get(class, ZS_OBJS_ALLOCATED);
2193 	unsigned long obj_used = zs_stat_get(class, ZS_OBJS_INUSE);
2194 
2195 	if (obj_allocated <= obj_used)
2196 		return 0;
2197 
2198 	obj_wasted = obj_allocated - obj_used;
2199 	obj_wasted /= class->objs_per_zspage;
2200 
2201 	return obj_wasted * class->pages_per_zspage;
2202 }
2203 
2204 static unsigned long __zs_compact(struct zs_pool *pool,
2205 				  struct size_class *class)
2206 {
2207 	struct zs_compact_control cc;
2208 	struct zspage *src_zspage = NULL;
2209 	struct zspage *dst_zspage = NULL;
2210 	unsigned long pages_freed = 0;
2211 
2212 	/*
2213 	 * protect the race between zpage migration and zs_free
2214 	 * as well as zpage allocation/free
2215 	 */
2216 	spin_lock(&pool->lock);
2217 	while (zs_can_compact(class)) {
2218 		int fg;
2219 
2220 		if (!dst_zspage) {
2221 			dst_zspage = isolate_dst_zspage(class);
2222 			if (!dst_zspage)
2223 				break;
2224 			migrate_write_lock(dst_zspage);
2225 			cc.d_page = get_first_page(dst_zspage);
2226 		}
2227 
2228 		src_zspage = isolate_src_zspage(class);
2229 		if (!src_zspage)
2230 			break;
2231 
2232 		migrate_write_lock_nested(src_zspage);
2233 
2234 		cc.obj_idx = 0;
2235 		cc.s_page = get_first_page(src_zspage);
2236 		migrate_zspage(pool, class, &cc);
2237 		fg = putback_zspage(class, src_zspage);
2238 		migrate_write_unlock(src_zspage);
2239 
2240 		if (fg == ZS_INUSE_RATIO_0) {
2241 			free_zspage(pool, class, src_zspage);
2242 			pages_freed += class->pages_per_zspage;
2243 		}
2244 		src_zspage = NULL;
2245 
2246 		if (get_fullness_group(class, dst_zspage) == ZS_INUSE_RATIO_100
2247 		    || spin_is_contended(&pool->lock)) {
2248 			putback_zspage(class, dst_zspage);
2249 			migrate_write_unlock(dst_zspage);
2250 			dst_zspage = NULL;
2251 
2252 			spin_unlock(&pool->lock);
2253 			cond_resched();
2254 			spin_lock(&pool->lock);
2255 		}
2256 	}
2257 
2258 	if (src_zspage) {
2259 		putback_zspage(class, src_zspage);
2260 		migrate_write_unlock(src_zspage);
2261 	}
2262 
2263 	if (dst_zspage) {
2264 		putback_zspage(class, dst_zspage);
2265 		migrate_write_unlock(dst_zspage);
2266 	}
2267 	spin_unlock(&pool->lock);
2268 
2269 	return pages_freed;
2270 }
2271 
2272 unsigned long zs_compact(struct zs_pool *pool)
2273 {
2274 	int i;
2275 	struct size_class *class;
2276 	unsigned long pages_freed = 0;
2277 
2278 	/*
2279 	 * Pool compaction is performed under pool->lock so it is basically
2280 	 * single-threaded. Having more than one thread in __zs_compact()
2281 	 * will increase pool->lock contention, which will impact other
2282 	 * zsmalloc operations that need pool->lock.
2283 	 */
2284 	if (atomic_xchg(&pool->compaction_in_progress, 1))
2285 		return 0;
2286 
2287 	for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2288 		class = pool->size_class[i];
2289 		if (class->index != i)
2290 			continue;
2291 		pages_freed += __zs_compact(pool, class);
2292 	}
2293 	atomic_long_add(pages_freed, &pool->stats.pages_compacted);
2294 	atomic_set(&pool->compaction_in_progress, 0);
2295 
2296 	return pages_freed;
2297 }
2298 EXPORT_SYMBOL_GPL(zs_compact);
2299 
2300 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2301 {
2302 	memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2303 }
2304 EXPORT_SYMBOL_GPL(zs_pool_stats);
2305 
2306 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2307 		struct shrink_control *sc)
2308 {
2309 	unsigned long pages_freed;
2310 	struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2311 			shrinker);
2312 
2313 	/*
2314 	 * Compact classes and calculate compaction delta.
2315 	 * Can run concurrently with a manually triggered
2316 	 * (by user) compaction.
2317 	 */
2318 	pages_freed = zs_compact(pool);
2319 
2320 	return pages_freed ? pages_freed : SHRINK_STOP;
2321 }
2322 
2323 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2324 		struct shrink_control *sc)
2325 {
2326 	int i;
2327 	struct size_class *class;
2328 	unsigned long pages_to_free = 0;
2329 	struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2330 			shrinker);
2331 
2332 	for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2333 		class = pool->size_class[i];
2334 		if (class->index != i)
2335 			continue;
2336 
2337 		pages_to_free += zs_can_compact(class);
2338 	}
2339 
2340 	return pages_to_free;
2341 }
2342 
2343 static void zs_unregister_shrinker(struct zs_pool *pool)
2344 {
2345 	unregister_shrinker(&pool->shrinker);
2346 }
2347 
2348 static int zs_register_shrinker(struct zs_pool *pool)
2349 {
2350 	pool->shrinker.scan_objects = zs_shrinker_scan;
2351 	pool->shrinker.count_objects = zs_shrinker_count;
2352 	pool->shrinker.batch = 0;
2353 	pool->shrinker.seeks = DEFAULT_SEEKS;
2354 
2355 	return register_shrinker(&pool->shrinker, "mm-zspool:%s",
2356 				 pool->name);
2357 }
2358 
2359 static int calculate_zspage_chain_size(int class_size)
2360 {
2361 	int i, min_waste = INT_MAX;
2362 	int chain_size = 1;
2363 
2364 	if (is_power_of_2(class_size))
2365 		return chain_size;
2366 
2367 	for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
2368 		int waste;
2369 
2370 		waste = (i * PAGE_SIZE) % class_size;
2371 		if (waste < min_waste) {
2372 			min_waste = waste;
2373 			chain_size = i;
2374 		}
2375 	}
2376 
2377 	return chain_size;
2378 }
2379 
2380 /**
2381  * zs_create_pool - Creates an allocation pool to work from.
2382  * @name: pool name to be created
2383  *
2384  * This function must be called before anything when using
2385  * the zsmalloc allocator.
2386  *
2387  * On success, a pointer to the newly created pool is returned,
2388  * otherwise NULL.
2389  */
2390 struct zs_pool *zs_create_pool(const char *name)
2391 {
2392 	int i;
2393 	struct zs_pool *pool;
2394 	struct size_class *prev_class = NULL;
2395 
2396 	pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2397 	if (!pool)
2398 		return NULL;
2399 
2400 	init_deferred_free(pool);
2401 	spin_lock_init(&pool->lock);
2402 	atomic_set(&pool->compaction_in_progress, 0);
2403 
2404 	pool->name = kstrdup(name, GFP_KERNEL);
2405 	if (!pool->name)
2406 		goto err;
2407 
2408 	if (create_cache(pool))
2409 		goto err;
2410 
2411 	/*
2412 	 * Iterate reversely, because, size of size_class that we want to use
2413 	 * for merging should be larger or equal to current size.
2414 	 */
2415 	for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2416 		int size;
2417 		int pages_per_zspage;
2418 		int objs_per_zspage;
2419 		struct size_class *class;
2420 		int fullness;
2421 
2422 		size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2423 		if (size > ZS_MAX_ALLOC_SIZE)
2424 			size = ZS_MAX_ALLOC_SIZE;
2425 		pages_per_zspage = calculate_zspage_chain_size(size);
2426 		objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2427 
2428 		/*
2429 		 * We iterate from biggest down to smallest classes,
2430 		 * so huge_class_size holds the size of the first huge
2431 		 * class. Any object bigger than or equal to that will
2432 		 * endup in the huge class.
2433 		 */
2434 		if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
2435 				!huge_class_size) {
2436 			huge_class_size = size;
2437 			/*
2438 			 * The object uses ZS_HANDLE_SIZE bytes to store the
2439 			 * handle. We need to subtract it, because zs_malloc()
2440 			 * unconditionally adds handle size before it performs
2441 			 * size class search - so object may be smaller than
2442 			 * huge class size, yet it still can end up in the huge
2443 			 * class because it grows by ZS_HANDLE_SIZE extra bytes
2444 			 * right before class lookup.
2445 			 */
2446 			huge_class_size -= (ZS_HANDLE_SIZE - 1);
2447 		}
2448 
2449 		/*
2450 		 * size_class is used for normal zsmalloc operation such
2451 		 * as alloc/free for that size. Although it is natural that we
2452 		 * have one size_class for each size, there is a chance that we
2453 		 * can get more memory utilization if we use one size_class for
2454 		 * many different sizes whose size_class have same
2455 		 * characteristics. So, we makes size_class point to
2456 		 * previous size_class if possible.
2457 		 */
2458 		if (prev_class) {
2459 			if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2460 				pool->size_class[i] = prev_class;
2461 				continue;
2462 			}
2463 		}
2464 
2465 		class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2466 		if (!class)
2467 			goto err;
2468 
2469 		class->size = size;
2470 		class->index = i;
2471 		class->pages_per_zspage = pages_per_zspage;
2472 		class->objs_per_zspage = objs_per_zspage;
2473 		pool->size_class[i] = class;
2474 
2475 		fullness = ZS_INUSE_RATIO_0;
2476 		while (fullness < NR_FULLNESS_GROUPS) {
2477 			INIT_LIST_HEAD(&class->fullness_list[fullness]);
2478 			fullness++;
2479 		}
2480 
2481 		prev_class = class;
2482 	}
2483 
2484 	/* debug only, don't abort if it fails */
2485 	zs_pool_stat_create(pool, name);
2486 
2487 	/*
2488 	 * Not critical since shrinker is only used to trigger internal
2489 	 * defragmentation of the pool which is pretty optional thing.  If
2490 	 * registration fails we still can use the pool normally and user can
2491 	 * trigger compaction manually. Thus, ignore return code.
2492 	 */
2493 	zs_register_shrinker(pool);
2494 
2495 #ifdef CONFIG_ZPOOL
2496 	INIT_LIST_HEAD(&pool->lru);
2497 #endif
2498 
2499 	return pool;
2500 
2501 err:
2502 	zs_destroy_pool(pool);
2503 	return NULL;
2504 }
2505 EXPORT_SYMBOL_GPL(zs_create_pool);
2506 
2507 void zs_destroy_pool(struct zs_pool *pool)
2508 {
2509 	int i;
2510 
2511 	zs_unregister_shrinker(pool);
2512 	zs_flush_migration(pool);
2513 	zs_pool_stat_destroy(pool);
2514 
2515 	for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2516 		int fg;
2517 		struct size_class *class = pool->size_class[i];
2518 
2519 		if (!class)
2520 			continue;
2521 
2522 		if (class->index != i)
2523 			continue;
2524 
2525 		for (fg = ZS_INUSE_RATIO_0; fg < NR_FULLNESS_GROUPS; fg++) {
2526 			if (list_empty(&class->fullness_list[fg]))
2527 				continue;
2528 
2529 			pr_err("Class-%d fullness group %d is not empty\n",
2530 			       class->size, fg);
2531 		}
2532 		kfree(class);
2533 	}
2534 
2535 	destroy_cache(pool);
2536 	kfree(pool->name);
2537 	kfree(pool);
2538 }
2539 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2540 
2541 #ifdef CONFIG_ZPOOL
2542 static void restore_freelist(struct zs_pool *pool, struct size_class *class,
2543 		struct zspage *zspage)
2544 {
2545 	unsigned int obj_idx = 0;
2546 	unsigned long handle, off = 0; /* off is within-page offset */
2547 	struct page *page = get_first_page(zspage);
2548 	struct link_free *prev_free = NULL;
2549 	void *prev_page_vaddr = NULL;
2550 
2551 	/* in case no free object found */
2552 	set_freeobj(zspage, (unsigned int)(-1UL));
2553 
2554 	while (page) {
2555 		void *vaddr = kmap_atomic(page);
2556 		struct page *next_page;
2557 
2558 		while (off < PAGE_SIZE) {
2559 			void *obj_addr = vaddr + off;
2560 
2561 			/* skip allocated object */
2562 			if (obj_allocated(page, obj_addr, &handle)) {
2563 				obj_idx++;
2564 				off += class->size;
2565 				continue;
2566 			}
2567 
2568 			/* free deferred handle from reclaim attempt */
2569 			if (obj_stores_deferred_handle(page, obj_addr, &handle))
2570 				cache_free_handle(pool, handle);
2571 
2572 			if (prev_free)
2573 				prev_free->next = obj_idx << OBJ_TAG_BITS;
2574 			else /* first free object found */
2575 				set_freeobj(zspage, obj_idx);
2576 
2577 			prev_free = (struct link_free *)vaddr + off / sizeof(*prev_free);
2578 			/* if last free object in a previous page, need to unmap */
2579 			if (prev_page_vaddr) {
2580 				kunmap_atomic(prev_page_vaddr);
2581 				prev_page_vaddr = NULL;
2582 			}
2583 
2584 			obj_idx++;
2585 			off += class->size;
2586 		}
2587 
2588 		/*
2589 		 * Handle the last (full or partial) object on this page.
2590 		 */
2591 		next_page = get_next_page(page);
2592 		if (next_page) {
2593 			if (!prev_free || prev_page_vaddr) {
2594 				/*
2595 				 * There is no free object in this page, so we can safely
2596 				 * unmap it.
2597 				 */
2598 				kunmap_atomic(vaddr);
2599 			} else {
2600 				/* update prev_page_vaddr since prev_free is on this page */
2601 				prev_page_vaddr = vaddr;
2602 			}
2603 		} else { /* this is the last page */
2604 			if (prev_free) {
2605 				/*
2606 				 * Reset OBJ_TAG_BITS bit to last link to tell
2607 				 * whether it's allocated object or not.
2608 				 */
2609 				prev_free->next = -1UL << OBJ_TAG_BITS;
2610 			}
2611 
2612 			/* unmap previous page (if not done yet) */
2613 			if (prev_page_vaddr) {
2614 				kunmap_atomic(prev_page_vaddr);
2615 				prev_page_vaddr = NULL;
2616 			}
2617 
2618 			kunmap_atomic(vaddr);
2619 		}
2620 
2621 		page = next_page;
2622 		off %= PAGE_SIZE;
2623 	}
2624 }
2625 
2626 static int zs_reclaim_page(struct zs_pool *pool, unsigned int retries)
2627 {
2628 	int i, obj_idx, ret = 0;
2629 	unsigned long handle;
2630 	struct zspage *zspage;
2631 	struct page *page;
2632 	int fullness;
2633 
2634 	/* Lock LRU and fullness list */
2635 	spin_lock(&pool->lock);
2636 	if (list_empty(&pool->lru)) {
2637 		spin_unlock(&pool->lock);
2638 		return -EINVAL;
2639 	}
2640 
2641 	for (i = 0; i < retries; i++) {
2642 		struct size_class *class;
2643 
2644 		zspage = list_last_entry(&pool->lru, struct zspage, lru);
2645 		list_del(&zspage->lru);
2646 
2647 		/* zs_free may free objects, but not the zspage and handles */
2648 		zspage->under_reclaim = true;
2649 
2650 		class = zspage_class(pool, zspage);
2651 		fullness = get_fullness_group(class, zspage);
2652 
2653 		/* Lock out object allocations and object compaction */
2654 		remove_zspage(class, zspage, fullness);
2655 
2656 		spin_unlock(&pool->lock);
2657 		cond_resched();
2658 
2659 		/* Lock backing pages into place */
2660 		lock_zspage(zspage);
2661 
2662 		obj_idx = 0;
2663 		page = get_first_page(zspage);
2664 		while (1) {
2665 			handle = find_alloced_obj(class, page, &obj_idx);
2666 			if (!handle) {
2667 				page = get_next_page(page);
2668 				if (!page)
2669 					break;
2670 				obj_idx = 0;
2671 				continue;
2672 			}
2673 
2674 			/*
2675 			 * This will write the object and call zs_free.
2676 			 *
2677 			 * zs_free will free the object, but the
2678 			 * under_reclaim flag prevents it from freeing
2679 			 * the zspage altogether. This is necessary so
2680 			 * that we can continue working with the
2681 			 * zspage potentially after the last object
2682 			 * has been freed.
2683 			 */
2684 			ret = pool->zpool_ops->evict(pool->zpool, handle);
2685 			if (ret)
2686 				goto next;
2687 
2688 			obj_idx++;
2689 		}
2690 
2691 next:
2692 		/* For freeing the zspage, or putting it back in the pool and LRU list. */
2693 		spin_lock(&pool->lock);
2694 		zspage->under_reclaim = false;
2695 
2696 		if (!get_zspage_inuse(zspage)) {
2697 			/*
2698 			 * Fullness went stale as zs_free() won't touch it
2699 			 * while the page is removed from the pool. Fix it
2700 			 * up for the check in __free_zspage().
2701 			 */
2702 			zspage->fullness = ZS_INUSE_RATIO_0;
2703 
2704 			__free_zspage(pool, class, zspage);
2705 			spin_unlock(&pool->lock);
2706 			return 0;
2707 		}
2708 
2709 		/*
2710 		 * Eviction fails on one of the handles, so we need to restore zspage.
2711 		 * We need to rebuild its freelist (and free stored deferred handles),
2712 		 * put it back to the correct size class, and add it to the LRU list.
2713 		 */
2714 		restore_freelist(pool, class, zspage);
2715 		putback_zspage(class, zspage);
2716 		list_add(&zspage->lru, &pool->lru);
2717 		unlock_zspage(zspage);
2718 	}
2719 
2720 	spin_unlock(&pool->lock);
2721 	return -EAGAIN;
2722 }
2723 #endif /* CONFIG_ZPOOL */
2724 
2725 static int __init zs_init(void)
2726 {
2727 	int ret;
2728 
2729 	ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2730 				zs_cpu_prepare, zs_cpu_dead);
2731 	if (ret)
2732 		goto out;
2733 
2734 #ifdef CONFIG_ZPOOL
2735 	zpool_register_driver(&zs_zpool_driver);
2736 #endif
2737 
2738 	zs_stat_init();
2739 
2740 	return 0;
2741 
2742 out:
2743 	return ret;
2744 }
2745 
2746 static void __exit zs_exit(void)
2747 {
2748 #ifdef CONFIG_ZPOOL
2749 	zpool_unregister_driver(&zs_zpool_driver);
2750 #endif
2751 	cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2752 
2753 	zs_stat_exit();
2754 }
2755 
2756 module_init(zs_init);
2757 module_exit(zs_exit);
2758 
2759 MODULE_LICENSE("Dual BSD/GPL");
2760 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2761