xref: /linux/mm/zsmalloc.c (revision c315da11e3272d5026b613b933a48016f3af3a18)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 /*
4  * zsmalloc memory allocator
5  *
6  * Copyright (C) 2011  Nitin Gupta
7  * Copyright (C) 2012, 2013 Minchan Kim
8  *
9  * This code is released using a dual license strategy: BSD/GPL
10  * You can choose the license that better fits your requirements.
11  *
12  * Released under the terms of 3-clause BSD License
13  * Released under the terms of GNU General Public License Version 2.0
14  */
15 
16 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 
18 /*
19  * lock ordering:
20  *	page_lock
21  *	pool->lock
22  *	class->lock
23  *	zspage->lock
24  *
25  * When ZS_OBJ_CLASS_BITS > 0, zs_free() skips pool->lock; it picks
26  * the size_class from obj's encoded class_idx and serializes against
27  * page migration via class->lock.
28  */
29 
30 #include <linux/module.h>
31 #include <linux/kernel.h>
32 #include <linux/sched.h>
33 #include <linux/errno.h>
34 #include <linux/highmem.h>
35 #include <linux/string.h>
36 #include <linux/slab.h>
37 #include <linux/scatterlist.h>
38 #include <linux/spinlock.h>
39 #include <linux/sprintf.h>
40 #include <linux/shrinker.h>
41 #include <linux/types.h>
42 #include <linux/debugfs.h>
43 #include <linux/zsmalloc.h>
44 #include <linux/fs.h>
45 #include <linux/workqueue.h>
46 #include "zpdesc.h"
47 
48 #define ZSPAGE_MAGIC	0x58
49 
50 /*
51  * This must be power of 2 and greater than or equal to sizeof(link_free).
52  * These two conditions ensure that any 'struct link_free' itself doesn't
53  * span more than 1 page which avoids complex case of mapping 2 pages simply
54  * to restore link_free pointer values.
55  */
56 #define ZS_ALIGN		8
57 
58 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
59 
60 /*
61  * Object location (<PFN>, <obj_idx>) is encoded as
62  * a single (unsigned long) handle value.
63  *
64  * Note that object index <obj_idx> starts from 0.
65  *
66  * This is made more complicated by various memory models and PAE.
67  */
68 
69 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
70 #ifdef MAX_PHYSMEM_BITS
71 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
72 #else
73 /*
74  * If this definition of MAX_PHYSMEM_BITS is used, ZS_OBJ_PFN_SHIFT will
75  * just be PAGE_SHIFT
76  */
77 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
78 #endif
79 #endif
80 
81 #define _PFN_BITS		(MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
82 
83 /*
84  * Head in allocated object should have OBJ_ALLOCATED_TAG
85  * to identify the object was allocated or not.
86  * It's okay to add the status bit in the least bit because
87  * header keeps handle which is 4byte-aligned address so we
88  * have room for two bit at least.
89  */
90 #define OBJ_ALLOCATED_TAG 1
91 
92 #define OBJ_TAG_BITS	1
93 #define OBJ_TAG_MASK	OBJ_ALLOCATED_TAG
94 
95 /*
96  * obj is encoded as [PFN | class_idx | obj_idx] within an unsigned long:
97  *
98  *   |<-- _PFN_BITS -->|<-- ZS_OBJ_CLASS_BITS -->|<-- ZS_OBJ_IDX_BITS -->|
99  *   +-----------------+-------------------------+-----------------------+
100  *   |       PFN       |        class_idx        |        obj_idx        |
101  *   +-----------------+-------------------------+-----------------------+
102  *  MSB                ^                                                LSB
103  *                     |
104  *                     +-- ZS_OBJ_PFN_SHIFT
105  *
106  * Encoding class_idx into obj lets zs_free() locate the size_class
107  * without holding pool->lock; class_idx is invariant across page
108  * migration (only PFN changes), so a lockless read of the obj value
109  * always yields a valid class_idx.
110  */
111 #define ZS_OBJ_PFN_SHIFT	(BITS_PER_LONG - _PFN_BITS)
112 
113 #define HUGE_BITS	1
114 #define FULLNESS_BITS	4
115 #define CLASS_BITS	8
116 #define MAGIC_VAL_BITS	8
117 
118 #define ZS_MAX_PAGES_PER_ZSPAGE	(_AC(CONFIG_ZSMALLOC_CHAIN_SIZE, UL))
119 
120 /*
121  * Bits to index a page within a zspage = ceil(log2(ZS_MAX_PAGES_PER_ZSPAGE)).
122  * Computed at preprocessor time, for use in #if below.  Kconfig
123  * restricts ZSMALLOC_CHAIN_SIZE to [4, 16].
124  */
125 #if ZS_MAX_PAGES_PER_ZSPAGE <= 4
126 #define ZS_PAGES_PER_ZSPAGE_BITS	2
127 #elif ZS_MAX_PAGES_PER_ZSPAGE <= 8
128 #define ZS_PAGES_PER_ZSPAGE_BITS	3
129 #elif ZS_MAX_PAGES_PER_ZSPAGE <= 16
130 #define ZS_PAGES_PER_ZSPAGE_BITS	4
131 #else
132 #error "ZSMALLOC_CHAIN_SIZE out of expected range [4,16]"
133 #endif
134 
135 /*
136  * Bits to index an object within a single PAGE_SIZE at the smallest
137  * possible object size: log2(PAGE_SIZE / 32) = PAGE_SHIFT - 5.
138  * 32 is the hard floor of ZS_MIN_ALLOC_SIZE.
139  */
140 #define ZS_OBJS_PER_PAGE_BITS	(PAGE_SHIFT - 5)
141 
142 /*
143  * Bits to index any object in the densest possible zspage.  Below this,
144  * ZS_MIN_ALLOC_SIZE is auto-raised by the MAX(32, ...) formula -- still
145  * correct, but objects are coarser.
146  */
147 #define ZS_OBJS_PER_ZSPAGE_BITS \
148 	(ZS_PAGES_PER_ZSPAGE_BITS + ZS_OBJS_PER_PAGE_BITS)
149 
150 /*
151  * Encode class_idx only when obj has spare bits; otherwise
152  * ZS_OBJ_CLASS_BITS folds to 0 (32-bit, or 64-bit UML/fallback).
153  */
154 #if BITS_PER_LONG >= 64 && \
155 	ZS_OBJ_PFN_SHIFT >= (CLASS_BITS + 1) + ZS_OBJS_PER_ZSPAGE_BITS
156 #define ZS_OBJ_CLASS_BITS	(CLASS_BITS + 1)
157 #else
158 #define ZS_OBJ_CLASS_BITS	0
159 #endif
160 #define ZS_OBJ_CLASS_MASK	((_AC(1, UL) << ZS_OBJ_CLASS_BITS) - 1)
161 
162 #define ZS_OBJ_IDX_BITS		(ZS_OBJ_PFN_SHIFT - ZS_OBJ_CLASS_BITS)
163 #define ZS_OBJ_IDX_MASK		((_AC(1, UL) << ZS_OBJ_IDX_BITS) - 1)
164 
165 /*
166  * Belt-and-suspenders: the #if above already guarantees this when
167  * class_idx is enabled.  Catches future tweaks that bypass it.
168  */
169 static_assert(ZS_OBJ_IDX_BITS >= ZS_PAGES_PER_ZSPAGE_BITS,
170 	      "zsmalloc: ZS_MIN_ALLOC_SIZE would exceed ZS_MAX_ALLOC_SIZE");
171 
172 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
173 #define ZS_MIN_ALLOC_SIZE \
174 	MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> ZS_OBJ_IDX_BITS))
175 /* each chunk includes extra space to keep handle */
176 #define ZS_MAX_ALLOC_SIZE	PAGE_SIZE
177 
178 /*
179  * On systems with 4K page size, this gives 255 size classes! There is a
180  * trade-off here:
181  *  - Large number of size classes is potentially wasteful as free page are
182  *    spread across these classes
183  *  - Small number of size classes causes large internal fragmentation
184  *  - Probably its better to use specific size classes (empirically
185  *    determined). NOTE: all those class sizes must be set as multiple of
186  *    ZS_ALIGN to make sure link_free itself never has to span 2 pages.
187  *
188  *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
189  *  (reason above)
190  */
191 #define ZS_SIZE_CLASS_DELTA	(PAGE_SIZE >> CLASS_BITS)
192 #define ZS_SIZE_CLASSES	(DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
193 				      ZS_SIZE_CLASS_DELTA) + 1)
194 
195 /*
196  * Pages are distinguished by the ratio of used memory (that is the ratio
197  * of ->inuse objects to all objects that page can store). For example,
198  * INUSE_RATIO_10 means that the ratio of used objects is > 0% and <= 10%.
199  *
200  * The number of fullness groups is not random. It allows us to keep
201  * difference between the least busy page in the group (minimum permitted
202  * number of ->inuse objects) and the most busy page (maximum permitted
203  * number of ->inuse objects) at a reasonable value.
204  */
205 enum fullness_group {
206 	ZS_INUSE_RATIO_0,
207 	ZS_INUSE_RATIO_10,
208 	/* NOTE: 8 more fullness groups here */
209 	ZS_INUSE_RATIO_99       = 10,
210 	ZS_INUSE_RATIO_100,
211 	NR_FULLNESS_GROUPS,
212 };
213 
214 enum class_stat_type {
215 	/* NOTE: stats for 12 fullness groups here: from inuse 0 to 100 */
216 	ZS_OBJS_ALLOCATED       = NR_FULLNESS_GROUPS,
217 	ZS_OBJS_INUSE,
218 	NR_CLASS_STAT_TYPES,
219 };
220 
221 struct zs_size_stat {
222 	unsigned long objs[NR_CLASS_STAT_TYPES];
223 };
224 
225 #ifdef CONFIG_ZSMALLOC_STAT
226 static struct dentry *zs_stat_root;
227 #endif
228 
229 static size_t huge_class_size;
230 
231 struct size_class {
232 	spinlock_t lock;
233 	struct list_head fullness_list[NR_FULLNESS_GROUPS];
234 	/*
235 	 * Size of objects stored in this class. Must be multiple
236 	 * of ZS_ALIGN.
237 	 */
238 	int size;
239 	int objs_per_zspage;
240 	/* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
241 	int pages_per_zspage;
242 
243 	unsigned int index;
244 	struct zs_size_stat stats;
245 };
246 
247 /*
248  * Placed within free objects to form a singly linked list.
249  * For every zspage, zspage->freeobj gives head of this list.
250  *
251  * This must be power of 2 and less than or equal to ZS_ALIGN
252  */
253 struct link_free {
254 	union {
255 		/*
256 		 * Free object index;
257 		 * It's valid for non-allocated object
258 		 */
259 		unsigned long next;
260 		/*
261 		 * Handle of allocated object.
262 		 */
263 		unsigned long handle;
264 	};
265 };
266 
267 static struct kmem_cache *handle_cachep;
268 static struct kmem_cache *zspage_cachep;
269 
270 struct zs_pool {
271 	const char *name;
272 
273 	struct size_class *size_class[ZS_SIZE_CLASSES];
274 
275 	atomic_long_t pages_allocated;
276 
277 	struct zs_pool_stats stats;
278 
279 	/* Compact classes */
280 	struct shrinker *shrinker;
281 
282 #ifdef CONFIG_ZSMALLOC_STAT
283 	struct dentry *stat_dentry;
284 #endif
285 #ifdef CONFIG_COMPACTION
286 	struct work_struct free_work;
287 #endif
288 	/* protect zspage migration/compaction */
289 	rwlock_t lock;
290 	atomic_t compaction_in_progress;
291 };
292 
293 static inline void zpdesc_inc_zone_page_state(struct zpdesc *zpdesc)
294 {
295 	inc_zone_page_state(zpdesc_page(zpdesc), NR_ZSPAGES);
296 }
297 
298 static inline void zpdesc_dec_zone_page_state(struct zpdesc *zpdesc)
299 {
300 	dec_zone_page_state(zpdesc_page(zpdesc), NR_ZSPAGES);
301 }
302 
303 static inline struct zpdesc *alloc_zpdesc(gfp_t gfp, const int nid)
304 {
305 	struct page *page = alloc_pages_node(nid, gfp, 0);
306 
307 	return page_zpdesc(page);
308 }
309 
310 static inline void free_zpdesc(struct zpdesc *zpdesc)
311 {
312 	struct page *page = zpdesc_page(zpdesc);
313 
314 	/* PageZsmalloc is sticky until the page is freed to the buddy. */
315 	__free_page(page);
316 }
317 
318 #define ZS_PAGE_UNLOCKED	0
319 #define ZS_PAGE_WRLOCKED	-1
320 
321 struct zspage_lock {
322 	spinlock_t lock;
323 	int cnt;
324 	struct lockdep_map dep_map;
325 };
326 
327 struct zspage {
328 	struct {
329 		unsigned int huge:HUGE_BITS;
330 		unsigned int fullness:FULLNESS_BITS;
331 		unsigned int class:CLASS_BITS + 1;
332 		unsigned int magic:MAGIC_VAL_BITS;
333 	};
334 	unsigned int inuse;
335 	unsigned int freeobj;
336 	struct zpdesc *first_zpdesc;
337 	struct list_head list; /* fullness list */
338 	struct zs_pool *pool;
339 	struct zspage_lock zsl;
340 };
341 
342 static void zspage_lock_init(struct zspage *zspage)
343 {
344 	static struct lock_class_key __key;
345 	struct zspage_lock *zsl = &zspage->zsl;
346 
347 	lockdep_init_map(&zsl->dep_map, "zspage->lock", &__key, 0);
348 	spin_lock_init(&zsl->lock);
349 	zsl->cnt = ZS_PAGE_UNLOCKED;
350 }
351 
352 /*
353  * The zspage lock can be held from atomic contexts, but it needs to remain
354  * preemptible when held for reading because it remains held outside of those
355  * atomic contexts, otherwise we unnecessarily lose preemptibility.
356  *
357  * To achieve this, the following rules are enforced on readers and writers:
358  *
359  * - Writers are blocked by both writers and readers, while readers are only
360  *   blocked by writers (i.e. normal rwlock semantics).
361  *
362  * - Writers are always atomic (to allow readers to spin waiting for them).
363  *
364  * - Writers always use trylock (as the lock may be held be sleeping readers).
365  *
366  * - Readers may spin on the lock (as they can only wait for atomic writers).
367  *
368  * - Readers may sleep while holding the lock (as writes only use trylock).
369  */
370 static void zspage_read_lock(struct zspage *zspage)
371 {
372 	struct zspage_lock *zsl = &zspage->zsl;
373 
374 	rwsem_acquire_read(&zsl->dep_map, 0, 0, _RET_IP_);
375 
376 	spin_lock(&zsl->lock);
377 	zsl->cnt++;
378 	spin_unlock(&zsl->lock);
379 
380 	lock_acquired(&zsl->dep_map, _RET_IP_);
381 }
382 
383 static void zspage_read_unlock(struct zspage *zspage)
384 {
385 	struct zspage_lock *zsl = &zspage->zsl;
386 
387 	rwsem_release(&zsl->dep_map, _RET_IP_);
388 
389 	spin_lock(&zsl->lock);
390 	zsl->cnt--;
391 	spin_unlock(&zsl->lock);
392 }
393 
394 static __must_check bool zspage_write_trylock(struct zspage *zspage)
395 {
396 	struct zspage_lock *zsl = &zspage->zsl;
397 
398 	spin_lock(&zsl->lock);
399 	if (zsl->cnt == ZS_PAGE_UNLOCKED) {
400 		zsl->cnt = ZS_PAGE_WRLOCKED;
401 		rwsem_acquire(&zsl->dep_map, 0, 1, _RET_IP_);
402 		lock_acquired(&zsl->dep_map, _RET_IP_);
403 		return true;
404 	}
405 
406 	spin_unlock(&zsl->lock);
407 	return false;
408 }
409 
410 static void zspage_write_unlock(struct zspage *zspage)
411 {
412 	struct zspage_lock *zsl = &zspage->zsl;
413 
414 	rwsem_release(&zsl->dep_map, _RET_IP_);
415 
416 	zsl->cnt = ZS_PAGE_UNLOCKED;
417 	spin_unlock(&zsl->lock);
418 }
419 
420 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
421 static void SetZsHugePage(struct zspage *zspage)
422 {
423 	zspage->huge = 1;
424 }
425 
426 static bool ZsHugePage(struct zspage *zspage)
427 {
428 	return zspage->huge;
429 }
430 
431 #ifdef CONFIG_COMPACTION
432 static void kick_deferred_free(struct zs_pool *pool);
433 static void init_deferred_free(struct zs_pool *pool);
434 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
435 #else
436 static void kick_deferred_free(struct zs_pool *pool) {}
437 static void init_deferred_free(struct zs_pool *pool) {}
438 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
439 #endif
440 
441 static unsigned long cache_alloc_handle(gfp_t gfp)
442 {
443 	gfp = gfp & ~(__GFP_HIGHMEM | __GFP_MOVABLE);
444 
445 	return (unsigned long)kmem_cache_alloc(handle_cachep, gfp);
446 }
447 
448 static void cache_free_handle(unsigned long handle)
449 {
450 	kmem_cache_free(handle_cachep, (void *)handle);
451 }
452 
453 static struct zspage *cache_alloc_zspage(gfp_t gfp)
454 {
455 	gfp = gfp & ~(__GFP_HIGHMEM | __GFP_MOVABLE);
456 
457 	return kmem_cache_zalloc(zspage_cachep, gfp);
458 }
459 
460 static void cache_free_zspage(struct zspage *zspage)
461 {
462 	kmem_cache_free(zspage_cachep, zspage);
463 }
464 
465 /*
466  * Pairs with READ_ONCE() in handle_to_obj(): zs_free() may read the
467  * handle locklessly, so prevent store tearing here.
468  */
469 static void record_obj(unsigned long handle, unsigned long obj)
470 {
471 	WRITE_ONCE(*(unsigned long *)handle, obj);
472 }
473 
474 /* Protected by class->lock */
475 static inline int get_zspage_inuse(struct zspage *zspage)
476 {
477 	return zspage->inuse;
478 }
479 
480 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
481 {
482 	zspage->inuse += val;
483 }
484 
485 static struct zpdesc *get_first_zpdesc(struct zspage *zspage)
486 {
487 	struct zpdesc *first_zpdesc = zspage->first_zpdesc;
488 
489 	/* the first zpdesc must point back to this zspage */
490 	VM_WARN_ON_ONCE_PAGE(first_zpdesc->zspage != zspage, zpdesc_page(first_zpdesc));
491 	return first_zpdesc;
492 }
493 
494 #define FIRST_OBJ_PAGE_TYPE_MASK	0xffffff
495 
496 static inline unsigned int get_first_obj_offset(struct zpdesc *zpdesc)
497 {
498 	VM_WARN_ON_ONCE(!PageZsmalloc(zpdesc_page(zpdesc)));
499 	return zpdesc->first_obj_offset & FIRST_OBJ_PAGE_TYPE_MASK;
500 }
501 
502 static inline void set_first_obj_offset(struct zpdesc *zpdesc, unsigned int offset)
503 {
504 	/* With 24 bits available, we can support offsets into 16 MiB pages. */
505 	BUILD_BUG_ON(PAGE_SIZE > SZ_16M);
506 	VM_WARN_ON_ONCE(!PageZsmalloc(zpdesc_page(zpdesc)));
507 	VM_WARN_ON_ONCE(offset & ~FIRST_OBJ_PAGE_TYPE_MASK);
508 	zpdesc->first_obj_offset &= ~FIRST_OBJ_PAGE_TYPE_MASK;
509 	zpdesc->first_obj_offset |= offset & FIRST_OBJ_PAGE_TYPE_MASK;
510 }
511 
512 static inline unsigned int get_freeobj(struct zspage *zspage)
513 {
514 	return zspage->freeobj;
515 }
516 
517 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
518 {
519 	zspage->freeobj = obj;
520 }
521 
522 static struct size_class *zspage_class(struct zs_pool *pool,
523 				       struct zspage *zspage)
524 {
525 	return pool->size_class[zspage->class];
526 }
527 
528 /*
529  * zsmalloc divides the pool into various size classes where each
530  * class maintains a list of zspages where each zspage is divided
531  * into equal sized chunks. Each allocation falls into one of these
532  * classes depending on its size. This function returns index of the
533  * size class which has chunk size big enough to hold the given size.
534  */
535 static int get_size_class_index(int size)
536 {
537 	int idx = 0;
538 
539 	if (likely(size > ZS_MIN_ALLOC_SIZE))
540 		idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
541 				ZS_SIZE_CLASS_DELTA);
542 
543 	return min_t(int, ZS_SIZE_CLASSES - 1, idx);
544 }
545 
546 static struct size_class *lookup_size_class(struct zs_pool *pool, size_t size)
547 {
548 	return pool->size_class[get_size_class_index(size + ZS_HANDLE_SIZE)];
549 }
550 
551 static inline void class_stat_add(struct size_class *class, int type,
552 				  unsigned long cnt)
553 {
554 	class->stats.objs[type] += cnt;
555 }
556 
557 static inline void class_stat_sub(struct size_class *class, int type,
558 				  unsigned long cnt)
559 {
560 	class->stats.objs[type] -= cnt;
561 }
562 
563 static inline unsigned long class_stat_read(struct size_class *class, int type)
564 {
565 	return class->stats.objs[type];
566 }
567 
568 #ifdef CONFIG_ZSMALLOC_STAT
569 
570 static void __init zs_stat_init(void)
571 {
572 	if (!debugfs_initialized()) {
573 		pr_warn("debugfs not available, stat dir not created\n");
574 		return;
575 	}
576 
577 	zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
578 }
579 
580 static void __exit zs_stat_exit(void)
581 {
582 	debugfs_remove_recursive(zs_stat_root);
583 }
584 
585 static unsigned long zs_can_compact(struct size_class *class);
586 
587 static int zs_stats_size_show(struct seq_file *s, void *v)
588 {
589 	int i, fg;
590 	struct zs_pool *pool = s->private;
591 	struct size_class *class;
592 	int objs_per_zspage;
593 	unsigned long obj_allocated, obj_used, pages_used, freeable;
594 	unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
595 	unsigned long total_freeable = 0;
596 	unsigned long inuse_totals[NR_FULLNESS_GROUPS] = {0, };
597 
598 	seq_printf(s, " %5s %5s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %13s %10s %10s %16s %8s\n",
599 			"class", "size", "10%", "20%", "30%", "40%",
600 			"50%", "60%", "70%", "80%", "90%", "99%", "100%",
601 			"obj_allocated", "obj_used", "pages_used",
602 			"pages_per_zspage", "freeable");
603 
604 	for (i = 0; i < ZS_SIZE_CLASSES; i++) {
605 
606 		class = pool->size_class[i];
607 
608 		if (class->index != i)
609 			continue;
610 
611 		spin_lock(&class->lock);
612 
613 		seq_printf(s, " %5u %5u ", i, class->size);
614 		for (fg = ZS_INUSE_RATIO_10; fg < NR_FULLNESS_GROUPS; fg++) {
615 			inuse_totals[fg] += class_stat_read(class, fg);
616 			seq_printf(s, "%9lu ", class_stat_read(class, fg));
617 		}
618 
619 		obj_allocated = class_stat_read(class, ZS_OBJS_ALLOCATED);
620 		obj_used = class_stat_read(class, ZS_OBJS_INUSE);
621 		freeable = zs_can_compact(class);
622 		spin_unlock(&class->lock);
623 
624 		objs_per_zspage = class->objs_per_zspage;
625 		pages_used = obj_allocated / objs_per_zspage *
626 				class->pages_per_zspage;
627 
628 		seq_printf(s, "%13lu %10lu %10lu %16d %8lu\n",
629 			   obj_allocated, obj_used, pages_used,
630 			   class->pages_per_zspage, freeable);
631 
632 		total_objs += obj_allocated;
633 		total_used_objs += obj_used;
634 		total_pages += pages_used;
635 		total_freeable += freeable;
636 	}
637 
638 	seq_printf(s, "\n %5s %5s ", "Total", "");
639 
640 	for (fg = ZS_INUSE_RATIO_10; fg < NR_FULLNESS_GROUPS; fg++)
641 		seq_printf(s, "%9lu ", inuse_totals[fg]);
642 
643 	seq_printf(s, "%13lu %10lu %10lu %16s %8lu\n",
644 		   total_objs, total_used_objs, total_pages, "",
645 		   total_freeable);
646 
647 	return 0;
648 }
649 DEFINE_SHOW_ATTRIBUTE(zs_stats_size);
650 
651 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
652 {
653 	if (!zs_stat_root) {
654 		pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
655 		return;
656 	}
657 
658 	pool->stat_dentry = debugfs_create_dir(name, zs_stat_root);
659 
660 	debugfs_create_file("classes", S_IFREG | 0444, pool->stat_dentry, pool,
661 			    &zs_stats_size_fops);
662 }
663 
664 static void zs_pool_stat_destroy(struct zs_pool *pool)
665 {
666 	debugfs_remove_recursive(pool->stat_dentry);
667 }
668 
669 #else /* CONFIG_ZSMALLOC_STAT */
670 static void __init zs_stat_init(void)
671 {
672 }
673 
674 static void __exit zs_stat_exit(void)
675 {
676 }
677 
678 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
679 {
680 }
681 
682 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
683 {
684 }
685 #endif
686 
687 
688 /*
689  * For each size class, zspages are divided into different groups
690  * depending on their usage ratio. This function returns fullness
691  * status of the given page.
692  */
693 static int get_fullness_group(struct size_class *class, struct zspage *zspage)
694 {
695 	int inuse, objs_per_zspage, ratio;
696 
697 	inuse = get_zspage_inuse(zspage);
698 	objs_per_zspage = class->objs_per_zspage;
699 
700 	if (inuse == 0)
701 		return ZS_INUSE_RATIO_0;
702 	if (inuse == objs_per_zspage)
703 		return ZS_INUSE_RATIO_100;
704 
705 	ratio = 100 * inuse / objs_per_zspage;
706 	/*
707 	 * Take integer division into consideration: a page with one inuse
708 	 * object out of 127 possible, will end up having 0 usage ratio,
709 	 * which is wrong as it belongs in ZS_INUSE_RATIO_10 fullness group.
710 	 */
711 	return ratio / 10 + 1;
712 }
713 
714 /*
715  * Each size class maintains various freelists and zspages are assigned
716  * to one of these freelists based on the number of live objects they
717  * have. This functions inserts the given zspage into the freelist
718  * identified by <class, fullness_group>.
719  */
720 static void insert_zspage(struct size_class *class,
721 				struct zspage *zspage,
722 				int fullness)
723 {
724 	class_stat_add(class, fullness, 1);
725 	list_add(&zspage->list, &class->fullness_list[fullness]);
726 	zspage->fullness = fullness;
727 }
728 
729 /*
730  * This function removes the given zspage from the freelist identified
731  * by <class, fullness_group>.
732  */
733 static void remove_zspage(struct size_class *class, struct zspage *zspage)
734 {
735 	int fullness = zspage->fullness;
736 
737 	VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
738 
739 	list_del_init(&zspage->list);
740 	class_stat_sub(class, fullness, 1);
741 }
742 
743 /*
744  * Each size class maintains zspages in different fullness groups depending
745  * on the number of live objects they contain. When allocating or freeing
746  * objects, the fullness status of the page can change, for instance, from
747  * INUSE_RATIO_80 to INUSE_RATIO_70 when freeing an object. This function
748  * checks if such a status change has occurred for the given page and
749  * accordingly moves the page from the list of the old fullness group to that
750  * of the new fullness group.
751  */
752 static int fix_fullness_group(struct size_class *class, struct zspage *zspage)
753 {
754 	int newfg;
755 
756 	newfg = get_fullness_group(class, zspage);
757 	if (newfg == zspage->fullness)
758 		goto out;
759 
760 	remove_zspage(class, zspage);
761 	insert_zspage(class, zspage, newfg);
762 out:
763 	return newfg;
764 }
765 
766 static struct zspage *get_zspage(struct zpdesc *zpdesc)
767 {
768 	struct zspage *zspage = zpdesc->zspage;
769 
770 	BUG_ON(zspage->magic != ZSPAGE_MAGIC);
771 	return zspage;
772 }
773 
774 static struct zpdesc *get_next_zpdesc(struct zpdesc *zpdesc)
775 {
776 	struct zspage *zspage = get_zspage(zpdesc);
777 
778 	if (unlikely(ZsHugePage(zspage)))
779 		return NULL;
780 
781 	return zpdesc->next;
782 }
783 
784 /**
785  * obj_to_location - get (<zpdesc>, <obj_idx>) from encoded object value
786  * @obj: the encoded object value
787  * @zpdesc: zpdesc object resides in zspage
788  * @obj_idx: object index
789  */
790 static void obj_to_location(unsigned long obj, struct zpdesc **zpdesc,
791 				unsigned int *obj_idx)
792 {
793 	*zpdesc = pfn_zpdesc(obj >> ZS_OBJ_PFN_SHIFT);
794 	*obj_idx = (obj & ZS_OBJ_IDX_MASK);
795 }
796 
797 static void obj_to_zpdesc(unsigned long obj, struct zpdesc **zpdesc)
798 {
799 	*zpdesc = pfn_zpdesc(obj >> ZS_OBJ_PFN_SHIFT);
800 }
801 
802 /**
803  * location_to_obj - encode (<zpdesc>, <obj_idx>, <class_idx>) into obj value
804  * @zpdesc: zpdesc object resides in zspage
805  * @obj_idx: object index
806  * @class_idx: size class index; ignored when ZS_OBJ_CLASS_BITS == 0
807  */
808 static unsigned long location_to_obj(struct zpdesc *zpdesc, unsigned int obj_idx,
809 				     unsigned int class_idx)
810 {
811 	unsigned long obj;
812 
813 	obj  = zpdesc_pfn(zpdesc) << ZS_OBJ_PFN_SHIFT;
814 	obj |= (unsigned long)(class_idx & ZS_OBJ_CLASS_MASK) << ZS_OBJ_IDX_BITS;
815 	obj |= obj_idx & ZS_OBJ_IDX_MASK;
816 
817 	return obj;
818 }
819 
820 static unsigned long handle_to_obj(unsigned long handle)
821 {
822 	return READ_ONCE(*(unsigned long *)handle);
823 }
824 
825 static inline bool obj_allocated(struct zpdesc *zpdesc, void *obj,
826 				 unsigned long *phandle)
827 {
828 	unsigned long handle;
829 	struct zspage *zspage = get_zspage(zpdesc);
830 
831 	if (unlikely(ZsHugePage(zspage))) {
832 		/* only first zpdesc holds the handle */
833 		VM_WARN_ON_ONCE_PAGE(zspage->first_zpdesc != zpdesc, zpdesc_page(zpdesc));
834 		handle = zpdesc->handle;
835 	} else
836 		handle = *(unsigned long *)obj;
837 
838 	if (!(handle & OBJ_ALLOCATED_TAG))
839 		return false;
840 
841 	/* Clear all tags before returning the handle */
842 	*phandle = handle & ~OBJ_TAG_MASK;
843 	return true;
844 }
845 
846 static void reset_zpdesc(struct zpdesc *zpdesc)
847 {
848 	zpdesc->zspage = NULL;
849 	zpdesc->next = NULL;
850 	/* PageZsmalloc is sticky until the page is freed to the buddy. */
851 }
852 
853 static int trylock_zspage(struct zspage *zspage)
854 {
855 	struct zpdesc *cursor, *fail;
856 
857 	for (cursor = get_first_zpdesc(zspage); cursor != NULL; cursor =
858 					get_next_zpdesc(cursor)) {
859 		if (!zpdesc_trylock(cursor)) {
860 			fail = cursor;
861 			goto unlock;
862 		}
863 	}
864 
865 	return 1;
866 unlock:
867 	for (cursor = get_first_zpdesc(zspage); cursor != fail; cursor =
868 					get_next_zpdesc(cursor))
869 		zpdesc_unlock(cursor);
870 
871 	return 0;
872 }
873 
874 /*
875  * Three free helpers, kept apart here:
876  *
877  * __free_zspage_lockless(): bare core; walks zpdescs and returns pages
878  *   to the buddy allocator.  Caller owns all zpdesc locks and has
879  *   removed the zspage from its class list.  Used by zs_free() outside
880  *   class->lock so the buddy-side work does not stall the class.
881  *
882  * __free_zspage(): __free_zspage_lockless() + per-class accounting,
883  *   under class->lock.  Used by async_free_zspage(), the worker for
884  *   zspages whose trylock_zspage() failed.
885  *
886  * free_zspage(): full wrapper - trylock zpdescs, remove from class
887  *   list, call __free_zspage(); kicks deferred free on contention.
888  *   Used by compaction.
889  */
890 static inline void __free_zspage_lockless(struct zspage *zspage)
891 {
892 	struct zpdesc *zpdesc, *next;
893 
894 	VM_BUG_ON(get_zspage_inuse(zspage));
895 	VM_BUG_ON(zspage->fullness != ZS_INUSE_RATIO_0);
896 
897 	next = zpdesc = get_first_zpdesc(zspage);
898 	do {
899 		VM_BUG_ON_PAGE(!zpdesc_is_locked(zpdesc), zpdesc_page(zpdesc));
900 		next = get_next_zpdesc(zpdesc);
901 		reset_zpdesc(zpdesc);
902 		zpdesc_unlock(zpdesc);
903 		zpdesc_dec_zone_page_state(zpdesc);
904 		zpdesc_put(zpdesc);
905 		zpdesc = next;
906 	} while (zpdesc != NULL);
907 
908 	cache_free_zspage(zspage);
909 }
910 
911 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
912 			  struct zspage *zspage)
913 {
914 	assert_spin_locked(&class->lock);
915 	__free_zspage_lockless(zspage);
916 	class_stat_sub(class, ZS_OBJS_ALLOCATED, class->objs_per_zspage);
917 	atomic_long_sub(class->pages_per_zspage, &pool->pages_allocated);
918 }
919 
920 static void free_zspage(struct zs_pool *pool, struct size_class *class,
921 				struct zspage *zspage)
922 {
923 	VM_BUG_ON(get_zspage_inuse(zspage));
924 	VM_BUG_ON(list_empty(&zspage->list));
925 
926 	/*
927 	 * Since zs_free couldn't be sleepable, this function cannot call
928 	 * lock_page. The page locks trylock_zspage got will be released
929 	 * by __free_zspage.
930 	 */
931 	if (!trylock_zspage(zspage)) {
932 		kick_deferred_free(pool);
933 		return;
934 	}
935 
936 	remove_zspage(class, zspage);
937 	__free_zspage(pool, class, zspage);
938 }
939 
940 /* Initialize a newly allocated zspage */
941 static void init_zspage(struct size_class *class, struct zspage *zspage)
942 {
943 	unsigned int freeobj = 1;
944 	unsigned long off = 0;
945 	struct zpdesc *zpdesc = get_first_zpdesc(zspage);
946 
947 	while (zpdesc) {
948 		struct zpdesc *next_zpdesc;
949 		struct link_free *link;
950 		void *vaddr;
951 
952 		set_first_obj_offset(zpdesc, off);
953 
954 		vaddr = kmap_local_zpdesc(zpdesc);
955 		link = (struct link_free *)vaddr + off / sizeof(*link);
956 
957 		while ((off += class->size) < PAGE_SIZE) {
958 			link->next = freeobj++ << OBJ_TAG_BITS;
959 			link += class->size / sizeof(*link);
960 		}
961 
962 		/*
963 		 * We now come to the last (full or partial) object on this
964 		 * page, which must point to the first object on the next
965 		 * page (if present)
966 		 */
967 		next_zpdesc = get_next_zpdesc(zpdesc);
968 		if (next_zpdesc) {
969 			link->next = freeobj++ << OBJ_TAG_BITS;
970 		} else {
971 			/*
972 			 * Reset OBJ_TAG_BITS bit to last link to tell
973 			 * whether it's allocated object or not.
974 			 */
975 			link->next = -1UL << OBJ_TAG_BITS;
976 		}
977 		kunmap_local(vaddr);
978 		zpdesc = next_zpdesc;
979 		off %= PAGE_SIZE;
980 	}
981 
982 	set_freeobj(zspage, 0);
983 }
984 
985 static void create_page_chain(struct size_class *class, struct zspage *zspage,
986 				struct zpdesc *zpdescs[])
987 {
988 	int i;
989 	struct zpdesc *zpdesc;
990 	struct zpdesc *prev_zpdesc = NULL;
991 	int nr_zpdescs = class->pages_per_zspage;
992 
993 	/*
994 	 * Allocate individual pages and link them together as:
995 	 * 1. all pages are linked together using zpdesc->next
996 	 * 2. each sub-page point to zspage using zpdesc->zspage
997 	 *
998 	 * The first zpdesc has its zspage->first_zpdesc set to itself, no
999 	 * other zpdesc has this set.
1000 	 */
1001 	for (i = 0; i < nr_zpdescs; i++) {
1002 		zpdesc = zpdescs[i];
1003 		zpdesc->zspage = zspage;
1004 		zpdesc->next = NULL;
1005 		if (i == 0) {
1006 			zspage->first_zpdesc = zpdesc;
1007 			if (unlikely(class->objs_per_zspage == 1 &&
1008 					class->pages_per_zspage == 1))
1009 				SetZsHugePage(zspage);
1010 		} else {
1011 			prev_zpdesc->next = zpdesc;
1012 		}
1013 		prev_zpdesc = zpdesc;
1014 	}
1015 }
1016 
1017 /*
1018  * Allocate a zspage for the given size class
1019  */
1020 static struct zspage *alloc_zspage(struct zs_pool *pool,
1021 				   struct size_class *class,
1022 				   gfp_t gfp, const int nid)
1023 {
1024 	int i;
1025 	struct zpdesc *zpdescs[ZS_MAX_PAGES_PER_ZSPAGE];
1026 	struct zspage *zspage = cache_alloc_zspage(gfp);
1027 
1028 	if (!zspage)
1029 		return NULL;
1030 
1031 	if (!IS_ENABLED(CONFIG_COMPACTION))
1032 		gfp &= ~__GFP_MOVABLE;
1033 
1034 	zspage->magic = ZSPAGE_MAGIC;
1035 	zspage->pool = pool;
1036 	zspage->class = class->index;
1037 	zspage_lock_init(zspage);
1038 
1039 	for (i = 0; i < class->pages_per_zspage; i++) {
1040 		struct zpdesc *zpdesc;
1041 
1042 		zpdesc = alloc_zpdesc(gfp, nid);
1043 		if (!zpdesc) {
1044 			while (--i >= 0) {
1045 				zpdesc_dec_zone_page_state(zpdescs[i]);
1046 				free_zpdesc(zpdescs[i]);
1047 			}
1048 			cache_free_zspage(zspage);
1049 			return NULL;
1050 		}
1051 		__zpdesc_set_zsmalloc(zpdesc);
1052 
1053 		zpdesc_inc_zone_page_state(zpdesc);
1054 		zpdescs[i] = zpdesc;
1055 	}
1056 
1057 	create_page_chain(class, zspage, zpdescs);
1058 	init_zspage(class, zspage);
1059 
1060 	return zspage;
1061 }
1062 
1063 static struct zspage *find_get_zspage(struct size_class *class)
1064 {
1065 	int i;
1066 	struct zspage *zspage;
1067 
1068 	for (i = ZS_INUSE_RATIO_99; i >= ZS_INUSE_RATIO_0; i--) {
1069 		zspage = list_first_entry_or_null(&class->fullness_list[i],
1070 						  struct zspage, list);
1071 		if (zspage)
1072 			break;
1073 	}
1074 
1075 	return zspage;
1076 }
1077 
1078 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1079 					int objs_per_zspage)
1080 {
1081 	if (prev->pages_per_zspage == pages_per_zspage &&
1082 		prev->objs_per_zspage == objs_per_zspage)
1083 		return true;
1084 
1085 	return false;
1086 }
1087 
1088 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1089 {
1090 	return get_zspage_inuse(zspage) == class->objs_per_zspage;
1091 }
1092 
1093 static bool zspage_empty(struct zspage *zspage)
1094 {
1095 	return get_zspage_inuse(zspage) == 0;
1096 }
1097 
1098 /**
1099  * zs_lookup_class_index() - Returns index of the zsmalloc &size_class
1100  * that hold objects of the provided size.
1101  * @pool: zsmalloc pool to use
1102  * @size: object size
1103  *
1104  * Context: Any context.
1105  *
1106  * Return: the index of the zsmalloc &size_class that hold objects of the
1107  * provided size.
1108  */
1109 unsigned int zs_lookup_class_index(struct zs_pool *pool, unsigned int size)
1110 {
1111 	struct size_class *class;
1112 
1113 	class = lookup_size_class(pool, size);
1114 
1115 	return class->index;
1116 }
1117 EXPORT_SYMBOL_GPL(zs_lookup_class_index);
1118 
1119 unsigned long zs_get_total_pages(struct zs_pool *pool)
1120 {
1121 	return atomic_long_read(&pool->pages_allocated);
1122 }
1123 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1124 
1125 void zs_obj_read_sg_begin(struct zs_pool *pool, unsigned long handle,
1126 			  struct scatterlist *sg, size_t mem_len)
1127 {
1128 	struct zspage *zspage;
1129 	struct zpdesc *zpdesc;
1130 	unsigned long obj, off;
1131 	unsigned int obj_idx;
1132 	struct size_class *class;
1133 
1134 	/* Guarantee we can get zspage from handle safely */
1135 	read_lock(&pool->lock);
1136 	obj = handle_to_obj(handle);
1137 	obj_to_location(obj, &zpdesc, &obj_idx);
1138 	zspage = get_zspage(zpdesc);
1139 
1140 	/* Make sure migration doesn't move any pages in this zspage */
1141 	zspage_read_lock(zspage);
1142 	read_unlock(&pool->lock);
1143 
1144 	class = zspage_class(pool, zspage);
1145 	off = offset_in_page(class->size * obj_idx);
1146 
1147 	if (!ZsHugePage(zspage))
1148 		off += ZS_HANDLE_SIZE;
1149 
1150 	if (off + mem_len <= PAGE_SIZE) {
1151 		/* this object is contained entirely within a page */
1152 		sg_init_table(sg, 1);
1153 		sg_set_page(sg, zpdesc_page(zpdesc), mem_len, off);
1154 	} else {
1155 		size_t sizes[2];
1156 
1157 		/* this object spans two pages */
1158 		sizes[0] = PAGE_SIZE - off;
1159 		sizes[1] = mem_len - sizes[0];
1160 
1161 		sg_init_table(sg, 2);
1162 		sg_set_page(sg, zpdesc_page(zpdesc), sizes[0], off);
1163 
1164 		zpdesc = get_next_zpdesc(zpdesc);
1165 		sg = sg_next(sg);
1166 
1167 		sg_set_page(sg, zpdesc_page(zpdesc), sizes[1], 0);
1168 	}
1169 }
1170 EXPORT_SYMBOL_GPL(zs_obj_read_sg_begin);
1171 
1172 void zs_obj_read_sg_end(struct zs_pool *pool, unsigned long handle)
1173 {
1174 	struct zspage *zspage;
1175 	struct zpdesc *zpdesc;
1176 	unsigned long obj;
1177 	unsigned int obj_idx;
1178 
1179 	obj = handle_to_obj(handle);
1180 	obj_to_location(obj, &zpdesc, &obj_idx);
1181 	zspage = get_zspage(zpdesc);
1182 
1183 	zspage_read_unlock(zspage);
1184 }
1185 EXPORT_SYMBOL_GPL(zs_obj_read_sg_end);
1186 
1187 void zs_obj_write(struct zs_pool *pool, unsigned long handle,
1188 		  void *handle_mem, size_t mem_len)
1189 {
1190 	struct zspage *zspage;
1191 	struct zpdesc *zpdesc;
1192 	unsigned long obj, off;
1193 	unsigned int obj_idx;
1194 	struct size_class *class;
1195 
1196 	/* Guarantee we can get zspage from handle safely */
1197 	read_lock(&pool->lock);
1198 	obj = handle_to_obj(handle);
1199 	obj_to_location(obj, &zpdesc, &obj_idx);
1200 	zspage = get_zspage(zpdesc);
1201 
1202 	/* Make sure migration doesn't move any pages in this zspage */
1203 	zspage_read_lock(zspage);
1204 	read_unlock(&pool->lock);
1205 
1206 	class = zspage_class(pool, zspage);
1207 	off = offset_in_page(class->size * obj_idx);
1208 
1209 	if (!ZsHugePage(zspage))
1210 		off += ZS_HANDLE_SIZE;
1211 
1212 	if (off + mem_len <= PAGE_SIZE) {
1213 		/* this object is contained entirely within a page */
1214 		void *dst = kmap_local_zpdesc(zpdesc);
1215 
1216 		memcpy(dst + off, handle_mem, mem_len);
1217 		kunmap_local(dst);
1218 	} else {
1219 		/* this object spans two pages */
1220 		size_t sizes[2];
1221 
1222 		sizes[0] = PAGE_SIZE - off;
1223 		sizes[1] = mem_len - sizes[0];
1224 
1225 		memcpy_to_page(zpdesc_page(zpdesc), off,
1226 			       handle_mem, sizes[0]);
1227 		zpdesc = get_next_zpdesc(zpdesc);
1228 		memcpy_to_page(zpdesc_page(zpdesc), 0,
1229 			       handle_mem + sizes[0], sizes[1]);
1230 	}
1231 
1232 	zspage_read_unlock(zspage);
1233 }
1234 EXPORT_SYMBOL_GPL(zs_obj_write);
1235 
1236 /**
1237  * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1238  *                        zsmalloc &size_class.
1239  * @pool: zsmalloc pool to use
1240  *
1241  * The function returns the size of the first huge class - any object of equal
1242  * or bigger size will be stored in zspage consisting of a single physical
1243  * page.
1244  *
1245  * Context: Any context.
1246  *
1247  * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1248  */
1249 size_t zs_huge_class_size(struct zs_pool *pool)
1250 {
1251 	return huge_class_size;
1252 }
1253 EXPORT_SYMBOL_GPL(zs_huge_class_size);
1254 
1255 static unsigned long obj_malloc(struct zs_pool *pool,
1256 				struct zspage *zspage, unsigned long handle)
1257 {
1258 	int i, nr_zpdesc, offset;
1259 	unsigned long obj;
1260 	struct link_free *link;
1261 	struct size_class *class;
1262 
1263 	struct zpdesc *m_zpdesc;
1264 	unsigned long m_offset;
1265 	void *vaddr;
1266 
1267 	class = pool->size_class[zspage->class];
1268 	obj = get_freeobj(zspage);
1269 
1270 	offset = obj * class->size;
1271 	nr_zpdesc = offset >> PAGE_SHIFT;
1272 	m_offset = offset_in_page(offset);
1273 	m_zpdesc = get_first_zpdesc(zspage);
1274 
1275 	for (i = 0; i < nr_zpdesc; i++)
1276 		m_zpdesc = get_next_zpdesc(m_zpdesc);
1277 
1278 	vaddr = kmap_local_zpdesc(m_zpdesc);
1279 	link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1280 	set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1281 	if (likely(!ZsHugePage(zspage)))
1282 		/* record handle in the header of allocated chunk */
1283 		link->handle = handle | OBJ_ALLOCATED_TAG;
1284 	else
1285 		zspage->first_zpdesc->handle = handle | OBJ_ALLOCATED_TAG;
1286 
1287 	kunmap_local(vaddr);
1288 	mod_zspage_inuse(zspage, 1);
1289 
1290 	obj = location_to_obj(m_zpdesc, obj, zspage->class);
1291 	record_obj(handle, obj);
1292 
1293 	return obj;
1294 }
1295 
1296 
1297 /**
1298  * zs_malloc - Allocate block of given size from pool.
1299  * @pool: pool to allocate from
1300  * @size: size of block to allocate
1301  * @gfp: gfp flags when allocating object
1302  * @nid: The preferred node id to allocate new zspage (if needed)
1303  *
1304  * On success, handle to the allocated object is returned,
1305  * otherwise an ERR_PTR().
1306  * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1307  */
1308 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp,
1309 			const int nid)
1310 {
1311 	unsigned long handle;
1312 	struct size_class *class;
1313 	int newfg;
1314 	struct zspage *zspage;
1315 
1316 	if (unlikely(!size))
1317 		return (unsigned long)ERR_PTR(-EINVAL);
1318 
1319 	if (unlikely(size > ZS_MAX_ALLOC_SIZE))
1320 		return (unsigned long)ERR_PTR(-ENOSPC);
1321 
1322 	handle = cache_alloc_handle(gfp);
1323 	if (!handle)
1324 		return (unsigned long)ERR_PTR(-ENOMEM);
1325 
1326 	class = lookup_size_class(pool, size);
1327 
1328 	/* class->lock effectively protects the zpage migration */
1329 	spin_lock(&class->lock);
1330 	zspage = find_get_zspage(class);
1331 	if (likely(zspage)) {
1332 		obj_malloc(pool, zspage, handle);
1333 		/* Now move the zspage to another fullness group, if required */
1334 		fix_fullness_group(class, zspage);
1335 		class_stat_add(class, ZS_OBJS_INUSE, 1);
1336 
1337 		goto out;
1338 	}
1339 
1340 	spin_unlock(&class->lock);
1341 
1342 	zspage = alloc_zspage(pool, class, gfp, nid);
1343 	if (!zspage) {
1344 		cache_free_handle(handle);
1345 		return (unsigned long)ERR_PTR(-ENOMEM);
1346 	}
1347 
1348 	spin_lock(&class->lock);
1349 	obj_malloc(pool, zspage, handle);
1350 	newfg = get_fullness_group(class, zspage);
1351 	insert_zspage(class, zspage, newfg);
1352 	atomic_long_add(class->pages_per_zspage, &pool->pages_allocated);
1353 	class_stat_add(class, ZS_OBJS_ALLOCATED, class->objs_per_zspage);
1354 	class_stat_add(class, ZS_OBJS_INUSE, 1);
1355 
1356 	/* We completely set up zspage so mark them as movable */
1357 	SetZsPageMovable(pool, zspage);
1358 out:
1359 	spin_unlock(&class->lock);
1360 
1361 	return handle;
1362 }
1363 EXPORT_SYMBOL_GPL(zs_malloc);
1364 
1365 static void obj_free(int class_size, unsigned long obj)
1366 {
1367 	struct link_free *link;
1368 	struct zspage *zspage;
1369 	struct zpdesc *f_zpdesc;
1370 	unsigned long f_offset;
1371 	unsigned int f_objidx;
1372 	void *vaddr;
1373 
1374 
1375 	obj_to_location(obj, &f_zpdesc, &f_objidx);
1376 	f_offset = offset_in_page(class_size * f_objidx);
1377 	zspage = get_zspage(f_zpdesc);
1378 
1379 	vaddr = kmap_local_zpdesc(f_zpdesc);
1380 	link = (struct link_free *)(vaddr + f_offset);
1381 
1382 	/* Insert this object in containing zspage's freelist */
1383 	if (likely(!ZsHugePage(zspage)))
1384 		link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1385 	else
1386 		f_zpdesc->handle = 0;
1387 	set_freeobj(zspage, f_objidx);
1388 
1389 	kunmap_local(vaddr);
1390 	mod_zspage_inuse(zspage, -1);
1391 }
1392 
1393 #if (ZS_OBJ_CLASS_BITS > 0) || defined(CONFIG_COMPACTION)
1394 /* Folds to 0 when ZS_OBJ_CLASS_BITS == 0; no ifdef needed at callers. */
1395 static unsigned int obj_to_class_idx(unsigned long obj)
1396 {
1397 	return (obj >> ZS_OBJ_IDX_BITS) & ZS_OBJ_CLASS_MASK;
1398 }
1399 #endif
1400 
1401 /*
1402  * Resolve @handle to its zspage / size_class and acquire class->lock.
1403  *
1404  * When class_idx is encoded in obj (ZS_OBJ_CLASS_BITS > 0), it is
1405  * invariant under page migration, so the handle can be read locklessly
1406  * to pick the size_class.  Once class->lock is held migration is
1407  * blocked and the handle is re-read to obtain a stable PFN.
1408  *
1409  * Otherwise (32-bit, or 64-bit fallback paths like UML where the
1410  * encoding is disabled), fall back to pool->lock for the lookup.
1411  */
1412 #if ZS_OBJ_CLASS_BITS > 0
1413 static inline void obj_class_get_and_lock(struct zs_pool *pool, unsigned long handle,
1414 					 unsigned long *objp, struct zspage **zspagep,
1415 					 struct size_class **classp)
1416 	__acquires(&(*classp)->lock)
1417 {
1418 	struct zpdesc *f_zpdesc;
1419 	unsigned long obj;
1420 
1421 	obj = handle_to_obj(handle);
1422 	*classp = pool->size_class[obj_to_class_idx(obj)];
1423 	spin_lock(&(*classp)->lock);
1424 	/* Re-read under class->lock: PFN is now stable vs migration. */
1425 	obj = handle_to_obj(handle);
1426 	obj_to_zpdesc(obj, &f_zpdesc);
1427 	*zspagep = get_zspage(f_zpdesc);
1428 	*objp = obj;
1429 }
1430 #else
1431 static inline void obj_class_get_and_lock(struct zs_pool *pool, unsigned long handle,
1432 					 unsigned long *objp, struct zspage **zspagep,
1433 					 struct size_class **classp)
1434 	__acquires(&(*classp)->lock)
1435 {
1436 	struct zpdesc *f_zpdesc;
1437 	unsigned long obj;
1438 
1439 	read_lock(&pool->lock);
1440 	obj = handle_to_obj(handle);
1441 	obj_to_zpdesc(obj, &f_zpdesc);
1442 	*zspagep = get_zspage(f_zpdesc);
1443 	*classp = zspage_class(pool, *zspagep);
1444 	spin_lock(&(*classp)->lock);
1445 	read_unlock(&pool->lock);
1446 	*objp = obj;
1447 }
1448 #endif
1449 
1450 void zs_free(struct zs_pool *pool, unsigned long handle)
1451 {
1452 	struct zspage *zspage;
1453 	unsigned long obj;
1454 	struct size_class *class;
1455 	int fullness;
1456 	struct zspage *zspage_to_free = NULL;
1457 
1458 	if (IS_ERR_OR_NULL((void *)handle))
1459 		return;
1460 
1461 	obj_class_get_and_lock(pool, handle, &obj, &zspage, &class);
1462 
1463 	class_stat_sub(class, ZS_OBJS_INUSE, 1);
1464 	obj_free(class->size, obj);
1465 
1466 	fullness = fix_fullness_group(class, zspage);
1467 	if (fullness == ZS_INUSE_RATIO_0) {
1468 		if (trylock_zspage(zspage)) {
1469 			remove_zspage(class, zspage);
1470 			class_stat_sub(class, ZS_OBJS_ALLOCATED,
1471 				       class->objs_per_zspage);
1472 			zspage_to_free = zspage;
1473 		} else {
1474 			kick_deferred_free(pool);
1475 		}
1476 	}
1477 
1478 	spin_unlock(&class->lock);
1479 
1480 	if (zspage_to_free) {
1481 		__free_zspage_lockless(zspage_to_free);
1482 		atomic_long_sub(class->pages_per_zspage, &pool->pages_allocated);
1483 	}
1484 	cache_free_handle(handle);
1485 }
1486 EXPORT_SYMBOL_GPL(zs_free);
1487 
1488 static void zs_object_copy(struct size_class *class, unsigned long dst,
1489 				unsigned long src)
1490 {
1491 	struct zpdesc *s_zpdesc, *d_zpdesc;
1492 	unsigned int s_objidx, d_objidx;
1493 	unsigned long s_off, d_off;
1494 	void *s_addr, *d_addr;
1495 	int s_size, d_size, size;
1496 	int written = 0;
1497 
1498 	s_size = d_size = class->size;
1499 
1500 	obj_to_location(src, &s_zpdesc, &s_objidx);
1501 	obj_to_location(dst, &d_zpdesc, &d_objidx);
1502 
1503 	s_off = offset_in_page(class->size * s_objidx);
1504 	d_off = offset_in_page(class->size * d_objidx);
1505 
1506 	if (s_off + class->size > PAGE_SIZE)
1507 		s_size = PAGE_SIZE - s_off;
1508 
1509 	if (d_off + class->size > PAGE_SIZE)
1510 		d_size = PAGE_SIZE - d_off;
1511 
1512 	s_addr = kmap_local_zpdesc(s_zpdesc);
1513 	d_addr = kmap_local_zpdesc(d_zpdesc);
1514 
1515 	while (1) {
1516 		size = min(s_size, d_size);
1517 		memcpy(d_addr + d_off, s_addr + s_off, size);
1518 		written += size;
1519 
1520 		if (written == class->size)
1521 			break;
1522 
1523 		s_off += size;
1524 		s_size -= size;
1525 		d_off += size;
1526 		d_size -= size;
1527 
1528 		/*
1529 		 * Calling kunmap_local(d_addr) is necessary. kunmap_local()
1530 		 * calls must occurs in reverse order of calls to kmap_local_page().
1531 		 * So, to call kunmap_local(s_addr) we should first call
1532 		 * kunmap_local(d_addr). For more details see
1533 		 * Documentation/mm/highmem.rst.
1534 		 */
1535 		if (s_off >= PAGE_SIZE) {
1536 			kunmap_local(d_addr);
1537 			kunmap_local(s_addr);
1538 			s_zpdesc = get_next_zpdesc(s_zpdesc);
1539 			s_addr = kmap_local_zpdesc(s_zpdesc);
1540 			d_addr = kmap_local_zpdesc(d_zpdesc);
1541 			s_size = class->size - written;
1542 			s_off = 0;
1543 		}
1544 
1545 		if (d_off >= PAGE_SIZE) {
1546 			kunmap_local(d_addr);
1547 			d_zpdesc = get_next_zpdesc(d_zpdesc);
1548 			d_addr = kmap_local_zpdesc(d_zpdesc);
1549 			d_size = class->size - written;
1550 			d_off = 0;
1551 		}
1552 	}
1553 
1554 	kunmap_local(d_addr);
1555 	kunmap_local(s_addr);
1556 }
1557 
1558 /*
1559  * Find alloced object in zspage from index object and
1560  * return handle.
1561  */
1562 static unsigned long find_alloced_obj(struct size_class *class,
1563 				      struct zpdesc *zpdesc, int *obj_idx)
1564 {
1565 	unsigned int offset;
1566 	int index = *obj_idx;
1567 	unsigned long handle = 0;
1568 	void *addr = kmap_local_zpdesc(zpdesc);
1569 
1570 	offset = get_first_obj_offset(zpdesc);
1571 	offset += class->size * index;
1572 
1573 	while (offset < PAGE_SIZE) {
1574 		if (obj_allocated(zpdesc, addr + offset, &handle))
1575 			break;
1576 
1577 		offset += class->size;
1578 		index++;
1579 	}
1580 
1581 	kunmap_local(addr);
1582 
1583 	*obj_idx = index;
1584 
1585 	return handle;
1586 }
1587 
1588 static void migrate_zspage(struct zs_pool *pool, struct zspage *src_zspage,
1589 			   struct zspage *dst_zspage)
1590 {
1591 	unsigned long used_obj, free_obj;
1592 	unsigned long handle;
1593 	int obj_idx = 0;
1594 	struct zpdesc *s_zpdesc = get_first_zpdesc(src_zspage);
1595 	struct size_class *class = pool->size_class[src_zspage->class];
1596 
1597 	while (1) {
1598 		handle = find_alloced_obj(class, s_zpdesc, &obj_idx);
1599 		if (!handle) {
1600 			s_zpdesc = get_next_zpdesc(s_zpdesc);
1601 			if (!s_zpdesc)
1602 				break;
1603 			obj_idx = 0;
1604 			continue;
1605 		}
1606 
1607 		used_obj = handle_to_obj(handle);
1608 		free_obj = obj_malloc(pool, dst_zspage, handle);
1609 		zs_object_copy(class, free_obj, used_obj);
1610 		obj_idx++;
1611 		obj_free(class->size, used_obj);
1612 
1613 		/* Stop if there is no more space */
1614 		if (zspage_full(class, dst_zspage))
1615 			break;
1616 
1617 		/* Stop if there are no more objects to migrate */
1618 		if (zspage_empty(src_zspage))
1619 			break;
1620 	}
1621 }
1622 
1623 static struct zspage *isolate_src_zspage(struct size_class *class)
1624 {
1625 	struct zspage *zspage;
1626 	int fg;
1627 
1628 	for (fg = ZS_INUSE_RATIO_10; fg <= ZS_INUSE_RATIO_99; fg++) {
1629 		zspage = list_first_entry_or_null(&class->fullness_list[fg],
1630 						  struct zspage, list);
1631 		if (zspage) {
1632 			remove_zspage(class, zspage);
1633 			return zspage;
1634 		}
1635 	}
1636 
1637 	return zspage;
1638 }
1639 
1640 static struct zspage *isolate_dst_zspage(struct size_class *class)
1641 {
1642 	struct zspage *zspage;
1643 	int fg;
1644 
1645 	for (fg = ZS_INUSE_RATIO_99; fg >= ZS_INUSE_RATIO_10; fg--) {
1646 		zspage = list_first_entry_or_null(&class->fullness_list[fg],
1647 						  struct zspage, list);
1648 		if (zspage) {
1649 			remove_zspage(class, zspage);
1650 			return zspage;
1651 		}
1652 	}
1653 
1654 	return zspage;
1655 }
1656 
1657 /*
1658  * putback_zspage - add @zspage into right class's fullness list
1659  * @class: destination class
1660  * @zspage: target page
1661  *
1662  * Return @zspage's fullness status
1663  */
1664 static int putback_zspage(struct size_class *class, struct zspage *zspage)
1665 {
1666 	int fullness;
1667 
1668 	fullness = get_fullness_group(class, zspage);
1669 	insert_zspage(class, zspage, fullness);
1670 
1671 	return fullness;
1672 }
1673 
1674 #ifdef CONFIG_COMPACTION
1675 /*
1676  * To prevent zspage destroy during migration, zspage freeing should
1677  * hold locks of all pages in the zspage.
1678  */
1679 static void lock_zspage(struct zspage *zspage)
1680 {
1681 	struct zpdesc *curr_zpdesc, *zpdesc;
1682 
1683 	/*
1684 	 * Pages we haven't locked yet can be migrated off the list while we're
1685 	 * trying to lock them, so we need to be careful and only attempt to
1686 	 * lock each page under zspage_read_lock(). Otherwise, the page we lock
1687 	 * may no longer belong to the zspage. This means that we may wait for
1688 	 * the wrong page to unlock, so we must take a reference to the page
1689 	 * prior to waiting for it to unlock outside zspage_read_lock().
1690 	 */
1691 	while (1) {
1692 		zspage_read_lock(zspage);
1693 		zpdesc = get_first_zpdesc(zspage);
1694 		if (zpdesc_trylock(zpdesc))
1695 			break;
1696 		zpdesc_get(zpdesc);
1697 		zspage_read_unlock(zspage);
1698 		zpdesc_wait_locked(zpdesc);
1699 		zpdesc_put(zpdesc);
1700 	}
1701 
1702 	curr_zpdesc = zpdesc;
1703 	while ((zpdesc = get_next_zpdesc(curr_zpdesc))) {
1704 		if (zpdesc_trylock(zpdesc)) {
1705 			curr_zpdesc = zpdesc;
1706 		} else {
1707 			zpdesc_get(zpdesc);
1708 			zspage_read_unlock(zspage);
1709 			zpdesc_wait_locked(zpdesc);
1710 			zpdesc_put(zpdesc);
1711 			zspage_read_lock(zspage);
1712 		}
1713 	}
1714 	zspage_read_unlock(zspage);
1715 }
1716 
1717 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1718 				struct zpdesc *newzpdesc, struct zpdesc *oldzpdesc)
1719 {
1720 	struct zpdesc *zpdesc;
1721 	struct zpdesc *zpdescs[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1722 	unsigned int first_obj_offset;
1723 	int idx = 0;
1724 
1725 	zpdesc = get_first_zpdesc(zspage);
1726 	do {
1727 		if (zpdesc == oldzpdesc)
1728 			zpdescs[idx] = newzpdesc;
1729 		else
1730 			zpdescs[idx] = zpdesc;
1731 		idx++;
1732 	} while ((zpdesc = get_next_zpdesc(zpdesc)) != NULL);
1733 
1734 	create_page_chain(class, zspage, zpdescs);
1735 	first_obj_offset = get_first_obj_offset(oldzpdesc);
1736 	set_first_obj_offset(newzpdesc, first_obj_offset);
1737 	if (unlikely(ZsHugePage(zspage)))
1738 		newzpdesc->handle = oldzpdesc->handle;
1739 	__zpdesc_set_movable(newzpdesc);
1740 }
1741 
1742 static bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1743 {
1744 	/*
1745 	 * Page is locked so zspage can't be destroyed concurrently
1746 	 * (see free_zspage()). But if the page was already destroyed
1747 	 * (see reset_zpdesc()), refuse isolation here.
1748 	 */
1749 	return page_zpdesc(page)->zspage;
1750 }
1751 
1752 static int zs_page_migrate(struct page *newpage, struct page *page,
1753 		enum migrate_mode mode)
1754 {
1755 	struct zs_pool *pool;
1756 	struct size_class *class;
1757 	struct zspage *zspage;
1758 	struct zpdesc *dummy;
1759 	struct zpdesc *newzpdesc = page_zpdesc(newpage);
1760 	struct zpdesc *zpdesc = page_zpdesc(page);
1761 	void *s_addr, *d_addr, *addr;
1762 	unsigned int offset;
1763 	unsigned long handle;
1764 	unsigned long old_obj, new_obj;
1765 	unsigned int obj_idx;
1766 
1767 	/*
1768 	 * TODO: nothing prevents a zspage from getting destroyed while
1769 	 * it is isolated for migration, as the page lock is temporarily
1770 	 * dropped after zs_page_isolate() succeeded: we should rework that
1771 	 * and defer destroying such pages once they are un-isolated (putback)
1772 	 * instead.
1773 	 */
1774 	if (!zpdesc->zspage)
1775 		return 0;
1776 
1777 	/* The page is locked, so this pointer must remain valid */
1778 	zspage = get_zspage(zpdesc);
1779 	pool = zspage->pool;
1780 
1781 	/*
1782 	 * The pool migrate_lock protects against races between zpage migration
1783 	 * and zs_free(), but only when ZS_OBJ_CLASS_BITS does not apply.
1784 	 */
1785 	write_lock(&pool->lock);
1786 	class = zspage_class(pool, zspage);
1787 
1788 	/*
1789 	 * the class lock protects zpage alloc/free in the zspage.
1790 	 */
1791 	spin_lock(&class->lock);
1792 	/* the zspage write_lock protects zpage access via zs_obj_read/write() */
1793 	if (!zspage_write_trylock(zspage)) {
1794 		spin_unlock(&class->lock);
1795 		write_unlock(&pool->lock);
1796 		/*
1797 		 * Return -EBUSY but not -EAGAIN: the zspage's reader-lock
1798 		 * owner may hold the lock for an unbounded duration due to a
1799 		 * slow decompression or reader-lock owner preemption.
1800 		 * Since migration retries are bounded by
1801 		 * NR_MAX_MIGRATE_PAGES_RETRY and performed with virtually no
1802 		 * delay between attempts, there is no guarantee the lock will
1803 		 * be released in time for a retry to succeed.
1804 		 * -EAGAIN implies "try again soon", which does not hold here.
1805 		 * -EBUSY more accurately conveys "resource is occupied,
1806 		 * migration cannot proceed".
1807 		 */
1808 		return -EBUSY;
1809 	}
1810 
1811 	/* We're committed, tell the world that this is a Zsmalloc page. */
1812 	__zpdesc_set_zsmalloc(newzpdesc);
1813 
1814 	offset = get_first_obj_offset(zpdesc);
1815 	s_addr = kmap_local_zpdesc(zpdesc);
1816 
1817 	/*
1818 	 * Here, any user cannot access all objects in the zspage so let's move.
1819 	 */
1820 	d_addr = kmap_local_zpdesc(newzpdesc);
1821 	copy_page(d_addr, s_addr);
1822 	kmsan_copy_page_meta(zpdesc_page(newzpdesc), zpdesc_page(zpdesc));
1823 	kunmap_local(d_addr);
1824 
1825 	for (addr = s_addr + offset; addr < s_addr + PAGE_SIZE;
1826 					addr += class->size) {
1827 		if (obj_allocated(zpdesc, addr, &handle)) {
1828 
1829 			old_obj = handle_to_obj(handle);
1830 			obj_to_location(old_obj, &dummy, &obj_idx);
1831 			new_obj = location_to_obj(newzpdesc, obj_idx,
1832 						  obj_to_class_idx(old_obj));
1833 			record_obj(handle, new_obj);
1834 		}
1835 	}
1836 	kunmap_local(s_addr);
1837 
1838 	replace_sub_page(class, zspage, newzpdesc, zpdesc);
1839 	/*
1840 	 * Since we complete the data copy and set up new zspage structure,
1841 	 * it's okay to release migration_lock.
1842 	 */
1843 	zspage_write_unlock(zspage);
1844 	spin_unlock(&class->lock);
1845 	write_unlock(&pool->lock);
1846 
1847 	zpdesc_get(newzpdesc);
1848 	if (zpdesc_zone(newzpdesc) != zpdesc_zone(zpdesc)) {
1849 		zpdesc_dec_zone_page_state(zpdesc);
1850 		zpdesc_inc_zone_page_state(newzpdesc);
1851 	}
1852 
1853 	reset_zpdesc(zpdesc);
1854 	zpdesc_put(zpdesc);
1855 
1856 	return 0;
1857 }
1858 
1859 static void zs_page_putback(struct page *page)
1860 {
1861 }
1862 
1863 const struct movable_operations zsmalloc_mops = {
1864 	.isolate_page = zs_page_isolate,
1865 	.migrate_page = zs_page_migrate,
1866 	.putback_page = zs_page_putback,
1867 };
1868 
1869 /*
1870  * Caller should hold page_lock of all pages in the zspage
1871  * In here, we cannot use zspage meta data.
1872  */
1873 static void async_free_zspage(struct work_struct *work)
1874 {
1875 	int i;
1876 	struct size_class *class;
1877 	struct zspage *zspage, *tmp;
1878 	LIST_HEAD(free_pages);
1879 	struct zs_pool *pool = container_of(work, struct zs_pool,
1880 					free_work);
1881 
1882 	for (i = 0; i < ZS_SIZE_CLASSES; i++) {
1883 		class = pool->size_class[i];
1884 		if (class->index != i)
1885 			continue;
1886 
1887 		spin_lock(&class->lock);
1888 		list_splice_init(&class->fullness_list[ZS_INUSE_RATIO_0],
1889 				 &free_pages);
1890 		spin_unlock(&class->lock);
1891 	}
1892 
1893 	list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
1894 		list_del(&zspage->list);
1895 		lock_zspage(zspage);
1896 
1897 		class = zspage_class(pool, zspage);
1898 		spin_lock(&class->lock);
1899 		class_stat_sub(class, ZS_INUSE_RATIO_0, 1);
1900 		__free_zspage(pool, class, zspage);
1901 		spin_unlock(&class->lock);
1902 	}
1903 };
1904 
1905 static void kick_deferred_free(struct zs_pool *pool)
1906 {
1907 	schedule_work(&pool->free_work);
1908 }
1909 
1910 static void zs_flush_migration(struct zs_pool *pool)
1911 {
1912 	flush_work(&pool->free_work);
1913 }
1914 
1915 static void init_deferred_free(struct zs_pool *pool)
1916 {
1917 	INIT_WORK(&pool->free_work, async_free_zspage);
1918 }
1919 
1920 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
1921 {
1922 	struct zpdesc *zpdesc = get_first_zpdesc(zspage);
1923 
1924 	do {
1925 		WARN_ON(!zpdesc_trylock(zpdesc));
1926 		__zpdesc_set_movable(zpdesc);
1927 		zpdesc_unlock(zpdesc);
1928 	} while ((zpdesc = get_next_zpdesc(zpdesc)) != NULL);
1929 }
1930 #else
1931 static inline void zs_flush_migration(struct zs_pool *pool) { }
1932 #endif
1933 
1934 /*
1935  *
1936  * Based on the number of unused allocated objects calculate
1937  * and return the number of pages that we can free.
1938  */
1939 static unsigned long zs_can_compact(struct size_class *class)
1940 {
1941 	unsigned long obj_wasted;
1942 	unsigned long obj_allocated = class_stat_read(class, ZS_OBJS_ALLOCATED);
1943 	unsigned long obj_used = class_stat_read(class, ZS_OBJS_INUSE);
1944 
1945 	if (obj_allocated <= obj_used)
1946 		return 0;
1947 
1948 	obj_wasted = obj_allocated - obj_used;
1949 	obj_wasted /= class->objs_per_zspage;
1950 
1951 	return obj_wasted * class->pages_per_zspage;
1952 }
1953 
1954 static unsigned long __zs_compact(struct zs_pool *pool,
1955 				  struct size_class *class)
1956 {
1957 	struct zspage *src_zspage = NULL;
1958 	struct zspage *dst_zspage = NULL;
1959 	unsigned long pages_freed = 0;
1960 
1961 	/*
1962 	 * Protect against races between zpage migration and zs_free()
1963 	 * (only when ZS_OBJ_CLASS_BITS does not apply), as well as
1964 	 * zpage allocation and free.
1965 	 */
1966 	write_lock(&pool->lock);
1967 	spin_lock(&class->lock);
1968 	while (zs_can_compact(class)) {
1969 		int fg;
1970 
1971 		if (!dst_zspage) {
1972 			dst_zspage = isolate_dst_zspage(class);
1973 			if (!dst_zspage)
1974 				break;
1975 		}
1976 
1977 		src_zspage = isolate_src_zspage(class);
1978 		if (!src_zspage)
1979 			break;
1980 
1981 		if (!zspage_write_trylock(src_zspage))
1982 			break;
1983 
1984 		migrate_zspage(pool, src_zspage, dst_zspage);
1985 		zspage_write_unlock(src_zspage);
1986 
1987 		fg = putback_zspage(class, src_zspage);
1988 		if (fg == ZS_INUSE_RATIO_0) {
1989 			free_zspage(pool, class, src_zspage);
1990 			pages_freed += class->pages_per_zspage;
1991 		}
1992 		src_zspage = NULL;
1993 
1994 		if (get_fullness_group(class, dst_zspage) == ZS_INUSE_RATIO_100
1995 		    || rwlock_is_contended(&pool->lock)) {
1996 			putback_zspage(class, dst_zspage);
1997 			dst_zspage = NULL;
1998 
1999 			spin_unlock(&class->lock);
2000 			write_unlock(&pool->lock);
2001 			cond_resched();
2002 			write_lock(&pool->lock);
2003 			spin_lock(&class->lock);
2004 		}
2005 	}
2006 
2007 	if (src_zspage)
2008 		putback_zspage(class, src_zspage);
2009 
2010 	if (dst_zspage)
2011 		putback_zspage(class, dst_zspage);
2012 
2013 	spin_unlock(&class->lock);
2014 	write_unlock(&pool->lock);
2015 
2016 	return pages_freed;
2017 }
2018 
2019 unsigned long zs_compact(struct zs_pool *pool)
2020 {
2021 	int i;
2022 	struct size_class *class;
2023 	unsigned long pages_freed = 0;
2024 
2025 	/*
2026 	 * Pool compaction is performed under pool->lock so it is basically
2027 	 * single-threaded. Having more than one thread in __zs_compact()
2028 	 * will increase pool->lock contention, which will impact other
2029 	 * zsmalloc operations that need pool->lock.
2030 	 */
2031 	if (atomic_xchg(&pool->compaction_in_progress, 1))
2032 		return 0;
2033 
2034 	for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2035 		class = pool->size_class[i];
2036 		if (class->index != i)
2037 			continue;
2038 		pages_freed += __zs_compact(pool, class);
2039 	}
2040 	atomic_long_add(pages_freed, &pool->stats.pages_compacted);
2041 	atomic_set(&pool->compaction_in_progress, 0);
2042 
2043 	return pages_freed;
2044 }
2045 EXPORT_SYMBOL_GPL(zs_compact);
2046 
2047 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2048 {
2049 	memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2050 }
2051 EXPORT_SYMBOL_GPL(zs_pool_stats);
2052 
2053 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2054 		struct shrink_control *sc)
2055 {
2056 	unsigned long pages_freed;
2057 	struct zs_pool *pool = shrinker->private_data;
2058 
2059 	/*
2060 	 * Compact classes and calculate compaction delta.
2061 	 * Can run concurrently with a manually triggered
2062 	 * (by user) compaction.
2063 	 */
2064 	pages_freed = zs_compact(pool);
2065 
2066 	return pages_freed ? pages_freed : SHRINK_STOP;
2067 }
2068 
2069 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2070 		struct shrink_control *sc)
2071 {
2072 	int i;
2073 	struct size_class *class;
2074 	unsigned long pages_to_free = 0;
2075 	struct zs_pool *pool = shrinker->private_data;
2076 
2077 	for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2078 		class = pool->size_class[i];
2079 		if (class->index != i)
2080 			continue;
2081 
2082 		pages_to_free += zs_can_compact(class);
2083 	}
2084 
2085 	return pages_to_free;
2086 }
2087 
2088 static void zs_unregister_shrinker(struct zs_pool *pool)
2089 {
2090 	shrinker_free(pool->shrinker);
2091 }
2092 
2093 static int zs_register_shrinker(struct zs_pool *pool)
2094 {
2095 	pool->shrinker = shrinker_alloc(0, "mm-zspool:%s", pool->name);
2096 	if (!pool->shrinker)
2097 		return -ENOMEM;
2098 
2099 	pool->shrinker->scan_objects = zs_shrinker_scan;
2100 	pool->shrinker->count_objects = zs_shrinker_count;
2101 	pool->shrinker->batch = 0;
2102 	pool->shrinker->private_data = pool;
2103 
2104 	shrinker_register(pool->shrinker);
2105 
2106 	return 0;
2107 }
2108 
2109 static int calculate_zspage_chain_size(int class_size)
2110 {
2111 	int i, min_waste = INT_MAX;
2112 	int chain_size = 1;
2113 
2114 	if (is_power_of_2(class_size))
2115 		return chain_size;
2116 
2117 	for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
2118 		int waste;
2119 
2120 		waste = (i * PAGE_SIZE) % class_size;
2121 		if (waste < min_waste) {
2122 			min_waste = waste;
2123 			chain_size = i;
2124 		}
2125 	}
2126 
2127 	return chain_size;
2128 }
2129 
2130 /**
2131  * zs_create_pool - Creates an allocation pool to work from.
2132  * @name: pool name to be created
2133  *
2134  * This function must be called before anything when using
2135  * the zsmalloc allocator.
2136  *
2137  * On success, a pointer to the newly created pool is returned,
2138  * otherwise NULL.
2139  */
2140 struct zs_pool *zs_create_pool(const char *name)
2141 {
2142 	int i;
2143 	struct zs_pool *pool;
2144 	struct size_class *prev_class = NULL;
2145 
2146 	pool = kzalloc_obj(*pool);
2147 	if (!pool)
2148 		return NULL;
2149 
2150 	init_deferred_free(pool);
2151 	rwlock_init(&pool->lock);
2152 	atomic_set(&pool->compaction_in_progress, 0);
2153 
2154 	pool->name = kstrdup(name, GFP_KERNEL);
2155 	if (!pool->name)
2156 		goto err;
2157 
2158 	/*
2159 	 * Iterate reversely, because, size of size_class that we want to use
2160 	 * for merging should be larger or equal to current size.
2161 	 */
2162 	for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2163 		int size;
2164 		int pages_per_zspage;
2165 		int objs_per_zspage;
2166 		struct size_class *class;
2167 		int fullness;
2168 
2169 		size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2170 		if (size > ZS_MAX_ALLOC_SIZE)
2171 			size = ZS_MAX_ALLOC_SIZE;
2172 		pages_per_zspage = calculate_zspage_chain_size(size);
2173 		objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2174 
2175 		/*
2176 		 * We iterate from biggest down to smallest classes,
2177 		 * so huge_class_size holds the size of the first huge
2178 		 * class. Any object bigger than or equal to that will
2179 		 * endup in the huge class.
2180 		 */
2181 		if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
2182 				!huge_class_size) {
2183 			huge_class_size = size;
2184 			/*
2185 			 * The object uses ZS_HANDLE_SIZE bytes to store the
2186 			 * handle. We need to subtract it, because zs_malloc()
2187 			 * unconditionally adds handle size before it performs
2188 			 * size class search - so object may be smaller than
2189 			 * huge class size, yet it still can end up in the huge
2190 			 * class because it grows by ZS_HANDLE_SIZE extra bytes
2191 			 * right before class lookup.
2192 			 */
2193 			huge_class_size -= (ZS_HANDLE_SIZE - 1);
2194 		}
2195 
2196 		/*
2197 		 * size_class is used for normal zsmalloc operation such
2198 		 * as alloc/free for that size. Although it is natural that we
2199 		 * have one size_class for each size, there is a chance that we
2200 		 * can get more memory utilization if we use one size_class for
2201 		 * many different sizes whose size_class have same
2202 		 * characteristics. So, we makes size_class point to
2203 		 * previous size_class if possible.
2204 		 */
2205 		if (prev_class) {
2206 			if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2207 				pool->size_class[i] = prev_class;
2208 				continue;
2209 			}
2210 		}
2211 
2212 		class = kzalloc_obj(struct size_class);
2213 		if (!class)
2214 			goto err;
2215 
2216 		class->size = size;
2217 		class->index = i;
2218 		class->pages_per_zspage = pages_per_zspage;
2219 		class->objs_per_zspage = objs_per_zspage;
2220 		spin_lock_init(&class->lock);
2221 		pool->size_class[i] = class;
2222 
2223 		fullness = ZS_INUSE_RATIO_0;
2224 		while (fullness < NR_FULLNESS_GROUPS) {
2225 			INIT_LIST_HEAD(&class->fullness_list[fullness]);
2226 			fullness++;
2227 		}
2228 
2229 		prev_class = class;
2230 	}
2231 
2232 	/* debug only, don't abort if it fails */
2233 	zs_pool_stat_create(pool, name);
2234 
2235 	/*
2236 	 * Not critical since shrinker is only used to trigger internal
2237 	 * defragmentation of the pool which is pretty optional thing.  If
2238 	 * registration fails we still can use the pool normally and user can
2239 	 * trigger compaction manually. Thus, ignore return code.
2240 	 */
2241 	zs_register_shrinker(pool);
2242 
2243 	return pool;
2244 
2245 err:
2246 	zs_destroy_pool(pool);
2247 	return NULL;
2248 }
2249 EXPORT_SYMBOL_GPL(zs_create_pool);
2250 
2251 void zs_destroy_pool(struct zs_pool *pool)
2252 {
2253 	int i;
2254 
2255 	zs_unregister_shrinker(pool);
2256 	zs_flush_migration(pool);
2257 	zs_pool_stat_destroy(pool);
2258 
2259 	for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2260 		int fg;
2261 		struct size_class *class = pool->size_class[i];
2262 
2263 		if (!class)
2264 			continue;
2265 
2266 		if (class->index != i)
2267 			continue;
2268 
2269 		for (fg = ZS_INUSE_RATIO_0; fg < NR_FULLNESS_GROUPS; fg++) {
2270 			if (list_empty(&class->fullness_list[fg]))
2271 				continue;
2272 
2273 			pr_err("Class-%d fullness group %d is not empty\n",
2274 			       class->size, fg);
2275 		}
2276 		kfree(class);
2277 	}
2278 
2279 	kfree(pool->name);
2280 	kfree(pool);
2281 }
2282 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2283 
2284 static void zs_destroy_caches(void)
2285 {
2286 	kmem_cache_destroy(handle_cachep);
2287 	handle_cachep = NULL;
2288 	kmem_cache_destroy(zspage_cachep);
2289 	zspage_cachep = NULL;
2290 }
2291 
2292 static int __init zs_init_caches(void)
2293 {
2294 	handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
2295 					  0, 0, NULL);
2296 	zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
2297 					  0, 0, NULL);
2298 
2299 	if (!handle_cachep || !zspage_cachep) {
2300 		zs_destroy_caches();
2301 		return -ENOMEM;
2302 	}
2303 	return 0;
2304 }
2305 
2306 static int __init zs_init(void)
2307 {
2308 	int rc;
2309 
2310 	rc = zs_init_caches();
2311 	if (rc)
2312 		return rc;
2313 
2314 #ifdef CONFIG_COMPACTION
2315 	rc = set_movable_ops(&zsmalloc_mops, PGTY_zsmalloc);
2316 	if (rc) {
2317 		zs_destroy_caches();
2318 		return rc;
2319 	}
2320 #endif
2321 	zs_stat_init();
2322 	return 0;
2323 }
2324 
2325 static void __exit zs_exit(void)
2326 {
2327 #ifdef CONFIG_COMPACTION
2328 	set_movable_ops(NULL, PGTY_zsmalloc);
2329 #endif
2330 	zs_stat_exit();
2331 	zs_destroy_caches();
2332 }
2333 
2334 module_init(zs_init);
2335 module_exit(zs_exit);
2336 
2337 MODULE_LICENSE("Dual BSD/GPL");
2338 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2339 MODULE_DESCRIPTION("zsmalloc memory allocator");
2340