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