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