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->first_page: points to the first component (0-order) page
20 *	page->index (union with page->freelist): offset of the first object
21 *		starting in this page. For the first page, this is
22 *		always 0, so we use this field (aka freelist) to point
23 *		to the first free object in zspage.
24 *	page->lru: links together all component pages (except the first page)
25 *		of a zspage
26 *
27 *	For _first_ page only:
28 *
29 *	page->private (union with page->first_page): refers to the
30 *		component page after the first page
31 *		If the page is first_page for huge object, it stores handle.
32 *		Look at size_class->huge.
33 *	page->freelist: points to the first free object in zspage.
34 *		Free objects are linked together using in-place
35 *		metadata.
36 *	page->objects: maximum number of objects we can store in this
37 *		zspage (class->zspage_order * PAGE_SIZE / class->size)
38 *	page->lru: links together first pages of various zspages.
39 *		Basically forming list of zspages in a fullness group.
40 *	page->mapping: class index and fullness group of the zspage
41 *
42 * Usage of struct page flags:
43 *	PG_private: identifies the first component page
44 *	PG_private2: identifies the last component page
45 *
46 */
47
48#ifdef CONFIG_ZSMALLOC_DEBUG
49#define DEBUG
50#endif
51
52#include <linux/module.h>
53#include <linux/kernel.h>
54#include <linux/sched.h>
55#include <linux/bitops.h>
56#include <linux/errno.h>
57#include <linux/highmem.h>
58#include <linux/string.h>
59#include <linux/slab.h>
60#include <asm/tlbflush.h>
61#include <asm/pgtable.h>
62#include <linux/cpumask.h>
63#include <linux/cpu.h>
64#include <linux/vmalloc.h>
65#include <linux/hardirq.h>
66#include <linux/spinlock.h>
67#include <linux/types.h>
68#include <linux/debugfs.h>
69#include <linux/zsmalloc.h>
70#include <linux/zpool.h>
71
72/*
73 * This must be power of 2 and greater than of 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/*
81 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
82 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
83 */
84#define ZS_MAX_ZSPAGE_ORDER 2
85#define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
86
87#define ZS_HANDLE_SIZE (sizeof(unsigned long))
88
89/*
90 * Object location (<PFN>, <obj_idx>) is encoded as
91 * as single (unsigned long) handle value.
92 *
93 * Note that object index <obj_idx> is relative to system
94 * page <PFN> it is stored in, so for each sub-page belonging
95 * to a zspage, obj_idx starts with 0.
96 *
97 * This is made more complicated by various memory models and PAE.
98 */
99
100#ifndef MAX_PHYSMEM_BITS
101#ifdef CONFIG_HIGHMEM64G
102#define MAX_PHYSMEM_BITS 36
103#else /* !CONFIG_HIGHMEM64G */
104/*
105 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
106 * be PAGE_SHIFT
107 */
108#define MAX_PHYSMEM_BITS BITS_PER_LONG
109#endif
110#endif
111#define _PFN_BITS		(MAX_PHYSMEM_BITS - PAGE_SHIFT)
112
113/*
114 * Memory for allocating for handle keeps object position by
115 * encoding <page, obj_idx> and the encoded value has a room
116 * in least bit(ie, look at obj_to_location).
117 * We use the bit to synchronize between object access by
118 * user and migration.
119 */
120#define HANDLE_PIN_BIT	0
121
122/*
123 * Head in allocated object should have OBJ_ALLOCATED_TAG
124 * to identify the object was allocated or not.
125 * It's okay to add the status bit in the least bit because
126 * header keeps handle which is 4byte-aligned address so we
127 * have room for two bit at least.
128 */
129#define OBJ_ALLOCATED_TAG 1
130#define OBJ_TAG_BITS 1
131#define OBJ_INDEX_BITS	(BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
132#define OBJ_INDEX_MASK	((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
133
134#define MAX(a, b) ((a) >= (b) ? (a) : (b))
135/* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
136#define ZS_MIN_ALLOC_SIZE \
137	MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
138/* each chunk includes extra space to keep handle */
139#define ZS_MAX_ALLOC_SIZE	PAGE_SIZE
140
141/*
142 * On systems with 4K page size, this gives 255 size classes! There is a
143 * trader-off here:
144 *  - Large number of size classes is potentially wasteful as free page are
145 *    spread across these classes
146 *  - Small number of size classes causes large internal fragmentation
147 *  - Probably its better to use specific size classes (empirically
148 *    determined). NOTE: all those class sizes must be set as multiple of
149 *    ZS_ALIGN to make sure link_free itself never has to span 2 pages.
150 *
151 *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
152 *  (reason above)
153 */
154#define ZS_SIZE_CLASS_DELTA	(PAGE_SIZE >> 8)
155
156/*
157 * We do not maintain any list for completely empty or full pages
158 */
159enum fullness_group {
160	ZS_ALMOST_FULL,
161	ZS_ALMOST_EMPTY,
162	_ZS_NR_FULLNESS_GROUPS,
163
164	ZS_EMPTY,
165	ZS_FULL
166};
167
168enum zs_stat_type {
169	OBJ_ALLOCATED,
170	OBJ_USED,
171	CLASS_ALMOST_FULL,
172	CLASS_ALMOST_EMPTY,
173	NR_ZS_STAT_TYPE,
174};
175
176#ifdef CONFIG_ZSMALLOC_STAT
177
178static struct dentry *zs_stat_root;
179
180struct zs_size_stat {
181	unsigned long objs[NR_ZS_STAT_TYPE];
182};
183
184#endif
185
186/*
187 * number of size_classes
188 */
189static int zs_size_classes;
190
191/*
192 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
193 *	n <= N / f, where
194 * n = number of allocated objects
195 * N = total number of objects zspage can store
196 * f = fullness_threshold_frac
197 *
198 * Similarly, we assign zspage to:
199 *	ZS_ALMOST_FULL	when n > N / f
200 *	ZS_EMPTY	when n == 0
201 *	ZS_FULL		when n == N
202 *
203 * (see: fix_fullness_group())
204 */
205static const int fullness_threshold_frac = 4;
206
207struct size_class {
208	/*
209	 * Size of objects stored in this class. Must be multiple
210	 * of ZS_ALIGN.
211	 */
212	int size;
213	unsigned int index;
214
215	/* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
216	int pages_per_zspage;
217	/* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
218	bool huge;
219
220#ifdef CONFIG_ZSMALLOC_STAT
221	struct zs_size_stat stats;
222#endif
223
224	spinlock_t lock;
225
226	struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
227};
228
229/*
230 * Placed within free objects to form a singly linked list.
231 * For every zspage, first_page->freelist gives head of this list.
232 *
233 * This must be power of 2 and less than or equal to ZS_ALIGN
234 */
235struct link_free {
236	union {
237		/*
238		 * Position of next free chunk (encodes <PFN, obj_idx>)
239		 * It's valid for non-allocated object
240		 */
241		void *next;
242		/*
243		 * Handle of allocated object.
244		 */
245		unsigned long handle;
246	};
247};
248
249struct zs_pool {
250	char *name;
251
252	struct size_class **size_class;
253	struct kmem_cache *handle_cachep;
254
255	gfp_t flags;	/* allocation flags used when growing pool */
256	atomic_long_t pages_allocated;
257
258#ifdef CONFIG_ZSMALLOC_STAT
259	struct dentry *stat_dentry;
260#endif
261};
262
263/*
264 * A zspage's class index and fullness group
265 * are encoded in its (first)page->mapping
266 */
267#define CLASS_IDX_BITS	28
268#define FULLNESS_BITS	4
269#define CLASS_IDX_MASK	((1 << CLASS_IDX_BITS) - 1)
270#define FULLNESS_MASK	((1 << FULLNESS_BITS) - 1)
271
272struct mapping_area {
273#ifdef CONFIG_PGTABLE_MAPPING
274	struct vm_struct *vm; /* vm area for mapping object that span pages */
275#else
276	char *vm_buf; /* copy buffer for objects that span pages */
277#endif
278	char *vm_addr; /* address of kmap_atomic()'ed pages */
279	enum zs_mapmode vm_mm; /* mapping mode */
280	bool huge;
281};
282
283static int create_handle_cache(struct zs_pool *pool)
284{
285	pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
286					0, 0, NULL);
287	return pool->handle_cachep ? 0 : 1;
288}
289
290static void destroy_handle_cache(struct zs_pool *pool)
291{
292	if (pool->handle_cachep)
293		kmem_cache_destroy(pool->handle_cachep);
294}
295
296static unsigned long alloc_handle(struct zs_pool *pool)
297{
298	return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
299		pool->flags & ~__GFP_HIGHMEM);
300}
301
302static void free_handle(struct zs_pool *pool, unsigned long handle)
303{
304	kmem_cache_free(pool->handle_cachep, (void *)handle);
305}
306
307static void record_obj(unsigned long handle, unsigned long obj)
308{
309	/*
310	 * lsb of @obj represents handle lock while other bits
311	 * represent object value the handle is pointing so
312	 * updating shouldn't do store tearing.
313	 */
314	WRITE_ONCE(*(unsigned long *)handle, obj);
315}
316
317/* zpool driver */
318
319#ifdef CONFIG_ZPOOL
320
321static void *zs_zpool_create(char *name, gfp_t gfp, struct zpool_ops *zpool_ops)
322{
323	return zs_create_pool(name, gfp);
324}
325
326static void zs_zpool_destroy(void *pool)
327{
328	zs_destroy_pool(pool);
329}
330
331static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
332			unsigned long *handle)
333{
334	*handle = zs_malloc(pool, size);
335	return *handle ? 0 : -1;
336}
337static void zs_zpool_free(void *pool, unsigned long handle)
338{
339	zs_free(pool, handle);
340}
341
342static int zs_zpool_shrink(void *pool, unsigned int pages,
343			unsigned int *reclaimed)
344{
345	return -EINVAL;
346}
347
348static void *zs_zpool_map(void *pool, unsigned long handle,
349			enum zpool_mapmode mm)
350{
351	enum zs_mapmode zs_mm;
352
353	switch (mm) {
354	case ZPOOL_MM_RO:
355		zs_mm = ZS_MM_RO;
356		break;
357	case ZPOOL_MM_WO:
358		zs_mm = ZS_MM_WO;
359		break;
360	case ZPOOL_MM_RW: /* fallthru */
361	default:
362		zs_mm = ZS_MM_RW;
363		break;
364	}
365
366	return zs_map_object(pool, handle, zs_mm);
367}
368static void zs_zpool_unmap(void *pool, unsigned long handle)
369{
370	zs_unmap_object(pool, handle);
371}
372
373static u64 zs_zpool_total_size(void *pool)
374{
375	return zs_get_total_pages(pool) << PAGE_SHIFT;
376}
377
378static struct zpool_driver zs_zpool_driver = {
379	.type =		"zsmalloc",
380	.owner =	THIS_MODULE,
381	.create =	zs_zpool_create,
382	.destroy =	zs_zpool_destroy,
383	.malloc =	zs_zpool_malloc,
384	.free =		zs_zpool_free,
385	.shrink =	zs_zpool_shrink,
386	.map =		zs_zpool_map,
387	.unmap =	zs_zpool_unmap,
388	.total_size =	zs_zpool_total_size,
389};
390
391MODULE_ALIAS("zpool-zsmalloc");
392#endif /* CONFIG_ZPOOL */
393
394static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
395{
396	return pages_per_zspage * PAGE_SIZE / size;
397}
398
399/* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
400static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
401
402static int is_first_page(struct page *page)
403{
404	return PagePrivate(page);
405}
406
407static int is_last_page(struct page *page)
408{
409	return PagePrivate2(page);
410}
411
412static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
413				enum fullness_group *fullness)
414{
415	unsigned long m;
416	BUG_ON(!is_first_page(page));
417
418	m = (unsigned long)page->mapping;
419	*fullness = m & FULLNESS_MASK;
420	*class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
421}
422
423static void set_zspage_mapping(struct page *page, unsigned int class_idx,
424				enum fullness_group fullness)
425{
426	unsigned long m;
427	BUG_ON(!is_first_page(page));
428
429	m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
430			(fullness & FULLNESS_MASK);
431	page->mapping = (struct address_space *)m;
432}
433
434/*
435 * zsmalloc divides the pool into various size classes where each
436 * class maintains a list of zspages where each zspage is divided
437 * into equal sized chunks. Each allocation falls into one of these
438 * classes depending on its size. This function returns index of the
439 * size class which has chunk size big enough to hold the give size.
440 */
441static int get_size_class_index(int size)
442{
443	int idx = 0;
444
445	if (likely(size > ZS_MIN_ALLOC_SIZE))
446		idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
447				ZS_SIZE_CLASS_DELTA);
448
449	return min(zs_size_classes - 1, idx);
450}
451
452#ifdef CONFIG_ZSMALLOC_STAT
453
454static inline void zs_stat_inc(struct size_class *class,
455				enum zs_stat_type type, unsigned long cnt)
456{
457	class->stats.objs[type] += cnt;
458}
459
460static inline void zs_stat_dec(struct size_class *class,
461				enum zs_stat_type type, unsigned long cnt)
462{
463	class->stats.objs[type] -= cnt;
464}
465
466static inline unsigned long zs_stat_get(struct size_class *class,
467				enum zs_stat_type type)
468{
469	return class->stats.objs[type];
470}
471
472static int __init zs_stat_init(void)
473{
474	if (!debugfs_initialized())
475		return -ENODEV;
476
477	zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
478	if (!zs_stat_root)
479		return -ENOMEM;
480
481	return 0;
482}
483
484static void __exit zs_stat_exit(void)
485{
486	debugfs_remove_recursive(zs_stat_root);
487}
488
489static int zs_stats_size_show(struct seq_file *s, void *v)
490{
491	int i;
492	struct zs_pool *pool = s->private;
493	struct size_class *class;
494	int objs_per_zspage;
495	unsigned long class_almost_full, class_almost_empty;
496	unsigned long obj_allocated, obj_used, pages_used;
497	unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
498	unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
499
500	seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s\n",
501			"class", "size", "almost_full", "almost_empty",
502			"obj_allocated", "obj_used", "pages_used",
503			"pages_per_zspage");
504
505	for (i = 0; i < zs_size_classes; i++) {
506		class = pool->size_class[i];
507
508		if (class->index != i)
509			continue;
510
511		spin_lock(&class->lock);
512		class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
513		class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
514		obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
515		obj_used = zs_stat_get(class, OBJ_USED);
516		spin_unlock(&class->lock);
517
518		objs_per_zspage = get_maxobj_per_zspage(class->size,
519				class->pages_per_zspage);
520		pages_used = obj_allocated / objs_per_zspage *
521				class->pages_per_zspage;
522
523		seq_printf(s, " %5u %5u %11lu %12lu %13lu %10lu %10lu %16d\n",
524			i, class->size, class_almost_full, class_almost_empty,
525			obj_allocated, obj_used, pages_used,
526			class->pages_per_zspage);
527
528		total_class_almost_full += class_almost_full;
529		total_class_almost_empty += class_almost_empty;
530		total_objs += obj_allocated;
531		total_used_objs += obj_used;
532		total_pages += pages_used;
533	}
534
535	seq_puts(s, "\n");
536	seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu\n",
537			"Total", "", total_class_almost_full,
538			total_class_almost_empty, total_objs,
539			total_used_objs, total_pages);
540
541	return 0;
542}
543
544static int zs_stats_size_open(struct inode *inode, struct file *file)
545{
546	return single_open(file, zs_stats_size_show, inode->i_private);
547}
548
549static const struct file_operations zs_stat_size_ops = {
550	.open           = zs_stats_size_open,
551	.read           = seq_read,
552	.llseek         = seq_lseek,
553	.release        = single_release,
554};
555
556static int zs_pool_stat_create(char *name, struct zs_pool *pool)
557{
558	struct dentry *entry;
559
560	if (!zs_stat_root)
561		return -ENODEV;
562
563	entry = debugfs_create_dir(name, zs_stat_root);
564	if (!entry) {
565		pr_warn("debugfs dir <%s> creation failed\n", name);
566		return -ENOMEM;
567	}
568	pool->stat_dentry = entry;
569
570	entry = debugfs_create_file("classes", S_IFREG | S_IRUGO,
571			pool->stat_dentry, pool, &zs_stat_size_ops);
572	if (!entry) {
573		pr_warn("%s: debugfs file entry <%s> creation failed\n",
574				name, "classes");
575		return -ENOMEM;
576	}
577
578	return 0;
579}
580
581static void zs_pool_stat_destroy(struct zs_pool *pool)
582{
583	debugfs_remove_recursive(pool->stat_dentry);
584}
585
586#else /* CONFIG_ZSMALLOC_STAT */
587
588static inline void zs_stat_inc(struct size_class *class,
589				enum zs_stat_type type, unsigned long cnt)
590{
591}
592
593static inline void zs_stat_dec(struct size_class *class,
594				enum zs_stat_type type, unsigned long cnt)
595{
596}
597
598static inline unsigned long zs_stat_get(struct size_class *class,
599				enum zs_stat_type type)
600{
601	return 0;
602}
603
604static int __init zs_stat_init(void)
605{
606	return 0;
607}
608
609static void __exit zs_stat_exit(void)
610{
611}
612
613static inline int zs_pool_stat_create(char *name, struct zs_pool *pool)
614{
615	return 0;
616}
617
618static inline void zs_pool_stat_destroy(struct zs_pool *pool)
619{
620}
621
622#endif
623
624
625/*
626 * For each size class, zspages are divided into different groups
627 * depending on how "full" they are. This was done so that we could
628 * easily find empty or nearly empty zspages when we try to shrink
629 * the pool (not yet implemented). This function returns fullness
630 * status of the given page.
631 */
632static enum fullness_group get_fullness_group(struct page *page)
633{
634	int inuse, max_objects;
635	enum fullness_group fg;
636	BUG_ON(!is_first_page(page));
637
638	inuse = page->inuse;
639	max_objects = page->objects;
640
641	if (inuse == 0)
642		fg = ZS_EMPTY;
643	else if (inuse == max_objects)
644		fg = ZS_FULL;
645	else if (inuse <= 3 * max_objects / fullness_threshold_frac)
646		fg = ZS_ALMOST_EMPTY;
647	else
648		fg = ZS_ALMOST_FULL;
649
650	return fg;
651}
652
653/*
654 * Each size class maintains various freelists and zspages are assigned
655 * to one of these freelists based on the number of live objects they
656 * have. This functions inserts the given zspage into the freelist
657 * identified by <class, fullness_group>.
658 */
659static void insert_zspage(struct page *page, struct size_class *class,
660				enum fullness_group fullness)
661{
662	struct page **head;
663
664	BUG_ON(!is_first_page(page));
665
666	if (fullness >= _ZS_NR_FULLNESS_GROUPS)
667		return;
668
669	head = &class->fullness_list[fullness];
670	if (*head)
671		list_add_tail(&page->lru, &(*head)->lru);
672
673	*head = page;
674	zs_stat_inc(class, fullness == ZS_ALMOST_EMPTY ?
675			CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1);
676}
677
678/*
679 * This function removes the given zspage from the freelist identified
680 * by <class, fullness_group>.
681 */
682static void remove_zspage(struct page *page, struct size_class *class,
683				enum fullness_group fullness)
684{
685	struct page **head;
686
687	BUG_ON(!is_first_page(page));
688
689	if (fullness >= _ZS_NR_FULLNESS_GROUPS)
690		return;
691
692	head = &class->fullness_list[fullness];
693	BUG_ON(!*head);
694	if (list_empty(&(*head)->lru))
695		*head = NULL;
696	else if (*head == page)
697		*head = (struct page *)list_entry((*head)->lru.next,
698					struct page, lru);
699
700	list_del_init(&page->lru);
701	zs_stat_dec(class, fullness == ZS_ALMOST_EMPTY ?
702			CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1);
703}
704
705/*
706 * Each size class maintains zspages in different fullness groups depending
707 * on the number of live objects they contain. When allocating or freeing
708 * objects, the fullness status of the page can change, say, from ALMOST_FULL
709 * to ALMOST_EMPTY when freeing an object. This function checks if such
710 * a status change has occurred for the given page and accordingly moves the
711 * page from the freelist of the old fullness group to that of the new
712 * fullness group.
713 */
714static enum fullness_group fix_fullness_group(struct size_class *class,
715						struct page *page)
716{
717	int class_idx;
718	enum fullness_group currfg, newfg;
719
720	BUG_ON(!is_first_page(page));
721
722	get_zspage_mapping(page, &class_idx, &currfg);
723	newfg = get_fullness_group(page);
724	if (newfg == currfg)
725		goto out;
726
727	remove_zspage(page, class, currfg);
728	insert_zspage(page, class, newfg);
729	set_zspage_mapping(page, class_idx, newfg);
730
731out:
732	return newfg;
733}
734
735/*
736 * We have to decide on how many pages to link together
737 * to form a zspage for each size class. This is important
738 * to reduce wastage due to unusable space left at end of
739 * each zspage which is given as:
740 *     wastage = Zp % class_size
741 *     usage = Zp - wastage
742 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
743 *
744 * For example, for size class of 3/8 * PAGE_SIZE, we should
745 * link together 3 PAGE_SIZE sized pages to form a zspage
746 * since then we can perfectly fit in 8 such objects.
747 */
748static int get_pages_per_zspage(int class_size)
749{
750	int i, max_usedpc = 0;
751	/* zspage order which gives maximum used size per KB */
752	int max_usedpc_order = 1;
753
754	for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
755		int zspage_size;
756		int waste, usedpc;
757
758		zspage_size = i * PAGE_SIZE;
759		waste = zspage_size % class_size;
760		usedpc = (zspage_size - waste) * 100 / zspage_size;
761
762		if (usedpc > max_usedpc) {
763			max_usedpc = usedpc;
764			max_usedpc_order = i;
765		}
766	}
767
768	return max_usedpc_order;
769}
770
771/*
772 * A single 'zspage' is composed of many system pages which are
773 * linked together using fields in struct page. This function finds
774 * the first/head page, given any component page of a zspage.
775 */
776static struct page *get_first_page(struct page *page)
777{
778	if (is_first_page(page))
779		return page;
780	else
781		return page->first_page;
782}
783
784static struct page *get_next_page(struct page *page)
785{
786	struct page *next;
787
788	if (is_last_page(page))
789		next = NULL;
790	else if (is_first_page(page))
791		next = (struct page *)page_private(page);
792	else
793		next = list_entry(page->lru.next, struct page, lru);
794
795	return next;
796}
797
798/*
799 * Encode <page, obj_idx> as a single handle value.
800 * We use the least bit of handle for tagging.
801 */
802static void *location_to_obj(struct page *page, unsigned long obj_idx)
803{
804	unsigned long obj;
805
806	if (!page) {
807		BUG_ON(obj_idx);
808		return NULL;
809	}
810
811	obj = page_to_pfn(page) << OBJ_INDEX_BITS;
812	obj |= ((obj_idx) & OBJ_INDEX_MASK);
813	obj <<= OBJ_TAG_BITS;
814
815	return (void *)obj;
816}
817
818/*
819 * Decode <page, obj_idx> pair from the given object handle. We adjust the
820 * decoded obj_idx back to its original value since it was adjusted in
821 * location_to_obj().
822 */
823static void obj_to_location(unsigned long obj, struct page **page,
824				unsigned long *obj_idx)
825{
826	obj >>= OBJ_TAG_BITS;
827	*page = pfn_to_page(obj >> OBJ_INDEX_BITS);
828	*obj_idx = (obj & OBJ_INDEX_MASK);
829}
830
831static unsigned long handle_to_obj(unsigned long handle)
832{
833	return *(unsigned long *)handle;
834}
835
836static unsigned long obj_to_head(struct size_class *class, struct page *page,
837			void *obj)
838{
839	if (class->huge) {
840		VM_BUG_ON(!is_first_page(page));
841		return *(unsigned long *)page_private(page);
842	} else
843		return *(unsigned long *)obj;
844}
845
846static unsigned long obj_idx_to_offset(struct page *page,
847				unsigned long obj_idx, int class_size)
848{
849	unsigned long off = 0;
850
851	if (!is_first_page(page))
852		off = page->index;
853
854	return off + obj_idx * class_size;
855}
856
857static inline int trypin_tag(unsigned long handle)
858{
859	unsigned long *ptr = (unsigned long *)handle;
860
861	return !test_and_set_bit_lock(HANDLE_PIN_BIT, ptr);
862}
863
864static void pin_tag(unsigned long handle)
865{
866	while (!trypin_tag(handle));
867}
868
869static void unpin_tag(unsigned long handle)
870{
871	unsigned long *ptr = (unsigned long *)handle;
872
873	clear_bit_unlock(HANDLE_PIN_BIT, ptr);
874}
875
876static void reset_page(struct page *page)
877{
878	clear_bit(PG_private, &page->flags);
879	clear_bit(PG_private_2, &page->flags);
880	set_page_private(page, 0);
881	page->mapping = NULL;
882	page->freelist = NULL;
883	page_mapcount_reset(page);
884}
885
886static void free_zspage(struct page *first_page)
887{
888	struct page *nextp, *tmp, *head_extra;
889
890	BUG_ON(!is_first_page(first_page));
891	BUG_ON(first_page->inuse);
892
893	head_extra = (struct page *)page_private(first_page);
894
895	reset_page(first_page);
896	__free_page(first_page);
897
898	/* zspage with only 1 system page */
899	if (!head_extra)
900		return;
901
902	list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
903		list_del(&nextp->lru);
904		reset_page(nextp);
905		__free_page(nextp);
906	}
907	reset_page(head_extra);
908	__free_page(head_extra);
909}
910
911/* Initialize a newly allocated zspage */
912static void init_zspage(struct page *first_page, struct size_class *class)
913{
914	unsigned long off = 0;
915	struct page *page = first_page;
916
917	BUG_ON(!is_first_page(first_page));
918	while (page) {
919		struct page *next_page;
920		struct link_free *link;
921		unsigned int i = 1;
922		void *vaddr;
923
924		/*
925		 * page->index stores offset of first object starting
926		 * in the page. For the first page, this is always 0,
927		 * so we use first_page->index (aka ->freelist) to store
928		 * head of corresponding zspage's freelist.
929		 */
930		if (page != first_page)
931			page->index = off;
932
933		vaddr = kmap_atomic(page);
934		link = (struct link_free *)vaddr + off / sizeof(*link);
935
936		while ((off += class->size) < PAGE_SIZE) {
937			link->next = location_to_obj(page, i++);
938			link += class->size / sizeof(*link);
939		}
940
941		/*
942		 * We now come to the last (full or partial) object on this
943		 * page, which must point to the first object on the next
944		 * page (if present)
945		 */
946		next_page = get_next_page(page);
947		link->next = location_to_obj(next_page, 0);
948		kunmap_atomic(vaddr);
949		page = next_page;
950		off %= PAGE_SIZE;
951	}
952}
953
954/*
955 * Allocate a zspage for the given size class
956 */
957static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
958{
959	int i, error;
960	struct page *first_page = NULL, *uninitialized_var(prev_page);
961
962	/*
963	 * Allocate individual pages and link them together as:
964	 * 1. first page->private = first sub-page
965	 * 2. all sub-pages are linked together using page->lru
966	 * 3. each sub-page is linked to the first page using page->first_page
967	 *
968	 * For each size class, First/Head pages are linked together using
969	 * page->lru. Also, we set PG_private to identify the first page
970	 * (i.e. no other sub-page has this flag set) and PG_private_2 to
971	 * identify the last page.
972	 */
973	error = -ENOMEM;
974	for (i = 0; i < class->pages_per_zspage; i++) {
975		struct page *page;
976
977		page = alloc_page(flags);
978		if (!page)
979			goto cleanup;
980
981		INIT_LIST_HEAD(&page->lru);
982		if (i == 0) {	/* first page */
983			SetPagePrivate(page);
984			set_page_private(page, 0);
985			first_page = page;
986			first_page->inuse = 0;
987		}
988		if (i == 1)
989			set_page_private(first_page, (unsigned long)page);
990		if (i >= 1)
991			page->first_page = first_page;
992		if (i >= 2)
993			list_add(&page->lru, &prev_page->lru);
994		if (i == class->pages_per_zspage - 1)	/* last page */
995			SetPagePrivate2(page);
996		prev_page = page;
997	}
998
999	init_zspage(first_page, class);
1000
1001	first_page->freelist = location_to_obj(first_page, 0);
1002	/* Maximum number of objects we can store in this zspage */
1003	first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
1004
1005	error = 0; /* Success */
1006
1007cleanup:
1008	if (unlikely(error) && first_page) {
1009		free_zspage(first_page);
1010		first_page = NULL;
1011	}
1012
1013	return first_page;
1014}
1015
1016static struct page *find_get_zspage(struct size_class *class)
1017{
1018	int i;
1019	struct page *page;
1020
1021	for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
1022		page = class->fullness_list[i];
1023		if (page)
1024			break;
1025	}
1026
1027	return page;
1028}
1029
1030#ifdef CONFIG_PGTABLE_MAPPING
1031static inline int __zs_cpu_up(struct mapping_area *area)
1032{
1033	/*
1034	 * Make sure we don't leak memory if a cpu UP notification
1035	 * and zs_init() race and both call zs_cpu_up() on the same cpu
1036	 */
1037	if (area->vm)
1038		return 0;
1039	area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
1040	if (!area->vm)
1041		return -ENOMEM;
1042	return 0;
1043}
1044
1045static inline void __zs_cpu_down(struct mapping_area *area)
1046{
1047	if (area->vm)
1048		free_vm_area(area->vm);
1049	area->vm = NULL;
1050}
1051
1052static inline void *__zs_map_object(struct mapping_area *area,
1053				struct page *pages[2], int off, int size)
1054{
1055	BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1056	area->vm_addr = area->vm->addr;
1057	return area->vm_addr + off;
1058}
1059
1060static inline void __zs_unmap_object(struct mapping_area *area,
1061				struct page *pages[2], int off, int size)
1062{
1063	unsigned long addr = (unsigned long)area->vm_addr;
1064
1065	unmap_kernel_range(addr, PAGE_SIZE * 2);
1066}
1067
1068#else /* CONFIG_PGTABLE_MAPPING */
1069
1070static inline int __zs_cpu_up(struct mapping_area *area)
1071{
1072	/*
1073	 * Make sure we don't leak memory if a cpu UP notification
1074	 * and zs_init() race and both call zs_cpu_up() on the same cpu
1075	 */
1076	if (area->vm_buf)
1077		return 0;
1078	area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1079	if (!area->vm_buf)
1080		return -ENOMEM;
1081	return 0;
1082}
1083
1084static inline void __zs_cpu_down(struct mapping_area *area)
1085{
1086	kfree(area->vm_buf);
1087	area->vm_buf = NULL;
1088}
1089
1090static void *__zs_map_object(struct mapping_area *area,
1091			struct page *pages[2], int off, int size)
1092{
1093	int sizes[2];
1094	void *addr;
1095	char *buf = area->vm_buf;
1096
1097	/* disable page faults to match kmap_atomic() return conditions */
1098	pagefault_disable();
1099
1100	/* no read fastpath */
1101	if (area->vm_mm == ZS_MM_WO)
1102		goto out;
1103
1104	sizes[0] = PAGE_SIZE - off;
1105	sizes[1] = size - sizes[0];
1106
1107	/* copy object to per-cpu buffer */
1108	addr = kmap_atomic(pages[0]);
1109	memcpy(buf, addr + off, sizes[0]);
1110	kunmap_atomic(addr);
1111	addr = kmap_atomic(pages[1]);
1112	memcpy(buf + sizes[0], addr, sizes[1]);
1113	kunmap_atomic(addr);
1114out:
1115	return area->vm_buf;
1116}
1117
1118static void __zs_unmap_object(struct mapping_area *area,
1119			struct page *pages[2], int off, int size)
1120{
1121	int sizes[2];
1122	void *addr;
1123	char *buf;
1124
1125	/* no write fastpath */
1126	if (area->vm_mm == ZS_MM_RO)
1127		goto out;
1128
1129	buf = area->vm_buf;
1130	if (!area->huge) {
1131		buf = buf + ZS_HANDLE_SIZE;
1132		size -= ZS_HANDLE_SIZE;
1133		off += ZS_HANDLE_SIZE;
1134	}
1135
1136	sizes[0] = PAGE_SIZE - off;
1137	sizes[1] = size - sizes[0];
1138
1139	/* copy per-cpu buffer to object */
1140	addr = kmap_atomic(pages[0]);
1141	memcpy(addr + off, buf, sizes[0]);
1142	kunmap_atomic(addr);
1143	addr = kmap_atomic(pages[1]);
1144	memcpy(addr, buf + sizes[0], sizes[1]);
1145	kunmap_atomic(addr);
1146
1147out:
1148	/* enable page faults to match kunmap_atomic() return conditions */
1149	pagefault_enable();
1150}
1151
1152#endif /* CONFIG_PGTABLE_MAPPING */
1153
1154static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
1155				void *pcpu)
1156{
1157	int ret, cpu = (long)pcpu;
1158	struct mapping_area *area;
1159
1160	switch (action) {
1161	case CPU_UP_PREPARE:
1162		area = &per_cpu(zs_map_area, cpu);
1163		ret = __zs_cpu_up(area);
1164		if (ret)
1165			return notifier_from_errno(ret);
1166		break;
1167	case CPU_DEAD:
1168	case CPU_UP_CANCELED:
1169		area = &per_cpu(zs_map_area, cpu);
1170		__zs_cpu_down(area);
1171		break;
1172	}
1173
1174	return NOTIFY_OK;
1175}
1176
1177static struct notifier_block zs_cpu_nb = {
1178	.notifier_call = zs_cpu_notifier
1179};
1180
1181static int zs_register_cpu_notifier(void)
1182{
1183	int cpu, uninitialized_var(ret);
1184
1185	cpu_notifier_register_begin();
1186
1187	__register_cpu_notifier(&zs_cpu_nb);
1188	for_each_online_cpu(cpu) {
1189		ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
1190		if (notifier_to_errno(ret))
1191			break;
1192	}
1193
1194	cpu_notifier_register_done();
1195	return notifier_to_errno(ret);
1196}
1197
1198static void zs_unregister_cpu_notifier(void)
1199{
1200	int cpu;
1201
1202	cpu_notifier_register_begin();
1203
1204	for_each_online_cpu(cpu)
1205		zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
1206	__unregister_cpu_notifier(&zs_cpu_nb);
1207
1208	cpu_notifier_register_done();
1209}
1210
1211static void init_zs_size_classes(void)
1212{
1213	int nr;
1214
1215	nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
1216	if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
1217		nr += 1;
1218
1219	zs_size_classes = nr;
1220}
1221
1222static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
1223{
1224	if (prev->pages_per_zspage != pages_per_zspage)
1225		return false;
1226
1227	if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
1228		!= get_maxobj_per_zspage(size, pages_per_zspage))
1229		return false;
1230
1231	return true;
1232}
1233
1234static bool zspage_full(struct page *page)
1235{
1236	BUG_ON(!is_first_page(page));
1237
1238	return page->inuse == page->objects;
1239}
1240
1241unsigned long zs_get_total_pages(struct zs_pool *pool)
1242{
1243	return atomic_long_read(&pool->pages_allocated);
1244}
1245EXPORT_SYMBOL_GPL(zs_get_total_pages);
1246
1247/**
1248 * zs_map_object - get address of allocated object from handle.
1249 * @pool: pool from which the object was allocated
1250 * @handle: handle returned from zs_malloc
1251 *
1252 * Before using an object allocated from zs_malloc, it must be mapped using
1253 * this function. When done with the object, it must be unmapped using
1254 * zs_unmap_object.
1255 *
1256 * Only one object can be mapped per cpu at a time. There is no protection
1257 * against nested mappings.
1258 *
1259 * This function returns with preemption and page faults disabled.
1260 */
1261void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1262			enum zs_mapmode mm)
1263{
1264	struct page *page;
1265	unsigned long obj, obj_idx, off;
1266
1267	unsigned int class_idx;
1268	enum fullness_group fg;
1269	struct size_class *class;
1270	struct mapping_area *area;
1271	struct page *pages[2];
1272	void *ret;
1273
1274	BUG_ON(!handle);
1275
1276	/*
1277	 * Because we use per-cpu mapping areas shared among the
1278	 * pools/users, we can't allow mapping in interrupt context
1279	 * because it can corrupt another users mappings.
1280	 */
1281	BUG_ON(in_interrupt());
1282
1283	/* From now on, migration cannot move the object */
1284	pin_tag(handle);
1285
1286	obj = handle_to_obj(handle);
1287	obj_to_location(obj, &page, &obj_idx);
1288	get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1289	class = pool->size_class[class_idx];
1290	off = obj_idx_to_offset(page, obj_idx, class->size);
1291
1292	area = &get_cpu_var(zs_map_area);
1293	area->vm_mm = mm;
1294	if (off + class->size <= PAGE_SIZE) {
1295		/* this object is contained entirely within a page */
1296		area->vm_addr = kmap_atomic(page);
1297		ret = area->vm_addr + off;
1298		goto out;
1299	}
1300
1301	/* this object spans two pages */
1302	pages[0] = page;
1303	pages[1] = get_next_page(page);
1304	BUG_ON(!pages[1]);
1305
1306	ret = __zs_map_object(area, pages, off, class->size);
1307out:
1308	if (!class->huge)
1309		ret += ZS_HANDLE_SIZE;
1310
1311	return ret;
1312}
1313EXPORT_SYMBOL_GPL(zs_map_object);
1314
1315void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1316{
1317	struct page *page;
1318	unsigned long obj, obj_idx, off;
1319
1320	unsigned int class_idx;
1321	enum fullness_group fg;
1322	struct size_class *class;
1323	struct mapping_area *area;
1324
1325	BUG_ON(!handle);
1326
1327	obj = handle_to_obj(handle);
1328	obj_to_location(obj, &page, &obj_idx);
1329	get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1330	class = pool->size_class[class_idx];
1331	off = obj_idx_to_offset(page, obj_idx, class->size);
1332
1333	area = this_cpu_ptr(&zs_map_area);
1334	if (off + class->size <= PAGE_SIZE)
1335		kunmap_atomic(area->vm_addr);
1336	else {
1337		struct page *pages[2];
1338
1339		pages[0] = page;
1340		pages[1] = get_next_page(page);
1341		BUG_ON(!pages[1]);
1342
1343		__zs_unmap_object(area, pages, off, class->size);
1344	}
1345	put_cpu_var(zs_map_area);
1346	unpin_tag(handle);
1347}
1348EXPORT_SYMBOL_GPL(zs_unmap_object);
1349
1350static unsigned long obj_malloc(struct page *first_page,
1351		struct size_class *class, unsigned long handle)
1352{
1353	unsigned long obj;
1354	struct link_free *link;
1355
1356	struct page *m_page;
1357	unsigned long m_objidx, m_offset;
1358	void *vaddr;
1359
1360	handle |= OBJ_ALLOCATED_TAG;
1361	obj = (unsigned long)first_page->freelist;
1362	obj_to_location(obj, &m_page, &m_objidx);
1363	m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
1364
1365	vaddr = kmap_atomic(m_page);
1366	link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1367	first_page->freelist = link->next;
1368	if (!class->huge)
1369		/* record handle in the header of allocated chunk */
1370		link->handle = handle;
1371	else
1372		/* record handle in first_page->private */
1373		set_page_private(first_page, handle);
1374	kunmap_atomic(vaddr);
1375	first_page->inuse++;
1376	zs_stat_inc(class, OBJ_USED, 1);
1377
1378	return obj;
1379}
1380
1381
1382/**
1383 * zs_malloc - Allocate block of given size from pool.
1384 * @pool: pool to allocate from
1385 * @size: size of block to allocate
1386 *
1387 * On success, handle to the allocated object is returned,
1388 * otherwise 0.
1389 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1390 */
1391unsigned long zs_malloc(struct zs_pool *pool, size_t size)
1392{
1393	unsigned long handle, obj;
1394	struct size_class *class;
1395	struct page *first_page;
1396
1397	if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1398		return 0;
1399
1400	handle = alloc_handle(pool);
1401	if (!handle)
1402		return 0;
1403
1404	/* extra space in chunk to keep the handle */
1405	size += ZS_HANDLE_SIZE;
1406	class = pool->size_class[get_size_class_index(size)];
1407
1408	spin_lock(&class->lock);
1409	first_page = find_get_zspage(class);
1410
1411	if (!first_page) {
1412		spin_unlock(&class->lock);
1413		first_page = alloc_zspage(class, pool->flags);
1414		if (unlikely(!first_page)) {
1415			free_handle(pool, handle);
1416			return 0;
1417		}
1418
1419		set_zspage_mapping(first_page, class->index, ZS_EMPTY);
1420		atomic_long_add(class->pages_per_zspage,
1421					&pool->pages_allocated);
1422
1423		spin_lock(&class->lock);
1424		zs_stat_inc(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1425				class->size, class->pages_per_zspage));
1426	}
1427
1428	obj = obj_malloc(first_page, class, handle);
1429	/* Now move the zspage to another fullness group, if required */
1430	fix_fullness_group(class, first_page);
1431	record_obj(handle, obj);
1432	spin_unlock(&class->lock);
1433
1434	return handle;
1435}
1436EXPORT_SYMBOL_GPL(zs_malloc);
1437
1438static void obj_free(struct zs_pool *pool, struct size_class *class,
1439			unsigned long obj)
1440{
1441	struct link_free *link;
1442	struct page *first_page, *f_page;
1443	unsigned long f_objidx, f_offset;
1444	void *vaddr;
1445	int class_idx;
1446	enum fullness_group fullness;
1447
1448	BUG_ON(!obj);
1449
1450	obj &= ~OBJ_ALLOCATED_TAG;
1451	obj_to_location(obj, &f_page, &f_objidx);
1452	first_page = get_first_page(f_page);
1453
1454	get_zspage_mapping(first_page, &class_idx, &fullness);
1455	f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1456
1457	vaddr = kmap_atomic(f_page);
1458
1459	/* Insert this object in containing zspage's freelist */
1460	link = (struct link_free *)(vaddr + f_offset);
1461	link->next = first_page->freelist;
1462	if (class->huge)
1463		set_page_private(first_page, 0);
1464	kunmap_atomic(vaddr);
1465	first_page->freelist = (void *)obj;
1466	first_page->inuse--;
1467	zs_stat_dec(class, OBJ_USED, 1);
1468}
1469
1470void zs_free(struct zs_pool *pool, unsigned long handle)
1471{
1472	struct page *first_page, *f_page;
1473	unsigned long obj, f_objidx;
1474	int class_idx;
1475	struct size_class *class;
1476	enum fullness_group fullness;
1477
1478	if (unlikely(!handle))
1479		return;
1480
1481	pin_tag(handle);
1482	obj = handle_to_obj(handle);
1483	obj_to_location(obj, &f_page, &f_objidx);
1484	first_page = get_first_page(f_page);
1485
1486	get_zspage_mapping(first_page, &class_idx, &fullness);
1487	class = pool->size_class[class_idx];
1488
1489	spin_lock(&class->lock);
1490	obj_free(pool, class, obj);
1491	fullness = fix_fullness_group(class, first_page);
1492	if (fullness == ZS_EMPTY) {
1493		zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1494				class->size, class->pages_per_zspage));
1495		atomic_long_sub(class->pages_per_zspage,
1496				&pool->pages_allocated);
1497		free_zspage(first_page);
1498	}
1499	spin_unlock(&class->lock);
1500	unpin_tag(handle);
1501
1502	free_handle(pool, handle);
1503}
1504EXPORT_SYMBOL_GPL(zs_free);
1505
1506static void zs_object_copy(unsigned long src, unsigned long dst,
1507				struct size_class *class)
1508{
1509	struct page *s_page, *d_page;
1510	unsigned long s_objidx, d_objidx;
1511	unsigned long s_off, d_off;
1512	void *s_addr, *d_addr;
1513	int s_size, d_size, size;
1514	int written = 0;
1515
1516	s_size = d_size = class->size;
1517
1518	obj_to_location(src, &s_page, &s_objidx);
1519	obj_to_location(dst, &d_page, &d_objidx);
1520
1521	s_off = obj_idx_to_offset(s_page, s_objidx, class->size);
1522	d_off = obj_idx_to_offset(d_page, d_objidx, class->size);
1523
1524	if (s_off + class->size > PAGE_SIZE)
1525		s_size = PAGE_SIZE - s_off;
1526
1527	if (d_off + class->size > PAGE_SIZE)
1528		d_size = PAGE_SIZE - d_off;
1529
1530	s_addr = kmap_atomic(s_page);
1531	d_addr = kmap_atomic(d_page);
1532
1533	while (1) {
1534		size = min(s_size, d_size);
1535		memcpy(d_addr + d_off, s_addr + s_off, size);
1536		written += size;
1537
1538		if (written == class->size)
1539			break;
1540
1541		s_off += size;
1542		s_size -= size;
1543		d_off += size;
1544		d_size -= size;
1545
1546		if (s_off >= PAGE_SIZE) {
1547			kunmap_atomic(d_addr);
1548			kunmap_atomic(s_addr);
1549			s_page = get_next_page(s_page);
1550			BUG_ON(!s_page);
1551			s_addr = kmap_atomic(s_page);
1552			d_addr = kmap_atomic(d_page);
1553			s_size = class->size - written;
1554			s_off = 0;
1555		}
1556
1557		if (d_off >= PAGE_SIZE) {
1558			kunmap_atomic(d_addr);
1559			d_page = get_next_page(d_page);
1560			BUG_ON(!d_page);
1561			d_addr = kmap_atomic(d_page);
1562			d_size = class->size - written;
1563			d_off = 0;
1564		}
1565	}
1566
1567	kunmap_atomic(d_addr);
1568	kunmap_atomic(s_addr);
1569}
1570
1571/*
1572 * Find alloced object in zspage from index object and
1573 * return handle.
1574 */
1575static unsigned long find_alloced_obj(struct page *page, int index,
1576					struct size_class *class)
1577{
1578	unsigned long head;
1579	int offset = 0;
1580	unsigned long handle = 0;
1581	void *addr = kmap_atomic(page);
1582
1583	if (!is_first_page(page))
1584		offset = page->index;
1585	offset += class->size * index;
1586
1587	while (offset < PAGE_SIZE) {
1588		head = obj_to_head(class, page, addr + offset);
1589		if (head & OBJ_ALLOCATED_TAG) {
1590			handle = head & ~OBJ_ALLOCATED_TAG;
1591			if (trypin_tag(handle))
1592				break;
1593			handle = 0;
1594		}
1595
1596		offset += class->size;
1597		index++;
1598	}
1599
1600	kunmap_atomic(addr);
1601	return handle;
1602}
1603
1604struct zs_compact_control {
1605	/* Source page for migration which could be a subpage of zspage. */
1606	struct page *s_page;
1607	/* Destination page for migration which should be a first page
1608	 * of zspage. */
1609	struct page *d_page;
1610	 /* Starting object index within @s_page which used for live object
1611	  * in the subpage. */
1612	int index;
1613	/* how many of objects are migrated */
1614	int nr_migrated;
1615};
1616
1617static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1618				struct zs_compact_control *cc)
1619{
1620	unsigned long used_obj, free_obj;
1621	unsigned long handle;
1622	struct page *s_page = cc->s_page;
1623	struct page *d_page = cc->d_page;
1624	unsigned long index = cc->index;
1625	int nr_migrated = 0;
1626	int ret = 0;
1627
1628	while (1) {
1629		handle = find_alloced_obj(s_page, index, class);
1630		if (!handle) {
1631			s_page = get_next_page(s_page);
1632			if (!s_page)
1633				break;
1634			index = 0;
1635			continue;
1636		}
1637
1638		/* Stop if there is no more space */
1639		if (zspage_full(d_page)) {
1640			unpin_tag(handle);
1641			ret = -ENOMEM;
1642			break;
1643		}
1644
1645		used_obj = handle_to_obj(handle);
1646		free_obj = obj_malloc(d_page, class, handle);
1647		zs_object_copy(used_obj, free_obj, class);
1648		index++;
1649		/*
1650		 * record_obj updates handle's value to free_obj and it will
1651		 * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
1652		 * breaks synchronization using pin_tag(e,g, zs_free) so
1653		 * let's keep the lock bit.
1654		 */
1655		free_obj |= BIT(HANDLE_PIN_BIT);
1656		record_obj(handle, free_obj);
1657		unpin_tag(handle);
1658		obj_free(pool, class, used_obj);
1659		nr_migrated++;
1660	}
1661
1662	/* Remember last position in this iteration */
1663	cc->s_page = s_page;
1664	cc->index = index;
1665	cc->nr_migrated = nr_migrated;
1666
1667	return ret;
1668}
1669
1670static struct page *alloc_target_page(struct size_class *class)
1671{
1672	int i;
1673	struct page *page;
1674
1675	for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
1676		page = class->fullness_list[i];
1677		if (page) {
1678			remove_zspage(page, class, i);
1679			break;
1680		}
1681	}
1682
1683	return page;
1684}
1685
1686static void putback_zspage(struct zs_pool *pool, struct size_class *class,
1687				struct page *first_page)
1688{
1689	enum fullness_group fullness;
1690
1691	BUG_ON(!is_first_page(first_page));
1692
1693	fullness = get_fullness_group(first_page);
1694	insert_zspage(first_page, class, fullness);
1695	set_zspage_mapping(first_page, class->index, fullness);
1696
1697	if (fullness == ZS_EMPTY) {
1698		zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1699			class->size, class->pages_per_zspage));
1700		atomic_long_sub(class->pages_per_zspage,
1701				&pool->pages_allocated);
1702
1703		free_zspage(first_page);
1704	}
1705}
1706
1707static struct page *isolate_source_page(struct size_class *class)
1708{
1709	struct page *page;
1710
1711	page = class->fullness_list[ZS_ALMOST_EMPTY];
1712	if (page)
1713		remove_zspage(page, class, ZS_ALMOST_EMPTY);
1714
1715	return page;
1716}
1717
1718static unsigned long __zs_compact(struct zs_pool *pool,
1719				struct size_class *class)
1720{
1721	int nr_to_migrate;
1722	struct zs_compact_control cc;
1723	struct page *src_page;
1724	struct page *dst_page = NULL;
1725	unsigned long nr_total_migrated = 0;
1726
1727	spin_lock(&class->lock);
1728	while ((src_page = isolate_source_page(class))) {
1729
1730		BUG_ON(!is_first_page(src_page));
1731
1732		/* The goal is to migrate all live objects in source page */
1733		nr_to_migrate = src_page->inuse;
1734		cc.index = 0;
1735		cc.s_page = src_page;
1736
1737		while ((dst_page = alloc_target_page(class))) {
1738			cc.d_page = dst_page;
1739			/*
1740			 * If there is no more space in dst_page, try to
1741			 * allocate another zspage.
1742			 */
1743			if (!migrate_zspage(pool, class, &cc))
1744				break;
1745
1746			putback_zspage(pool, class, dst_page);
1747			nr_total_migrated += cc.nr_migrated;
1748			nr_to_migrate -= cc.nr_migrated;
1749		}
1750
1751		/* Stop if we couldn't find slot */
1752		if (dst_page == NULL)
1753			break;
1754
1755		putback_zspage(pool, class, dst_page);
1756		putback_zspage(pool, class, src_page);
1757		spin_unlock(&class->lock);
1758		nr_total_migrated += cc.nr_migrated;
1759		cond_resched();
1760		spin_lock(&class->lock);
1761	}
1762
1763	if (src_page)
1764		putback_zspage(pool, class, src_page);
1765
1766	spin_unlock(&class->lock);
1767
1768	return nr_total_migrated;
1769}
1770
1771unsigned long zs_compact(struct zs_pool *pool)
1772{
1773	int i;
1774	unsigned long nr_migrated = 0;
1775	struct size_class *class;
1776
1777	for (i = zs_size_classes - 1; i >= 0; i--) {
1778		class = pool->size_class[i];
1779		if (!class)
1780			continue;
1781		if (class->index != i)
1782			continue;
1783		nr_migrated += __zs_compact(pool, class);
1784	}
1785
1786	return nr_migrated;
1787}
1788EXPORT_SYMBOL_GPL(zs_compact);
1789
1790/**
1791 * zs_create_pool - Creates an allocation pool to work from.
1792 * @flags: allocation flags used to allocate pool metadata
1793 *
1794 * This function must be called before anything when using
1795 * the zsmalloc allocator.
1796 *
1797 * On success, a pointer to the newly created pool is returned,
1798 * otherwise NULL.
1799 */
1800struct zs_pool *zs_create_pool(char *name, gfp_t flags)
1801{
1802	int i;
1803	struct zs_pool *pool;
1804	struct size_class *prev_class = NULL;
1805
1806	pool = kzalloc(sizeof(*pool), GFP_KERNEL);
1807	if (!pool)
1808		return NULL;
1809
1810	pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
1811			GFP_KERNEL);
1812	if (!pool->size_class) {
1813		kfree(pool);
1814		return NULL;
1815	}
1816
1817	pool->name = kstrdup(name, GFP_KERNEL);
1818	if (!pool->name)
1819		goto err;
1820
1821	if (create_handle_cache(pool))
1822		goto err;
1823
1824	/*
1825	 * Iterate reversly, because, size of size_class that we want to use
1826	 * for merging should be larger or equal to current size.
1827	 */
1828	for (i = zs_size_classes - 1; i >= 0; i--) {
1829		int size;
1830		int pages_per_zspage;
1831		struct size_class *class;
1832
1833		size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
1834		if (size > ZS_MAX_ALLOC_SIZE)
1835			size = ZS_MAX_ALLOC_SIZE;
1836		pages_per_zspage = get_pages_per_zspage(size);
1837
1838		/*
1839		 * size_class is used for normal zsmalloc operation such
1840		 * as alloc/free for that size. Although it is natural that we
1841		 * have one size_class for each size, there is a chance that we
1842		 * can get more memory utilization if we use one size_class for
1843		 * many different sizes whose size_class have same
1844		 * characteristics. So, we makes size_class point to
1845		 * previous size_class if possible.
1846		 */
1847		if (prev_class) {
1848			if (can_merge(prev_class, size, pages_per_zspage)) {
1849				pool->size_class[i] = prev_class;
1850				continue;
1851			}
1852		}
1853
1854		class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
1855		if (!class)
1856			goto err;
1857
1858		class->size = size;
1859		class->index = i;
1860		class->pages_per_zspage = pages_per_zspage;
1861		if (pages_per_zspage == 1 &&
1862			get_maxobj_per_zspage(size, pages_per_zspage) == 1)
1863			class->huge = true;
1864		spin_lock_init(&class->lock);
1865		pool->size_class[i] = class;
1866
1867		prev_class = class;
1868	}
1869
1870	pool->flags = flags;
1871
1872	if (zs_pool_stat_create(name, pool))
1873		goto err;
1874
1875	return pool;
1876
1877err:
1878	zs_destroy_pool(pool);
1879	return NULL;
1880}
1881EXPORT_SYMBOL_GPL(zs_create_pool);
1882
1883void zs_destroy_pool(struct zs_pool *pool)
1884{
1885	int i;
1886
1887	zs_pool_stat_destroy(pool);
1888
1889	for (i = 0; i < zs_size_classes; i++) {
1890		int fg;
1891		struct size_class *class = pool->size_class[i];
1892
1893		if (!class)
1894			continue;
1895
1896		if (class->index != i)
1897			continue;
1898
1899		for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
1900			if (class->fullness_list[fg]) {
1901				pr_info("Freeing non-empty class with size %db, fullness group %d\n",
1902					class->size, fg);
1903			}
1904		}
1905		kfree(class);
1906	}
1907
1908	destroy_handle_cache(pool);
1909	kfree(pool->size_class);
1910	kfree(pool->name);
1911	kfree(pool);
1912}
1913EXPORT_SYMBOL_GPL(zs_destroy_pool);
1914
1915static int __init zs_init(void)
1916{
1917	int ret = zs_register_cpu_notifier();
1918
1919	if (ret)
1920		goto notifier_fail;
1921
1922	init_zs_size_classes();
1923
1924#ifdef CONFIG_ZPOOL
1925	zpool_register_driver(&zs_zpool_driver);
1926#endif
1927
1928	ret = zs_stat_init();
1929	if (ret) {
1930		pr_err("zs stat initialization failed\n");
1931		goto stat_fail;
1932	}
1933	return 0;
1934
1935stat_fail:
1936#ifdef CONFIG_ZPOOL
1937	zpool_unregister_driver(&zs_zpool_driver);
1938#endif
1939notifier_fail:
1940	zs_unregister_cpu_notifier();
1941
1942	return ret;
1943}
1944
1945static void __exit zs_exit(void)
1946{
1947#ifdef CONFIG_ZPOOL
1948	zpool_unregister_driver(&zs_zpool_driver);
1949#endif
1950	zs_unregister_cpu_notifier();
1951
1952	zs_stat_exit();
1953}
1954
1955module_init(zs_init);
1956module_exit(zs_exit);
1957
1958MODULE_LICENSE("Dual BSD/GPL");
1959MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
1960