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