zsmalloc.c 60.3 KB
Newer Older
1 2 3 4
/*
 * zsmalloc memory allocator
 *
 * Copyright (C) 2011  Nitin Gupta
M
Minchan Kim 已提交
5
 * Copyright (C) 2012, 2013 Minchan Kim
6 7 8 9 10 11 12 13
 *
 * This code is released using a dual license strategy: BSD/GPL
 * You can choose the license that better fits your requirements.
 *
 * Released under the terms of 3-clause BSD License
 * Released under the terms of GNU General Public License Version 2.0
 */

N
Nitin Gupta 已提交
14 15 16 17 18
/*
 * Following is how we use various fields and flags of underlying
 * struct page(s) to form a zspage.
 *
 * Usage of struct page fields:
19
 *	page->private: points to zspage
M
Minchan Kim 已提交
20 21 22
 *	page->freelist(index): links together all component pages of a zspage
 *		For the huge page, this is always 0, so we use this field
 *		to store handle.
N
Nitin Gupta 已提交
23 24 25 26
 *
 * Usage of struct page flags:
 *	PG_private: identifies the first component page
 *	PG_private2: identifies the last component page
M
Minchan Kim 已提交
27
 *	PG_owner_priv_1: indentifies the huge component page
N
Nitin Gupta 已提交
28 29 30
 *
 */

31 32
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

33 34
#include <linux/module.h>
#include <linux/kernel.h>
M
Minchan Kim 已提交
35
#include <linux/sched.h>
36 37 38 39 40 41 42 43 44
#include <linux/bitops.h>
#include <linux/errno.h>
#include <linux/highmem.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <asm/tlbflush.h>
#include <asm/pgtable.h>
#include <linux/cpumask.h>
#include <linux/cpu.h>
45
#include <linux/vmalloc.h>
46
#include <linux/preempt.h>
47 48
#include <linux/spinlock.h>
#include <linux/types.h>
49
#include <linux/debugfs.h>
M
Minchan Kim 已提交
50
#include <linux/zsmalloc.h>
51
#include <linux/zpool.h>
M
Minchan Kim 已提交
52
#include <linux/mount.h>
53
#include <linux/migrate.h>
M
Minchan Kim 已提交
54 55 56
#include <linux/pagemap.h>

#define ZSPAGE_MAGIC	0x58
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

/*
 * This must be power of 2 and greater than of equal to sizeof(link_free).
 * These two conditions ensure that any 'struct link_free' itself doesn't
 * span more than 1 page which avoids complex case of mapping 2 pages simply
 * to restore link_free pointer values.
 */
#define ZS_ALIGN		8

/*
 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
 */
#define ZS_MAX_ZSPAGE_ORDER 2
#define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)

73 74
#define ZS_HANDLE_SIZE (sizeof(unsigned long))

75 76
/*
 * Object location (<PFN>, <obj_idx>) is encoded as
N
Nitin Cupta 已提交
77
 * as single (unsigned long) handle value.
78
 *
M
Minchan Kim 已提交
79
 * Note that object index <obj_idx> starts from 0.
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
 *
 * This is made more complicated by various memory models and PAE.
 */

#ifndef MAX_PHYSMEM_BITS
#ifdef CONFIG_HIGHMEM64G
#define MAX_PHYSMEM_BITS 36
#else /* !CONFIG_HIGHMEM64G */
/*
 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
 * be PAGE_SHIFT
 */
#define MAX_PHYSMEM_BITS BITS_PER_LONG
#endif
#endif
#define _PFN_BITS		(MAX_PHYSMEM_BITS - PAGE_SHIFT)
M
Minchan Kim 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

/*
 * Memory for allocating for handle keeps object position by
 * encoding <page, obj_idx> and the encoded value has a room
 * in least bit(ie, look at obj_to_location).
 * We use the bit to synchronize between object access by
 * user and migration.
 */
#define HANDLE_PIN_BIT	0

/*
 * Head in allocated object should have OBJ_ALLOCATED_TAG
 * to identify the object was allocated or not.
 * It's okay to add the status bit in the least bit because
 * header keeps handle which is 4byte-aligned address so we
 * have room for two bit at least.
 */
#define OBJ_ALLOCATED_TAG 1
#define OBJ_TAG_BITS 1
#define OBJ_INDEX_BITS	(BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
116 117 118 119 120 121
#define OBJ_INDEX_MASK	((_AC(1, UL) << OBJ_INDEX_BITS) - 1)

#define MAX(a, b) ((a) >= (b) ? (a) : (b))
/* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
#define ZS_MIN_ALLOC_SIZE \
	MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
122
/* each chunk includes extra space to keep handle */
123
#define ZS_MAX_ALLOC_SIZE	PAGE_SIZE
124 125

/*
126
 * On systems with 4K page size, this gives 255 size classes! There is a
127 128 129 130 131 132 133 134 135 136 137
 * trader-off here:
 *  - Large number of size classes is potentially wasteful as free page are
 *    spread across these classes
 *  - Small number of size classes causes large internal fragmentation
 *  - Probably its better to use specific size classes (empirically
 *    determined). NOTE: all those class sizes must be set as multiple of
 *    ZS_ALIGN to make sure link_free itself never has to span 2 pages.
 *
 *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
 *  (reason above)
 */
138
#define ZS_SIZE_CLASS_DELTA	(PAGE_SIZE >> CLASS_BITS)
139 140 141 142 143 144

/*
 * We do not maintain any list for completely empty or full pages
 */
enum fullness_group {
	ZS_EMPTY,
M
Minchan Kim 已提交
145 146 147 148
	ZS_ALMOST_EMPTY,
	ZS_ALMOST_FULL,
	ZS_FULL,
	NR_ZS_FULLNESS,
149 150
};

151
enum zs_stat_type {
M
Minchan Kim 已提交
152 153 154 155
	CLASS_EMPTY,
	CLASS_ALMOST_EMPTY,
	CLASS_ALMOST_FULL,
	CLASS_FULL,
156 157
	OBJ_ALLOCATED,
	OBJ_USED,
M
Minchan Kim 已提交
158
	NR_ZS_STAT_TYPE,
159 160 161 162 163 164
};

struct zs_size_stat {
	unsigned long objs[NR_ZS_STAT_TYPE];
};

165 166
#ifdef CONFIG_ZSMALLOC_STAT
static struct dentry *zs_stat_root;
167 168
#endif

M
Minchan Kim 已提交
169 170 171 172
#ifdef CONFIG_COMPACTION
static struct vfsmount *zsmalloc_mnt;
#endif

173 174 175 176 177
/*
 * number of size_classes
 */
static int zs_size_classes;

178 179 180 181 182
/*
 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
 *	n <= N / f, where
 * n = number of allocated objects
 * N = total number of objects zspage can store
183
 * f = fullness_threshold_frac
184 185 186 187 188 189 190 191 192 193 194
 *
 * Similarly, we assign zspage to:
 *	ZS_ALMOST_FULL	when n > N / f
 *	ZS_EMPTY	when n == 0
 *	ZS_FULL		when n == N
 *
 * (see: fix_fullness_group())
 */
static const int fullness_threshold_frac = 4;

struct size_class {
195
	spinlock_t lock;
M
Minchan Kim 已提交
196
	struct list_head fullness_list[NR_ZS_FULLNESS];
197 198 199 200 201
	/*
	 * Size of objects stored in this class. Must be multiple
	 * of ZS_ALIGN.
	 */
	int size;
202
	int objs_per_zspage;
203 204
	/* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
	int pages_per_zspage;
M
Minchan Kim 已提交
205 206 207

	unsigned int index;
	struct zs_size_stat stats;
208 209
};

M
Minchan Kim 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
/* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
static void SetPageHugeObject(struct page *page)
{
	SetPageOwnerPriv1(page);
}

static void ClearPageHugeObject(struct page *page)
{
	ClearPageOwnerPriv1(page);
}

static int PageHugeObject(struct page *page)
{
	return PageOwnerPriv1(page);
}

226 227
/*
 * Placed within free objects to form a singly linked list.
228
 * For every zspage, zspage->freeobj gives head of this list.
229 230 231 232
 *
 * This must be power of 2 and less than or equal to ZS_ALIGN
 */
struct link_free {
233 234
	union {
		/*
M
Minchan Kim 已提交
235
		 * Free object index;
236 237
		 * It's valid for non-allocated object
		 */
M
Minchan Kim 已提交
238
		unsigned long next;
239 240 241 242 243
		/*
		 * Handle of allocated object.
		 */
		unsigned long handle;
	};
244 245 246
};

struct zs_pool {
247
	const char *name;
248

249
	struct size_class **size_class;
250
	struct kmem_cache *handle_cachep;
251
	struct kmem_cache *zspage_cachep;
252

253
	atomic_long_t pages_allocated;
254

255
	struct zs_pool_stats stats;
256 257 258 259 260 261 262 263

	/* Compact classes */
	struct shrinker shrinker;
	/*
	 * To signify that register_shrinker() was successful
	 * and unregister_shrinker() will not Oops.
	 */
	bool shrinker_enabled;
264 265 266
#ifdef CONFIG_ZSMALLOC_STAT
	struct dentry *stat_dentry;
#endif
M
Minchan Kim 已提交
267 268 269 270
#ifdef CONFIG_COMPACTION
	struct inode *inode;
	struct work_struct free_work;
#endif
271
};
272 273 274 275 276

/*
 * A zspage's class index and fullness group
 * are encoded in its (first)page->mapping
 */
277 278
#define FULLNESS_BITS	2
#define CLASS_BITS	8
M
Minchan Kim 已提交
279 280
#define ISOLATED_BITS	3
#define MAGIC_VAL_BITS	8
M
Minchan Kim 已提交
281

282 283 284 285
struct zspage {
	struct {
		unsigned int fullness:FULLNESS_BITS;
		unsigned int class:CLASS_BITS;
M
Minchan Kim 已提交
286 287
		unsigned int isolated:ISOLATED_BITS;
		unsigned int magic:MAGIC_VAL_BITS;
288 289
	};
	unsigned int inuse;
M
Minchan Kim 已提交
290
	unsigned int freeobj;
291 292
	struct page *first_page;
	struct list_head list; /* fullness list */
M
Minchan Kim 已提交
293 294 295
#ifdef CONFIG_COMPACTION
	rwlock_t lock;
#endif
296
};
297

298
struct mapping_area {
299
#ifdef CONFIG_PGTABLE_MAPPING
300 301 302 303 304 305 306 307
	struct vm_struct *vm; /* vm area for mapping object that span pages */
#else
	char *vm_buf; /* copy buffer for objects that span pages */
#endif
	char *vm_addr; /* address of kmap_atomic()'ed pages */
	enum zs_mapmode vm_mm; /* mapping mode */
};

M
Minchan Kim 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
#ifdef CONFIG_COMPACTION
static int zs_register_migration(struct zs_pool *pool);
static void zs_unregister_migration(struct zs_pool *pool);
static void migrate_lock_init(struct zspage *zspage);
static void migrate_read_lock(struct zspage *zspage);
static void migrate_read_unlock(struct zspage *zspage);
static void kick_deferred_free(struct zs_pool *pool);
static void init_deferred_free(struct zs_pool *pool);
static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
#else
static int zsmalloc_mount(void) { return 0; }
static void zsmalloc_unmount(void) {}
static int zs_register_migration(struct zs_pool *pool) { return 0; }
static void zs_unregister_migration(struct zs_pool *pool) {}
static void migrate_lock_init(struct zspage *zspage) {}
static void migrate_read_lock(struct zspage *zspage) {}
static void migrate_read_unlock(struct zspage *zspage) {}
static void kick_deferred_free(struct zs_pool *pool) {}
static void init_deferred_free(struct zs_pool *pool) {}
static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
#endif

330
static int create_cache(struct zs_pool *pool)
331 332 333
{
	pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
					0, 0, NULL);
334 335 336 337 338 339 340 341 342 343 344 345
	if (!pool->handle_cachep)
		return 1;

	pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
					0, 0, NULL);
	if (!pool->zspage_cachep) {
		kmem_cache_destroy(pool->handle_cachep);
		pool->handle_cachep = NULL;
		return 1;
	}

	return 0;
346 347
}

348
static void destroy_cache(struct zs_pool *pool)
349
{
350
	kmem_cache_destroy(pool->handle_cachep);
351
	kmem_cache_destroy(pool->zspage_cachep);
352 353
}

354
static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
355 356
{
	return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
M
Minchan Kim 已提交
357
			gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
358 359
}

360
static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
361 362 363 364
{
	kmem_cache_free(pool->handle_cachep, (void *)handle);
}

365 366
static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
{
M
Minchan Kim 已提交
367 368
	return kmem_cache_alloc(pool->zspage_cachep,
			flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
369 370 371 372 373 374 375
};

static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
{
	kmem_cache_free(pool->zspage_cachep, zspage);
}

376 377
static void record_obj(unsigned long handle, unsigned long obj)
{
378 379 380 381 382 383
	/*
	 * lsb of @obj represents handle lock while other bits
	 * represent object value the handle is pointing so
	 * updating shouldn't do store tearing.
	 */
	WRITE_ONCE(*(unsigned long *)handle, obj);
384 385
}

386 387 388 389
/* zpool driver */

#ifdef CONFIG_ZPOOL

390
static void *zs_zpool_create(const char *name, gfp_t gfp,
391
			     const struct zpool_ops *zpool_ops,
D
Dan Streetman 已提交
392
			     struct zpool *zpool)
393
{
394 395 396 397 398 399
	/*
	 * Ignore global gfp flags: zs_malloc() may be invoked from
	 * different contexts and its caller must provide a valid
	 * gfp mask.
	 */
	return zs_create_pool(name);
400 401 402 403 404 405 406 407 408 409
}

static void zs_zpool_destroy(void *pool)
{
	zs_destroy_pool(pool);
}

static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
			unsigned long *handle)
{
410
	*handle = zs_malloc(pool, size, gfp);
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
	return *handle ? 0 : -1;
}
static void zs_zpool_free(void *pool, unsigned long handle)
{
	zs_free(pool, handle);
}

static int zs_zpool_shrink(void *pool, unsigned int pages,
			unsigned int *reclaimed)
{
	return -EINVAL;
}

static void *zs_zpool_map(void *pool, unsigned long handle,
			enum zpool_mapmode mm)
{
	enum zs_mapmode zs_mm;

	switch (mm) {
	case ZPOOL_MM_RO:
		zs_mm = ZS_MM_RO;
		break;
	case ZPOOL_MM_WO:
		zs_mm = ZS_MM_WO;
		break;
	case ZPOOL_MM_RW: /* fallthru */
	default:
		zs_mm = ZS_MM_RW;
		break;
	}

	return zs_map_object(pool, handle, zs_mm);
}
static void zs_zpool_unmap(void *pool, unsigned long handle)
{
	zs_unmap_object(pool, handle);
}

static u64 zs_zpool_total_size(void *pool)
{
451
	return zs_get_total_pages(pool) << PAGE_SHIFT;
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
}

static struct zpool_driver zs_zpool_driver = {
	.type =		"zsmalloc",
	.owner =	THIS_MODULE,
	.create =	zs_zpool_create,
	.destroy =	zs_zpool_destroy,
	.malloc =	zs_zpool_malloc,
	.free =		zs_zpool_free,
	.shrink =	zs_zpool_shrink,
	.map =		zs_zpool_map,
	.unmap =	zs_zpool_unmap,
	.total_size =	zs_zpool_total_size,
};

467
MODULE_ALIAS("zpool-zsmalloc");
468 469
#endif /* CONFIG_ZPOOL */

470 471 472
/* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
static DEFINE_PER_CPU(struct mapping_area, zs_map_area);

M
Minchan Kim 已提交
473 474 475 476 477
static bool is_zspage_isolated(struct zspage *zspage)
{
	return zspage->isolated;
}

478 479
static int is_first_page(struct page *page)
{
480
	return PagePrivate(page);
481 482
}

M
Minchan Kim 已提交
483
/* Protected by class->lock */
484
static inline int get_zspage_inuse(struct zspage *zspage)
M
Minchan Kim 已提交
485
{
486
	return zspage->inuse;
M
Minchan Kim 已提交
487 488
}

489
static inline void set_zspage_inuse(struct zspage *zspage, int val)
M
Minchan Kim 已提交
490
{
491
	zspage->inuse = val;
M
Minchan Kim 已提交
492 493
}

494
static inline void mod_zspage_inuse(struct zspage *zspage, int val)
M
Minchan Kim 已提交
495
{
496
	zspage->inuse += val;
M
Minchan Kim 已提交
497 498
}

M
Minchan Kim 已提交
499
static inline struct page *get_first_page(struct zspage *zspage)
M
Minchan Kim 已提交
500
{
M
Minchan Kim 已提交
501
	struct page *first_page = zspage->first_page;
502

M
Minchan Kim 已提交
503 504
	VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
	return first_page;
M
Minchan Kim 已提交
505 506
}

M
Minchan Kim 已提交
507
static inline int get_first_obj_offset(struct page *page)
M
Minchan Kim 已提交
508
{
M
Minchan Kim 已提交
509 510
	return page->units;
}
511

M
Minchan Kim 已提交
512 513 514
static inline void set_first_obj_offset(struct page *page, int offset)
{
	page->units = offset;
M
Minchan Kim 已提交
515 516
}

M
Minchan Kim 已提交
517
static inline unsigned int get_freeobj(struct zspage *zspage)
M
Minchan Kim 已提交
518
{
M
Minchan Kim 已提交
519
	return zspage->freeobj;
M
Minchan Kim 已提交
520 521
}

M
Minchan Kim 已提交
522
static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
M
Minchan Kim 已提交
523
{
M
Minchan Kim 已提交
524
	zspage->freeobj = obj;
M
Minchan Kim 已提交
525 526
}

527
static void get_zspage_mapping(struct zspage *zspage,
528
				unsigned int *class_idx,
529 530
				enum fullness_group *fullness)
{
M
Minchan Kim 已提交
531 532
	BUG_ON(zspage->magic != ZSPAGE_MAGIC);

533 534
	*fullness = zspage->fullness;
	*class_idx = zspage->class;
535 536
}

537
static void set_zspage_mapping(struct zspage *zspage,
538
				unsigned int class_idx,
539 540
				enum fullness_group fullness)
{
541 542
	zspage->class = class_idx;
	zspage->fullness = fullness;
543 544
}

N
Nitin Cupta 已提交
545 546 547 548 549 550 551
/*
 * zsmalloc divides the pool into various size classes where each
 * class maintains a list of zspages where each zspage is divided
 * into equal sized chunks. Each allocation falls into one of these
 * classes depending on its size. This function returns index of the
 * size class which has chunk size big enough to hold the give size.
 */
552 553 554 555 556 557 558 559
static int get_size_class_index(int size)
{
	int idx = 0;

	if (likely(size > ZS_MIN_ALLOC_SIZE))
		idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
				ZS_SIZE_CLASS_DELTA);

560
	return min(zs_size_classes - 1, idx);
561 562
}

M
Minchan Kim 已提交
563 564 565
static inline void zs_stat_inc(struct size_class *class,
				enum zs_stat_type type, unsigned long cnt)
{
M
Minchan Kim 已提交
566
	class->stats.objs[type] += cnt;
M
Minchan Kim 已提交
567 568 569 570 571
}

static inline void zs_stat_dec(struct size_class *class,
				enum zs_stat_type type, unsigned long cnt)
{
M
Minchan Kim 已提交
572
	class->stats.objs[type] -= cnt;
M
Minchan Kim 已提交
573 574 575 576 577
}

static inline unsigned long zs_stat_get(struct size_class *class,
				enum zs_stat_type type)
{
M
Minchan Kim 已提交
578
	return class->stats.objs[type];
M
Minchan Kim 已提交
579 580
}

581 582
#ifdef CONFIG_ZSMALLOC_STAT

583
static void __init zs_stat_init(void)
M
Minchan Kim 已提交
584
{
585 586 587 588
	if (!debugfs_initialized()) {
		pr_warn("debugfs not available, stat dir not created\n");
		return;
	}
M
Minchan Kim 已提交
589 590 591

	zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
	if (!zs_stat_root)
592
		pr_warn("debugfs 'zsmalloc' stat dir creation failed\n");
M
Minchan Kim 已提交
593 594 595 596 597 598 599
}

static void __exit zs_stat_exit(void)
{
	debugfs_remove_recursive(zs_stat_root);
}

600 601
static unsigned long zs_can_compact(struct size_class *class);

M
Minchan Kim 已提交
602 603 604 605 606 607 608
static int zs_stats_size_show(struct seq_file *s, void *v)
{
	int i;
	struct zs_pool *pool = s->private;
	struct size_class *class;
	int objs_per_zspage;
	unsigned long class_almost_full, class_almost_empty;
609
	unsigned long obj_allocated, obj_used, pages_used, freeable;
M
Minchan Kim 已提交
610 611
	unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
	unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
612
	unsigned long total_freeable = 0;
M
Minchan Kim 已提交
613

614
	seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
M
Minchan Kim 已提交
615 616
			"class", "size", "almost_full", "almost_empty",
			"obj_allocated", "obj_used", "pages_used",
617
			"pages_per_zspage", "freeable");
M
Minchan Kim 已提交
618 619 620 621 622 623 624 625 626 627 628 629

	for (i = 0; i < zs_size_classes; i++) {
		class = pool->size_class[i];

		if (class->index != i)
			continue;

		spin_lock(&class->lock);
		class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
		class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
		obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
		obj_used = zs_stat_get(class, OBJ_USED);
630
		freeable = zs_can_compact(class);
M
Minchan Kim 已提交
631 632
		spin_unlock(&class->lock);

633
		objs_per_zspage = class->objs_per_zspage;
M
Minchan Kim 已提交
634 635 636
		pages_used = obj_allocated / objs_per_zspage *
				class->pages_per_zspage;

637 638
		seq_printf(s, " %5u %5u %11lu %12lu %13lu"
				" %10lu %10lu %16d %8lu\n",
M
Minchan Kim 已提交
639 640
			i, class->size, class_almost_full, class_almost_empty,
			obj_allocated, obj_used, pages_used,
641
			class->pages_per_zspage, freeable);
M
Minchan Kim 已提交
642 643 644 645 646 647

		total_class_almost_full += class_almost_full;
		total_class_almost_empty += class_almost_empty;
		total_objs += obj_allocated;
		total_used_objs += obj_used;
		total_pages += pages_used;
648
		total_freeable += freeable;
M
Minchan Kim 已提交
649 650 651
	}

	seq_puts(s, "\n");
652
	seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
M
Minchan Kim 已提交
653 654
			"Total", "", total_class_almost_full,
			total_class_almost_empty, total_objs,
655
			total_used_objs, total_pages, "", total_freeable);
M
Minchan Kim 已提交
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

	return 0;
}

static int zs_stats_size_open(struct inode *inode, struct file *file)
{
	return single_open(file, zs_stats_size_show, inode->i_private);
}

static const struct file_operations zs_stat_size_ops = {
	.open           = zs_stats_size_open,
	.read           = seq_read,
	.llseek         = seq_lseek,
	.release        = single_release,
};

672
static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
M
Minchan Kim 已提交
673 674 675
{
	struct dentry *entry;

676 677
	if (!zs_stat_root) {
		pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
678
		return;
679
	}
M
Minchan Kim 已提交
680 681 682 683

	entry = debugfs_create_dir(name, zs_stat_root);
	if (!entry) {
		pr_warn("debugfs dir <%s> creation failed\n", name);
684
		return;
M
Minchan Kim 已提交
685 686 687 688 689 690 691 692
	}
	pool->stat_dentry = entry;

	entry = debugfs_create_file("classes", S_IFREG | S_IRUGO,
			pool->stat_dentry, pool, &zs_stat_size_ops);
	if (!entry) {
		pr_warn("%s: debugfs file entry <%s> creation failed\n",
				name, "classes");
693 694
		debugfs_remove_recursive(pool->stat_dentry);
		pool->stat_dentry = NULL;
M
Minchan Kim 已提交
695 696 697 698 699 700 701 702 703
	}
}

static void zs_pool_stat_destroy(struct zs_pool *pool)
{
	debugfs_remove_recursive(pool->stat_dentry);
}

#else /* CONFIG_ZSMALLOC_STAT */
704
static void __init zs_stat_init(void)
M
Minchan Kim 已提交
705 706 707 708 709 710 711
{
}

static void __exit zs_stat_exit(void)
{
}

712
static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
M
Minchan Kim 已提交
713 714 715 716 717 718 719 720
{
}

static inline void zs_pool_stat_destroy(struct zs_pool *pool)
{
}
#endif

M
Minchan Kim 已提交
721

N
Nitin Cupta 已提交
722 723 724 725 726 727 728
/*
 * For each size class, zspages are divided into different groups
 * depending on how "full" they are. This was done so that we could
 * easily find empty or nearly empty zspages when we try to shrink
 * the pool (not yet implemented). This function returns fullness
 * status of the given page.
 */
729
static enum fullness_group get_fullness_group(struct size_class *class,
730
						struct zspage *zspage)
731
{
732
	int inuse, objs_per_zspage;
733
	enum fullness_group fg;
M
Minchan Kim 已提交
734

735
	inuse = get_zspage_inuse(zspage);
736
	objs_per_zspage = class->objs_per_zspage;
737 738 739

	if (inuse == 0)
		fg = ZS_EMPTY;
740
	else if (inuse == objs_per_zspage)
741
		fg = ZS_FULL;
742
	else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
743 744 745 746 747 748 749
		fg = ZS_ALMOST_EMPTY;
	else
		fg = ZS_ALMOST_FULL;

	return fg;
}

N
Nitin Cupta 已提交
750 751 752 753 754 755
/*
 * Each size class maintains various freelists and zspages are assigned
 * to one of these freelists based on the number of live objects they
 * have. This functions inserts the given zspage into the freelist
 * identified by <class, fullness_group>.
 */
756
static void insert_zspage(struct size_class *class,
757 758
				struct zspage *zspage,
				enum fullness_group fullness)
759
{
760
	struct zspage *head;
761

M
Minchan Kim 已提交
762
	zs_stat_inc(class, fullness, 1);
763 764
	head = list_first_entry_or_null(&class->fullness_list[fullness],
					struct zspage, list);
765
	/*
766 767
	 * We want to see more ZS_FULL pages and less almost empty/full.
	 * Put pages with higher ->inuse first.
768
	 */
769 770 771 772 773 774 775
	if (head) {
		if (get_zspage_inuse(zspage) < get_zspage_inuse(head)) {
			list_add(&zspage->list, &head->list);
			return;
		}
	}
	list_add(&zspage->list, &class->fullness_list[fullness]);
776 777
}

N
Nitin Cupta 已提交
778 779 780 781
/*
 * This function removes the given zspage from the freelist identified
 * by <class, fullness_group>.
 */
782
static void remove_zspage(struct size_class *class,
783 784
				struct zspage *zspage,
				enum fullness_group fullness)
785
{
786
	VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
M
Minchan Kim 已提交
787
	VM_BUG_ON(is_zspage_isolated(zspage));
788

789
	list_del_init(&zspage->list);
M
Minchan Kim 已提交
790
	zs_stat_dec(class, fullness, 1);
791 792
}

N
Nitin Cupta 已提交
793 794 795 796 797 798 799 800 801
/*
 * Each size class maintains zspages in different fullness groups depending
 * on the number of live objects they contain. When allocating or freeing
 * objects, the fullness status of the page can change, say, from ALMOST_FULL
 * to ALMOST_EMPTY when freeing an object. This function checks if such
 * a status change has occurred for the given page and accordingly moves the
 * page from the freelist of the old fullness group to that of the new
 * fullness group.
 */
802
static enum fullness_group fix_fullness_group(struct size_class *class,
803
						struct zspage *zspage)
804 805 806 807
{
	int class_idx;
	enum fullness_group currfg, newfg;

808 809
	get_zspage_mapping(zspage, &class_idx, &currfg);
	newfg = get_fullness_group(class, zspage);
810 811 812
	if (newfg == currfg)
		goto out;

M
Minchan Kim 已提交
813 814 815 816 817
	if (!is_zspage_isolated(zspage)) {
		remove_zspage(class, zspage, currfg);
		insert_zspage(class, zspage, newfg);
	}

818
	set_zspage_mapping(zspage, class_idx, newfg);
819 820 821 822 823 824 825 826 827 828

out:
	return newfg;
}

/*
 * We have to decide on how many pages to link together
 * to form a zspage for each size class. This is important
 * to reduce wastage due to unusable space left at end of
 * each zspage which is given as:
829 830
 *     wastage = Zp % class_size
 *     usage = Zp - wastage
831 832 833 834 835 836
 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
 *
 * For example, for size class of 3/8 * PAGE_SIZE, we should
 * link together 3 PAGE_SIZE sized pages to form a zspage
 * since then we can perfectly fit in 8 such objects.
 */
837
static int get_pages_per_zspage(int class_size)
838 839 840 841 842
{
	int i, max_usedpc = 0;
	/* zspage order which gives maximum used size per KB */
	int max_usedpc_order = 1;

843
	for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
		int zspage_size;
		int waste, usedpc;

		zspage_size = i * PAGE_SIZE;
		waste = zspage_size % class_size;
		usedpc = (zspage_size - waste) * 100 / zspage_size;

		if (usedpc > max_usedpc) {
			max_usedpc = usedpc;
			max_usedpc_order = i;
		}
	}

	return max_usedpc_order;
}

860
static struct zspage *get_zspage(struct page *page)
861
{
M
Minchan Kim 已提交
862 863 864 865
	struct zspage *zspage = (struct zspage *)page->private;

	BUG_ON(zspage->magic != ZSPAGE_MAGIC);
	return zspage;
866 867 868 869
}

static struct page *get_next_page(struct page *page)
{
M
Minchan Kim 已提交
870 871 872 873
	if (unlikely(PageHugeObject(page)))
		return NULL;

	return page->freelist;
874 875
}

M
Minchan Kim 已提交
876 877 878 879
/**
 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
 * @page: page object resides in zspage
 * @obj_idx: object index
880
 */
M
Minchan Kim 已提交
881 882
static void obj_to_location(unsigned long obj, struct page **page,
				unsigned int *obj_idx)
883
{
M
Minchan Kim 已提交
884 885 886 887
	obj >>= OBJ_TAG_BITS;
	*page = pfn_to_page(obj >> OBJ_INDEX_BITS);
	*obj_idx = (obj & OBJ_INDEX_MASK);
}
888

M
Minchan Kim 已提交
889 890 891 892 893 894 895 896
/**
 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
 * @page: page object resides in zspage
 * @obj_idx: object index
 */
static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
{
	unsigned long obj;
897

M
Minchan Kim 已提交
898
	obj = page_to_pfn(page) << OBJ_INDEX_BITS;
M
Minchan Kim 已提交
899
	obj |= obj_idx & OBJ_INDEX_MASK;
M
Minchan Kim 已提交
900
	obj <<= OBJ_TAG_BITS;
901

M
Minchan Kim 已提交
902
	return obj;
903 904
}

905 906 907 908 909
static unsigned long handle_to_obj(unsigned long handle)
{
	return *(unsigned long *)handle;
}

M
Minchan Kim 已提交
910
static unsigned long obj_to_head(struct page *page, void *obj)
M
Minchan Kim 已提交
911
{
M
Minchan Kim 已提交
912
	if (unlikely(PageHugeObject(page))) {
M
Minchan Kim 已提交
913
		VM_BUG_ON_PAGE(!is_first_page(page), page);
914
		return page->index;
915 916
	} else
		return *(unsigned long *)obj;
M
Minchan Kim 已提交
917 918
}

M
Minchan Kim 已提交
919 920 921 922 923
static inline int testpin_tag(unsigned long handle)
{
	return bit_spin_is_locked(HANDLE_PIN_BIT, (unsigned long *)handle);
}

M
Minchan Kim 已提交
924 925
static inline int trypin_tag(unsigned long handle)
{
M
Minchan Kim 已提交
926
	return bit_spin_trylock(HANDLE_PIN_BIT, (unsigned long *)handle);
M
Minchan Kim 已提交
927 928 929 930
}

static void pin_tag(unsigned long handle)
{
M
Minchan Kim 已提交
931
	bit_spin_lock(HANDLE_PIN_BIT, (unsigned long *)handle);
M
Minchan Kim 已提交
932 933 934 935
}

static void unpin_tag(unsigned long handle)
{
M
Minchan Kim 已提交
936
	bit_spin_unlock(HANDLE_PIN_BIT, (unsigned long *)handle);
M
Minchan Kim 已提交
937 938
}

N
Nitin Gupta 已提交
939 940
static void reset_page(struct page *page)
{
M
Minchan Kim 已提交
941
	__ClearPageMovable(page);
N
Nitin Gupta 已提交
942 943 944
	clear_bit(PG_private, &page->flags);
	clear_bit(PG_private_2, &page->flags);
	set_page_private(page, 0);
M
Minchan Kim 已提交
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
	page_mapcount_reset(page);
	ClearPageHugeObject(page);
	page->freelist = NULL;
}

/*
 * To prevent zspage destroy during migration, zspage freeing should
 * hold locks of all pages in the zspage.
 */
void lock_zspage(struct zspage *zspage)
{
	struct page *page = get_first_page(zspage);

	do {
		lock_page(page);
	} while ((page = get_next_page(page)) != NULL);
}

int trylock_zspage(struct zspage *zspage)
{
	struct page *cursor, *fail;

	for (cursor = get_first_page(zspage); cursor != NULL; cursor =
					get_next_page(cursor)) {
		if (!trylock_page(cursor)) {
			fail = cursor;
			goto unlock;
		}
	}

	return 1;
unlock:
	for (cursor = get_first_page(zspage); cursor != fail; cursor =
					get_next_page(cursor))
		unlock_page(cursor);

	return 0;
N
Nitin Gupta 已提交
982 983
}

M
Minchan Kim 已提交
984 985
static void __free_zspage(struct zs_pool *pool, struct size_class *class,
				struct zspage *zspage)
986
{
987
	struct page *page, *next;
M
Minchan Kim 已提交
988 989 990 991 992 993
	enum fullness_group fg;
	unsigned int class_idx;

	get_zspage_mapping(zspage, &class_idx, &fg);

	assert_spin_locked(&class->lock);
994

995
	VM_BUG_ON(get_zspage_inuse(zspage));
M
Minchan Kim 已提交
996
	VM_BUG_ON(fg != ZS_EMPTY);
997

M
Minchan Kim 已提交
998
	next = page = get_first_page(zspage);
999
	do {
M
Minchan Kim 已提交
1000 1001
		VM_BUG_ON_PAGE(!PageLocked(page), page);
		next = get_next_page(page);
1002
		reset_page(page);
M
Minchan Kim 已提交
1003
		unlock_page(page);
M
Minchan Kim 已提交
1004
		dec_zone_page_state(page, NR_ZSPAGES);
1005 1006 1007
		put_page(page);
		page = next;
	} while (page != NULL);
1008

1009
	cache_free_zspage(pool, zspage);
M
Minchan Kim 已提交
1010

1011
	zs_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
M
Minchan Kim 已提交
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
	atomic_long_sub(class->pages_per_zspage,
					&pool->pages_allocated);
}

static void free_zspage(struct zs_pool *pool, struct size_class *class,
				struct zspage *zspage)
{
	VM_BUG_ON(get_zspage_inuse(zspage));
	VM_BUG_ON(list_empty(&zspage->list));

	if (!trylock_zspage(zspage)) {
		kick_deferred_free(pool);
		return;
	}

	remove_zspage(class, zspage, ZS_EMPTY);
	__free_zspage(pool, class, zspage);
1029 1030 1031
}

/* Initialize a newly allocated zspage */
1032
static void init_zspage(struct size_class *class, struct zspage *zspage)
1033
{
M
Minchan Kim 已提交
1034
	unsigned int freeobj = 1;
1035
	unsigned long off = 0;
M
Minchan Kim 已提交
1036
	struct page *page = get_first_page(zspage);
M
Minchan Kim 已提交
1037

1038 1039 1040
	while (page) {
		struct page *next_page;
		struct link_free *link;
1041
		void *vaddr;
1042

1043
		set_first_obj_offset(page, off);
1044

1045 1046
		vaddr = kmap_atomic(page);
		link = (struct link_free *)vaddr + off / sizeof(*link);
1047 1048

		while ((off += class->size) < PAGE_SIZE) {
1049
			link->next = freeobj++ << OBJ_TAG_BITS;
1050
			link += class->size / sizeof(*link);
1051 1052 1053 1054 1055 1056 1057 1058
		}

		/*
		 * We now come to the last (full or partial) object on this
		 * page, which must point to the first object on the next
		 * page (if present)
		 */
		next_page = get_next_page(page);
M
Minchan Kim 已提交
1059
		if (next_page) {
1060
			link->next = freeobj++ << OBJ_TAG_BITS;
M
Minchan Kim 已提交
1061 1062
		} else {
			/*
1063
			 * Reset OBJ_TAG_BITS bit to last link to tell
M
Minchan Kim 已提交
1064 1065
			 * whether it's allocated object or not.
			 */
1066
			link->next = -1 << OBJ_TAG_BITS;
M
Minchan Kim 已提交
1067
		}
1068
		kunmap_atomic(vaddr);
1069
		page = next_page;
1070
		off %= PAGE_SIZE;
1071
	}
1072

M
Minchan Kim 已提交
1073
	set_freeobj(zspage, 0);
1074 1075
}

M
Minchan Kim 已提交
1076 1077
static void create_page_chain(struct size_class *class, struct zspage *zspage,
				struct page *pages[])
1078
{
1079 1080 1081
	int i;
	struct page *page;
	struct page *prev_page = NULL;
M
Minchan Kim 已提交
1082
	int nr_pages = class->pages_per_zspage;
1083 1084 1085

	/*
	 * Allocate individual pages and link them together as:
M
Minchan Kim 已提交
1086
	 * 1. all pages are linked together using page->freelist
1087
	 * 2. each sub-page point to zspage using page->private
1088
	 *
1089 1090
	 * we set PG_private to identify the first page (i.e. no other sub-page
	 * has this flag set) and PG_private_2 to identify the last page.
1091
	 */
1092 1093
	for (i = 0; i < nr_pages; i++) {
		page = pages[i];
1094
		set_page_private(page, (unsigned long)zspage);
M
Minchan Kim 已提交
1095
		page->freelist = NULL;
1096
		if (i == 0) {
1097
			zspage->first_page = page;
1098
			SetPagePrivate(page);
M
Minchan Kim 已提交
1099 1100 1101
			if (unlikely(class->objs_per_zspage == 1 &&
					class->pages_per_zspage == 1))
				SetPageHugeObject(page);
1102
		} else {
M
Minchan Kim 已提交
1103
			prev_page->freelist = page;
1104
		}
M
Minchan Kim 已提交
1105
		if (i == nr_pages - 1)
1106
			SetPagePrivate2(page);
1107 1108
		prev_page = page;
	}
1109
}
1110

1111 1112 1113
/*
 * Allocate a zspage for the given size class
 */
1114 1115 1116
static struct zspage *alloc_zspage(struct zs_pool *pool,
					struct size_class *class,
					gfp_t gfp)
1117 1118 1119
{
	int i;
	struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1120 1121 1122 1123 1124 1125
	struct zspage *zspage = cache_alloc_zspage(pool, gfp);

	if (!zspage)
		return NULL;

	memset(zspage, 0, sizeof(struct zspage));
M
Minchan Kim 已提交
1126 1127
	zspage->magic = ZSPAGE_MAGIC;
	migrate_lock_init(zspage);
1128

1129 1130
	for (i = 0; i < class->pages_per_zspage; i++) {
		struct page *page;
1131

1132
		page = alloc_page(gfp);
1133
		if (!page) {
M
Minchan Kim 已提交
1134 1135
			while (--i >= 0) {
				dec_zone_page_state(pages[i], NR_ZSPAGES);
1136
				__free_page(pages[i]);
M
Minchan Kim 已提交
1137
			}
1138
			cache_free_zspage(pool, zspage);
1139 1140
			return NULL;
		}
M
Minchan Kim 已提交
1141 1142

		inc_zone_page_state(page, NR_ZSPAGES);
1143
		pages[i] = page;
1144 1145
	}

M
Minchan Kim 已提交
1146
	create_page_chain(class, zspage, pages);
1147
	init_zspage(class, zspage);
1148

1149
	return zspage;
1150 1151
}

1152
static struct zspage *find_get_zspage(struct size_class *class)
1153 1154
{
	int i;
1155
	struct zspage *zspage;
1156

M
Minchan Kim 已提交
1157
	for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1158 1159 1160
		zspage = list_first_entry_or_null(&class->fullness_list[i],
				struct zspage, list);
		if (zspage)
1161 1162 1163
			break;
	}

1164
	return zspage;
1165 1166
}

1167
#ifdef CONFIG_PGTABLE_MAPPING
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
static inline int __zs_cpu_up(struct mapping_area *area)
{
	/*
	 * Make sure we don't leak memory if a cpu UP notification
	 * and zs_init() race and both call zs_cpu_up() on the same cpu
	 */
	if (area->vm)
		return 0;
	area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
	if (!area->vm)
		return -ENOMEM;
	return 0;
}

static inline void __zs_cpu_down(struct mapping_area *area)
{
	if (area->vm)
		free_vm_area(area->vm);
	area->vm = NULL;
}

static inline void *__zs_map_object(struct mapping_area *area,
				struct page *pages[2], int off, int size)
{
1192
	BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1193 1194 1195 1196 1197 1198 1199 1200 1201
	area->vm_addr = area->vm->addr;
	return area->vm_addr + off;
}

static inline void __zs_unmap_object(struct mapping_area *area,
				struct page *pages[2], int off, int size)
{
	unsigned long addr = (unsigned long)area->vm_addr;

1202
	unmap_kernel_range(addr, PAGE_SIZE * 2);
1203 1204
}

1205
#else /* CONFIG_PGTABLE_MAPPING */
1206 1207 1208 1209 1210 1211 1212 1213 1214

static inline int __zs_cpu_up(struct mapping_area *area)
{
	/*
	 * Make sure we don't leak memory if a cpu UP notification
	 * and zs_init() race and both call zs_cpu_up() on the same cpu
	 */
	if (area->vm_buf)
		return 0;
1215
	area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1216 1217 1218 1219 1220 1221 1222
	if (!area->vm_buf)
		return -ENOMEM;
	return 0;
}

static inline void __zs_cpu_down(struct mapping_area *area)
{
1223
	kfree(area->vm_buf);
1224 1225 1226 1227 1228
	area->vm_buf = NULL;
}

static void *__zs_map_object(struct mapping_area *area,
			struct page *pages[2], int off, int size)
1229 1230 1231
{
	int sizes[2];
	void *addr;
1232
	char *buf = area->vm_buf;
1233

1234 1235 1236 1237 1238 1239
	/* disable page faults to match kmap_atomic() return conditions */
	pagefault_disable();

	/* no read fastpath */
	if (area->vm_mm == ZS_MM_WO)
		goto out;
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

	sizes[0] = PAGE_SIZE - off;
	sizes[1] = size - sizes[0];

	/* copy object to per-cpu buffer */
	addr = kmap_atomic(pages[0]);
	memcpy(buf, addr + off, sizes[0]);
	kunmap_atomic(addr);
	addr = kmap_atomic(pages[1]);
	memcpy(buf + sizes[0], addr, sizes[1]);
	kunmap_atomic(addr);
1251 1252
out:
	return area->vm_buf;
1253 1254
}

1255 1256
static void __zs_unmap_object(struct mapping_area *area,
			struct page *pages[2], int off, int size)
1257 1258 1259
{
	int sizes[2];
	void *addr;
1260
	char *buf;
1261

1262 1263 1264
	/* no write fastpath */
	if (area->vm_mm == ZS_MM_RO)
		goto out;
1265

1266
	buf = area->vm_buf;
1267 1268 1269
	buf = buf + ZS_HANDLE_SIZE;
	size -= ZS_HANDLE_SIZE;
	off += ZS_HANDLE_SIZE;
1270

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
	sizes[0] = PAGE_SIZE - off;
	sizes[1] = size - sizes[0];

	/* copy per-cpu buffer to object */
	addr = kmap_atomic(pages[0]);
	memcpy(addr + off, buf, sizes[0]);
	kunmap_atomic(addr);
	addr = kmap_atomic(pages[1]);
	memcpy(addr, buf + sizes[0], sizes[1]);
	kunmap_atomic(addr);
1281 1282 1283 1284

out:
	/* enable page faults to match kunmap_atomic() return conditions */
	pagefault_enable();
1285
}
1286

1287
#endif /* CONFIG_PGTABLE_MAPPING */
1288

1289 1290 1291
static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
				void *pcpu)
{
1292
	int ret, cpu = (long)pcpu;
1293 1294 1295 1296 1297
	struct mapping_area *area;

	switch (action) {
	case CPU_UP_PREPARE:
		area = &per_cpu(zs_map_area, cpu);
1298 1299 1300
		ret = __zs_cpu_up(area);
		if (ret)
			return notifier_from_errno(ret);
1301 1302 1303 1304
		break;
	case CPU_DEAD:
	case CPU_UP_CANCELED:
		area = &per_cpu(zs_map_area, cpu);
1305
		__zs_cpu_down(area);
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
		break;
	}

	return NOTIFY_OK;
}

static struct notifier_block zs_cpu_nb = {
	.notifier_call = zs_cpu_notifier
};

1316
static int zs_register_cpu_notifier(void)
1317
{
1318
	int cpu, uninitialized_var(ret);
1319

1320 1321 1322
	cpu_notifier_register_begin();

	__register_cpu_notifier(&zs_cpu_nb);
1323 1324
	for_each_online_cpu(cpu) {
		ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
1325 1326
		if (notifier_to_errno(ret))
			break;
1327
	}
1328 1329

	cpu_notifier_register_done();
1330 1331
	return notifier_to_errno(ret);
}
1332

1333
static void zs_unregister_cpu_notifier(void)
1334
{
1335
	int cpu;
1336

1337
	cpu_notifier_register_begin();
1338

1339 1340 1341
	for_each_online_cpu(cpu)
		zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
	__unregister_cpu_notifier(&zs_cpu_nb);
1342

1343
	cpu_notifier_register_done();
1344 1345
}

1346
static void init_zs_size_classes(void)
1347
{
1348
	int nr;
1349

1350 1351 1352
	nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
	if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
		nr += 1;
1353

1354
	zs_size_classes = nr;
1355 1356
}

1357 1358
static bool can_merge(struct size_class *prev, int pages_per_zspage,
					int objs_per_zspage)
1359
{
1360 1361 1362
	if (prev->pages_per_zspage == pages_per_zspage &&
		prev->objs_per_zspage == objs_per_zspage)
		return true;
1363

1364
	return false;
1365 1366
}

1367
static bool zspage_full(struct size_class *class, struct zspage *zspage)
M
Minchan Kim 已提交
1368
{
1369
	return get_zspage_inuse(zspage) == class->objs_per_zspage;
M
Minchan Kim 已提交
1370 1371
}

1372 1373 1374 1375 1376 1377
unsigned long zs_get_total_pages(struct zs_pool *pool)
{
	return atomic_long_read(&pool->pages_allocated);
}
EXPORT_SYMBOL_GPL(zs_get_total_pages);

1378
/**
1379 1380 1381
 * zs_map_object - get address of allocated object from handle.
 * @pool: pool from which the object was allocated
 * @handle: handle returned from zs_malloc
1382
 *
1383 1384 1385
 * Before using an object allocated from zs_malloc, it must be mapped using
 * this function. When done with the object, it must be unmapped using
 * zs_unmap_object.
1386
 *
1387 1388 1389 1390
 * Only one object can be mapped per cpu at a time. There is no protection
 * against nested mappings.
 *
 * This function returns with preemption and page faults disabled.
1391
 */
1392 1393
void *zs_map_object(struct zs_pool *pool, unsigned long handle,
			enum zs_mapmode mm)
1394
{
1395
	struct zspage *zspage;
1396
	struct page *page;
M
Minchan Kim 已提交
1397 1398
	unsigned long obj, off;
	unsigned int obj_idx;
1399

1400 1401 1402 1403 1404
	unsigned int class_idx;
	enum fullness_group fg;
	struct size_class *class;
	struct mapping_area *area;
	struct page *pages[2];
1405
	void *ret;
1406

1407
	/*
1408 1409 1410
	 * Because we use per-cpu mapping areas shared among the
	 * pools/users, we can't allow mapping in interrupt context
	 * because it can corrupt another users mappings.
1411
	 */
M
Minchan Kim 已提交
1412
	WARN_ON_ONCE(in_interrupt());
1413

M
Minchan Kim 已提交
1414 1415 1416
	/* From now on, migration cannot move the object */
	pin_tag(handle);

1417 1418
	obj = handle_to_obj(handle);
	obj_to_location(obj, &page, &obj_idx);
1419
	zspage = get_zspage(page);
M
Minchan Kim 已提交
1420 1421 1422 1423

	/* migration cannot move any subpage in this zspage */
	migrate_read_lock(zspage);

1424
	get_zspage_mapping(zspage, &class_idx, &fg);
1425
	class = pool->size_class[class_idx];
M
Minchan Kim 已提交
1426
	off = (class->size * obj_idx) & ~PAGE_MASK;
1427

1428 1429 1430 1431 1432
	area = &get_cpu_var(zs_map_area);
	area->vm_mm = mm;
	if (off + class->size <= PAGE_SIZE) {
		/* this object is contained entirely within a page */
		area->vm_addr = kmap_atomic(page);
1433 1434
		ret = area->vm_addr + off;
		goto out;
1435 1436
	}

1437 1438 1439 1440
	/* this object spans two pages */
	pages[0] = page;
	pages[1] = get_next_page(page);
	BUG_ON(!pages[1]);
1441

1442 1443
	ret = __zs_map_object(area, pages, off, class->size);
out:
M
Minchan Kim 已提交
1444
	if (likely(!PageHugeObject(page)))
1445 1446 1447
		ret += ZS_HANDLE_SIZE;

	return ret;
1448
}
1449
EXPORT_SYMBOL_GPL(zs_map_object);
1450

1451
void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1452
{
1453
	struct zspage *zspage;
1454
	struct page *page;
M
Minchan Kim 已提交
1455 1456
	unsigned long obj, off;
	unsigned int obj_idx;
1457

1458 1459 1460 1461
	unsigned int class_idx;
	enum fullness_group fg;
	struct size_class *class;
	struct mapping_area *area;
1462

1463 1464
	obj = handle_to_obj(handle);
	obj_to_location(obj, &page, &obj_idx);
1465 1466
	zspage = get_zspage(page);
	get_zspage_mapping(zspage, &class_idx, &fg);
1467
	class = pool->size_class[class_idx];
M
Minchan Kim 已提交
1468
	off = (class->size * obj_idx) & ~PAGE_MASK;
1469

1470 1471 1472 1473 1474
	area = this_cpu_ptr(&zs_map_area);
	if (off + class->size <= PAGE_SIZE)
		kunmap_atomic(area->vm_addr);
	else {
		struct page *pages[2];
1475

1476 1477 1478 1479 1480 1481 1482
		pages[0] = page;
		pages[1] = get_next_page(page);
		BUG_ON(!pages[1]);

		__zs_unmap_object(area, pages, off, class->size);
	}
	put_cpu_var(zs_map_area);
M
Minchan Kim 已提交
1483 1484

	migrate_read_unlock(zspage);
M
Minchan Kim 已提交
1485
	unpin_tag(handle);
1486
}
1487
EXPORT_SYMBOL_GPL(zs_unmap_object);
1488

1489
static unsigned long obj_malloc(struct size_class *class,
1490
				struct zspage *zspage, unsigned long handle)
1491
{
M
Minchan Kim 已提交
1492
	int i, nr_page, offset;
1493 1494 1495 1496
	unsigned long obj;
	struct link_free *link;

	struct page *m_page;
M
Minchan Kim 已提交
1497
	unsigned long m_offset;
1498 1499
	void *vaddr;

M
Minchan Kim 已提交
1500
	handle |= OBJ_ALLOCATED_TAG;
1501
	obj = get_freeobj(zspage);
M
Minchan Kim 已提交
1502 1503 1504 1505 1506 1507 1508 1509

	offset = obj * class->size;
	nr_page = offset >> PAGE_SHIFT;
	m_offset = offset & ~PAGE_MASK;
	m_page = get_first_page(zspage);

	for (i = 0; i < nr_page; i++)
		m_page = get_next_page(m_page);
1510 1511 1512

	vaddr = kmap_atomic(m_page);
	link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1513
	set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
M
Minchan Kim 已提交
1514
	if (likely(!PageHugeObject(m_page)))
1515 1516 1517
		/* record handle in the header of allocated chunk */
		link->handle = handle;
	else
1518 1519 1520
		/* record handle to page->index */
		zspage->first_page->index = handle;

1521
	kunmap_atomic(vaddr);
1522
	mod_zspage_inuse(zspage, 1);
1523 1524
	zs_stat_inc(class, OBJ_USED, 1);

M
Minchan Kim 已提交
1525 1526
	obj = location_to_obj(m_page, obj);

1527 1528 1529 1530
	return obj;
}


1531 1532 1533 1534 1535
/**
 * zs_malloc - Allocate block of given size from pool.
 * @pool: pool to allocate from
 * @size: size of block to allocate
 *
1536
 * On success, handle to the allocated object is returned,
1537
 * otherwise 0.
1538 1539
 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
 */
1540
unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1541
{
1542
	unsigned long handle, obj;
1543
	struct size_class *class;
M
Minchan Kim 已提交
1544
	enum fullness_group newfg;
1545
	struct zspage *zspage;
1546

1547
	if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1548 1549
		return 0;

1550
	handle = cache_alloc_handle(pool, gfp);
1551
	if (!handle)
1552
		return 0;
1553

1554 1555
	/* extra space in chunk to keep the handle */
	size += ZS_HANDLE_SIZE;
1556
	class = pool->size_class[get_size_class_index(size)];
1557 1558

	spin_lock(&class->lock);
1559
	zspage = find_get_zspage(class);
M
Minchan Kim 已提交
1560 1561 1562 1563 1564
	if (likely(zspage)) {
		obj = obj_malloc(class, zspage, handle);
		/* Now move the zspage to another fullness group, if required */
		fix_fullness_group(class, zspage);
		record_obj(handle, obj);
1565 1566
		spin_unlock(&class->lock);

M
Minchan Kim 已提交
1567 1568
		return handle;
	}
1569

M
Minchan Kim 已提交
1570 1571 1572 1573 1574 1575
	spin_unlock(&class->lock);

	zspage = alloc_zspage(pool, class, gfp);
	if (!zspage) {
		cache_free_handle(pool, handle);
		return 0;
1576 1577
	}

M
Minchan Kim 已提交
1578
	spin_lock(&class->lock);
1579
	obj = obj_malloc(class, zspage, handle);
M
Minchan Kim 已提交
1580 1581 1582
	newfg = get_fullness_group(class, zspage);
	insert_zspage(class, zspage, newfg);
	set_zspage_mapping(zspage, class->index, newfg);
1583
	record_obj(handle, obj);
M
Minchan Kim 已提交
1584 1585
	atomic_long_add(class->pages_per_zspage,
				&pool->pages_allocated);
1586
	zs_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
M
Minchan Kim 已提交
1587 1588 1589

	/* We completely set up zspage so mark them as movable */
	SetZsPageMovable(pool, zspage);
1590 1591
	spin_unlock(&class->lock);

1592
	return handle;
1593 1594 1595
}
EXPORT_SYMBOL_GPL(zs_malloc);

1596
static void obj_free(struct size_class *class, unsigned long obj)
1597 1598
{
	struct link_free *link;
1599 1600
	struct zspage *zspage;
	struct page *f_page;
M
Minchan Kim 已提交
1601 1602
	unsigned long f_offset;
	unsigned int f_objidx;
1603
	void *vaddr;
1604

M
Minchan Kim 已提交
1605
	obj &= ~OBJ_ALLOCATED_TAG;
1606
	obj_to_location(obj, &f_page, &f_objidx);
M
Minchan Kim 已提交
1607
	f_offset = (class->size * f_objidx) & ~PAGE_MASK;
1608
	zspage = get_zspage(f_page);
1609

1610
	vaddr = kmap_atomic(f_page);
1611 1612

	/* Insert this object in containing zspage's freelist */
1613
	link = (struct link_free *)(vaddr + f_offset);
1614
	link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1615
	kunmap_atomic(vaddr);
M
Minchan Kim 已提交
1616
	set_freeobj(zspage, f_objidx);
1617
	mod_zspage_inuse(zspage, -1);
1618
	zs_stat_dec(class, OBJ_USED, 1);
1619 1620 1621 1622
}

void zs_free(struct zs_pool *pool, unsigned long handle)
{
1623 1624
	struct zspage *zspage;
	struct page *f_page;
M
Minchan Kim 已提交
1625 1626
	unsigned long obj;
	unsigned int f_objidx;
1627 1628 1629
	int class_idx;
	struct size_class *class;
	enum fullness_group fullness;
M
Minchan Kim 已提交
1630
	bool isolated;
1631 1632 1633 1634

	if (unlikely(!handle))
		return;

M
Minchan Kim 已提交
1635
	pin_tag(handle);
1636 1637
	obj = handle_to_obj(handle);
	obj_to_location(obj, &f_page, &f_objidx);
1638
	zspage = get_zspage(f_page);
1639

M
Minchan Kim 已提交
1640 1641
	migrate_read_lock(zspage);

1642
	get_zspage_mapping(zspage, &class_idx, &fullness);
1643 1644 1645
	class = pool->size_class[class_idx];

	spin_lock(&class->lock);
1646
	obj_free(class, obj);
1647
	fullness = fix_fullness_group(class, zspage);
M
Minchan Kim 已提交
1648 1649 1650
	if (fullness != ZS_EMPTY) {
		migrate_read_unlock(zspage);
		goto out;
M
Minchan Kim 已提交
1651
	}
M
Minchan Kim 已提交
1652 1653 1654 1655 1656 1657 1658 1659

	isolated = is_zspage_isolated(zspage);
	migrate_read_unlock(zspage);
	/* If zspage is isolated, zs_page_putback will free the zspage */
	if (likely(!isolated))
		free_zspage(pool, class, zspage);
out:

1660
	spin_unlock(&class->lock);
M
Minchan Kim 已提交
1661
	unpin_tag(handle);
1662
	cache_free_handle(pool, handle);
M
Minchan Kim 已提交
1663 1664 1665
}
EXPORT_SYMBOL_GPL(zs_free);

1666 1667
static void zs_object_copy(struct size_class *class, unsigned long dst,
				unsigned long src)
M
Minchan Kim 已提交
1668 1669
{
	struct page *s_page, *d_page;
M
Minchan Kim 已提交
1670
	unsigned int s_objidx, d_objidx;
M
Minchan Kim 已提交
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
	unsigned long s_off, d_off;
	void *s_addr, *d_addr;
	int s_size, d_size, size;
	int written = 0;

	s_size = d_size = class->size;

	obj_to_location(src, &s_page, &s_objidx);
	obj_to_location(dst, &d_page, &d_objidx);

M
Minchan Kim 已提交
1681 1682
	s_off = (class->size * s_objidx) & ~PAGE_MASK;
	d_off = (class->size * d_objidx) & ~PAGE_MASK;
M
Minchan Kim 已提交
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700

	if (s_off + class->size > PAGE_SIZE)
		s_size = PAGE_SIZE - s_off;

	if (d_off + class->size > PAGE_SIZE)
		d_size = PAGE_SIZE - d_off;

	s_addr = kmap_atomic(s_page);
	d_addr = kmap_atomic(d_page);

	while (1) {
		size = min(s_size, d_size);
		memcpy(d_addr + d_off, s_addr + s_off, size);
		written += size;

		if (written == class->size)
			break;

1701 1702 1703 1704 1705 1706
		s_off += size;
		s_size -= size;
		d_off += size;
		d_size -= size;

		if (s_off >= PAGE_SIZE) {
M
Minchan Kim 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715
			kunmap_atomic(d_addr);
			kunmap_atomic(s_addr);
			s_page = get_next_page(s_page);
			s_addr = kmap_atomic(s_page);
			d_addr = kmap_atomic(d_page);
			s_size = class->size - written;
			s_off = 0;
		}

1716
		if (d_off >= PAGE_SIZE) {
M
Minchan Kim 已提交
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
			kunmap_atomic(d_addr);
			d_page = get_next_page(d_page);
			d_addr = kmap_atomic(d_page);
			d_size = class->size - written;
			d_off = 0;
		}
	}

	kunmap_atomic(d_addr);
	kunmap_atomic(s_addr);
}

/*
 * Find alloced object in zspage from index object and
 * return handle.
 */
1733
static unsigned long find_alloced_obj(struct size_class *class,
1734
					struct page *page, int *obj_idx)
M
Minchan Kim 已提交
1735 1736 1737
{
	unsigned long head;
	int offset = 0;
1738
	int index = *obj_idx;
M
Minchan Kim 已提交
1739 1740 1741
	unsigned long handle = 0;
	void *addr = kmap_atomic(page);

1742
	offset = get_first_obj_offset(page);
M
Minchan Kim 已提交
1743 1744 1745
	offset += class->size * index;

	while (offset < PAGE_SIZE) {
M
Minchan Kim 已提交
1746
		head = obj_to_head(page, addr + offset);
M
Minchan Kim 已提交
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
		if (head & OBJ_ALLOCATED_TAG) {
			handle = head & ~OBJ_ALLOCATED_TAG;
			if (trypin_tag(handle))
				break;
			handle = 0;
		}

		offset += class->size;
		index++;
	}

	kunmap_atomic(addr);
1759 1760 1761

	*obj_idx = index;

M
Minchan Kim 已提交
1762 1763 1764 1765
	return handle;
}

struct zs_compact_control {
1766
	/* Source spage for migration which could be a subpage of zspage */
M
Minchan Kim 已提交
1767 1768 1769 1770 1771 1772
	struct page *s_page;
	/* Destination page for migration which should be a first page
	 * of zspage. */
	struct page *d_page;
	 /* Starting object index within @s_page which used for live object
	  * in the subpage. */
1773
	int obj_idx;
M
Minchan Kim 已提交
1774 1775 1776 1777 1778 1779 1780 1781 1782
};

static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
				struct zs_compact_control *cc)
{
	unsigned long used_obj, free_obj;
	unsigned long handle;
	struct page *s_page = cc->s_page;
	struct page *d_page = cc->d_page;
1783
	int obj_idx = cc->obj_idx;
M
Minchan Kim 已提交
1784 1785 1786
	int ret = 0;

	while (1) {
1787
		handle = find_alloced_obj(class, s_page, &obj_idx);
M
Minchan Kim 已提交
1788 1789 1790 1791
		if (!handle) {
			s_page = get_next_page(s_page);
			if (!s_page)
				break;
1792
			obj_idx = 0;
M
Minchan Kim 已提交
1793 1794 1795 1796
			continue;
		}

		/* Stop if there is no more space */
1797
		if (zspage_full(class, get_zspage(d_page))) {
M
Minchan Kim 已提交
1798 1799 1800 1801 1802 1803
			unpin_tag(handle);
			ret = -ENOMEM;
			break;
		}

		used_obj = handle_to_obj(handle);
1804
		free_obj = obj_malloc(class, get_zspage(d_page), handle);
1805
		zs_object_copy(class, free_obj, used_obj);
1806
		obj_idx++;
1807 1808 1809 1810 1811 1812 1813
		/*
		 * record_obj updates handle's value to free_obj and it will
		 * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
		 * breaks synchronization using pin_tag(e,g, zs_free) so
		 * let's keep the lock bit.
		 */
		free_obj |= BIT(HANDLE_PIN_BIT);
M
Minchan Kim 已提交
1814 1815
		record_obj(handle, free_obj);
		unpin_tag(handle);
1816
		obj_free(class, used_obj);
M
Minchan Kim 已提交
1817 1818 1819 1820
	}

	/* Remember last position in this iteration */
	cc->s_page = s_page;
1821
	cc->obj_idx = obj_idx;
M
Minchan Kim 已提交
1822 1823 1824 1825

	return ret;
}

1826
static struct zspage *isolate_zspage(struct size_class *class, bool source)
M
Minchan Kim 已提交
1827 1828
{
	int i;
1829 1830
	struct zspage *zspage;
	enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
M
Minchan Kim 已提交
1831

1832 1833 1834 1835 1836 1837 1838 1839 1840
	if (!source) {
		fg[0] = ZS_ALMOST_FULL;
		fg[1] = ZS_ALMOST_EMPTY;
	}

	for (i = 0; i < 2; i++) {
		zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
							struct zspage, list);
		if (zspage) {
M
Minchan Kim 已提交
1841
			VM_BUG_ON(is_zspage_isolated(zspage));
1842 1843
			remove_zspage(class, zspage, fg[i]);
			return zspage;
M
Minchan Kim 已提交
1844 1845 1846
		}
	}

1847
	return zspage;
M
Minchan Kim 已提交
1848 1849
}

1850
/*
1851
 * putback_zspage - add @zspage into right class's fullness list
1852
 * @class: destination class
1853
 * @zspage: target page
1854
 *
1855
 * Return @zspage's fullness_group
1856
 */
1857
static enum fullness_group putback_zspage(struct size_class *class,
1858
			struct zspage *zspage)
M
Minchan Kim 已提交
1859 1860 1861
{
	enum fullness_group fullness;

M
Minchan Kim 已提交
1862 1863
	VM_BUG_ON(is_zspage_isolated(zspage));

1864 1865 1866
	fullness = get_fullness_group(class, zspage);
	insert_zspage(class, zspage, fullness);
	set_zspage_mapping(zspage, class->index, fullness);
1867

1868
	return fullness;
1869
}
M
Minchan Kim 已提交
1870

M
Minchan Kim 已提交
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
#ifdef CONFIG_COMPACTION
static struct dentry *zs_mount(struct file_system_type *fs_type,
				int flags, const char *dev_name, void *data)
{
	static const struct dentry_operations ops = {
		.d_dname = simple_dname,
	};

	return mount_pseudo(fs_type, "zsmalloc:", NULL, &ops, ZSMALLOC_MAGIC);
}

static struct file_system_type zsmalloc_fs = {
	.name		= "zsmalloc",
	.mount		= zs_mount,
	.kill_sb	= kill_anon_super,
};

static int zsmalloc_mount(void)
{
	int ret = 0;

	zsmalloc_mnt = kern_mount(&zsmalloc_fs);
	if (IS_ERR(zsmalloc_mnt))
		ret = PTR_ERR(zsmalloc_mnt);

	return ret;
}

static void zsmalloc_unmount(void)
{
	kern_unmount(zsmalloc_mnt);
}

static void migrate_lock_init(struct zspage *zspage)
{
	rwlock_init(&zspage->lock);
}

static void migrate_read_lock(struct zspage *zspage)
{
	read_lock(&zspage->lock);
}

static void migrate_read_unlock(struct zspage *zspage)
{
	read_unlock(&zspage->lock);
}

static void migrate_write_lock(struct zspage *zspage)
{
	write_lock(&zspage->lock);
}

static void migrate_write_unlock(struct zspage *zspage)
{
	write_unlock(&zspage->lock);
}

/* Number of isolated subpage for *page migration* in this zspage */
static void inc_zspage_isolation(struct zspage *zspage)
{
	zspage->isolated++;
}

static void dec_zspage_isolation(struct zspage *zspage)
{
	zspage->isolated--;
}

static void replace_sub_page(struct size_class *class, struct zspage *zspage,
				struct page *newpage, struct page *oldpage)
{
	struct page *page;
	struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
	int idx = 0;

	page = get_first_page(zspage);
	do {
		if (page == oldpage)
			pages[idx] = newpage;
		else
			pages[idx] = page;
		idx++;
	} while ((page = get_next_page(page)) != NULL);

	create_page_chain(class, zspage, pages);
	set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
	if (unlikely(PageHugeObject(oldpage)))
		newpage->index = oldpage->index;
	__SetPageMovable(newpage, page_mapping(oldpage));
}

bool zs_page_isolate(struct page *page, isolate_mode_t mode)
{
	struct zs_pool *pool;
	struct size_class *class;
	int class_idx;
	enum fullness_group fullness;
	struct zspage *zspage;
	struct address_space *mapping;

	/*
	 * Page is locked so zspage couldn't be destroyed. For detail, look at
	 * lock_zspage in free_zspage.
	 */
	VM_BUG_ON_PAGE(!PageMovable(page), page);
	VM_BUG_ON_PAGE(PageIsolated(page), page);

	zspage = get_zspage(page);

	/*
	 * Without class lock, fullness could be stale while class_idx is okay
	 * because class_idx is constant unless page is freed so we should get
	 * fullness again under class lock.
	 */
	get_zspage_mapping(zspage, &class_idx, &fullness);
	mapping = page_mapping(page);
	pool = mapping->private_data;
	class = pool->size_class[class_idx];

	spin_lock(&class->lock);
	if (get_zspage_inuse(zspage) == 0) {
		spin_unlock(&class->lock);
		return false;
	}

	/* zspage is isolated for object migration */
	if (list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
		spin_unlock(&class->lock);
		return false;
	}

	/*
	 * If this is first time isolation for the zspage, isolate zspage from
	 * size_class to prevent further object allocation from the zspage.
	 */
	if (!list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
		get_zspage_mapping(zspage, &class_idx, &fullness);
		remove_zspage(class, zspage, fullness);
	}

	inc_zspage_isolation(zspage);
	spin_unlock(&class->lock);

	return true;
}

int zs_page_migrate(struct address_space *mapping, struct page *newpage,
		struct page *page, enum migrate_mode mode)
{
	struct zs_pool *pool;
	struct size_class *class;
	int class_idx;
	enum fullness_group fullness;
	struct zspage *zspage;
	struct page *dummy;
	void *s_addr, *d_addr, *addr;
	int offset, pos;
	unsigned long handle, head;
	unsigned long old_obj, new_obj;
	unsigned int obj_idx;
	int ret = -EAGAIN;

	VM_BUG_ON_PAGE(!PageMovable(page), page);
	VM_BUG_ON_PAGE(!PageIsolated(page), page);

	zspage = get_zspage(page);

	/* Concurrent compactor cannot migrate any subpage in zspage */
	migrate_write_lock(zspage);
	get_zspage_mapping(zspage, &class_idx, &fullness);
	pool = mapping->private_data;
	class = pool->size_class[class_idx];
	offset = get_first_obj_offset(page);

	spin_lock(&class->lock);
	if (!get_zspage_inuse(zspage)) {
		ret = -EBUSY;
		goto unlock_class;
	}

	pos = offset;
	s_addr = kmap_atomic(page);
	while (pos < PAGE_SIZE) {
		head = obj_to_head(page, s_addr + pos);
		if (head & OBJ_ALLOCATED_TAG) {
			handle = head & ~OBJ_ALLOCATED_TAG;
			if (!trypin_tag(handle))
				goto unpin_objects;
		}
		pos += class->size;
	}

	/*
	 * Here, any user cannot access all objects in the zspage so let's move.
	 */
	d_addr = kmap_atomic(newpage);
	memcpy(d_addr, s_addr, PAGE_SIZE);
	kunmap_atomic(d_addr);

	for (addr = s_addr + offset; addr < s_addr + pos;
					addr += class->size) {
		head = obj_to_head(page, addr);
		if (head & OBJ_ALLOCATED_TAG) {
			handle = head & ~OBJ_ALLOCATED_TAG;
			if (!testpin_tag(handle))
				BUG();

			old_obj = handle_to_obj(handle);
			obj_to_location(old_obj, &dummy, &obj_idx);
			new_obj = (unsigned long)location_to_obj(newpage,
								obj_idx);
			new_obj |= BIT(HANDLE_PIN_BIT);
			record_obj(handle, new_obj);
		}
	}

	replace_sub_page(class, zspage, newpage, page);
	get_page(newpage);

	dec_zspage_isolation(zspage);

	/*
	 * Page migration is done so let's putback isolated zspage to
	 * the list if @page is final isolated subpage in the zspage.
	 */
	if (!is_zspage_isolated(zspage))
		putback_zspage(class, zspage);

	reset_page(page);
	put_page(page);
	page = newpage;

2104
	ret = MIGRATEPAGE_SUCCESS;
M
Minchan Kim 已提交
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
unpin_objects:
	for (addr = s_addr + offset; addr < s_addr + pos;
						addr += class->size) {
		head = obj_to_head(page, addr);
		if (head & OBJ_ALLOCATED_TAG) {
			handle = head & ~OBJ_ALLOCATED_TAG;
			if (!testpin_tag(handle))
				BUG();
			unpin_tag(handle);
		}
	}
	kunmap_atomic(s_addr);
unlock_class:
	spin_unlock(&class->lock);
	migrate_write_unlock(zspage);

	return ret;
}

void zs_page_putback(struct page *page)
{
	struct zs_pool *pool;
	struct size_class *class;
	int class_idx;
	enum fullness_group fg;
	struct address_space *mapping;
	struct zspage *zspage;

	VM_BUG_ON_PAGE(!PageMovable(page), page);
	VM_BUG_ON_PAGE(!PageIsolated(page), page);

	zspage = get_zspage(page);
	get_zspage_mapping(zspage, &class_idx, &fg);
	mapping = page_mapping(page);
	pool = mapping->private_data;
	class = pool->size_class[class_idx];

	spin_lock(&class->lock);
	dec_zspage_isolation(zspage);
	if (!is_zspage_isolated(zspage)) {
		fg = putback_zspage(class, zspage);
		/*
		 * Due to page_lock, we cannot free zspage immediately
		 * so let's defer.
		 */
		if (fg == ZS_EMPTY)
			schedule_work(&pool->free_work);
	}
	spin_unlock(&class->lock);
}

const struct address_space_operations zsmalloc_aops = {
	.isolate_page = zs_page_isolate,
	.migratepage = zs_page_migrate,
	.putback_page = zs_page_putback,
};

static int zs_register_migration(struct zs_pool *pool)
{
	pool->inode = alloc_anon_inode(zsmalloc_mnt->mnt_sb);
	if (IS_ERR(pool->inode)) {
		pool->inode = NULL;
		return 1;
	}

	pool->inode->i_mapping->private_data = pool;
	pool->inode->i_mapping->a_ops = &zsmalloc_aops;
	return 0;
}

static void zs_unregister_migration(struct zs_pool *pool)
{
	flush_work(&pool->free_work);
	if (pool->inode)
		iput(pool->inode);
}

/*
 * Caller should hold page_lock of all pages in the zspage
 * In here, we cannot use zspage meta data.
 */
static void async_free_zspage(struct work_struct *work)
{
	int i;
	struct size_class *class;
	unsigned int class_idx;
	enum fullness_group fullness;
	struct zspage *zspage, *tmp;
	LIST_HEAD(free_pages);
	struct zs_pool *pool = container_of(work, struct zs_pool,
					free_work);

	for (i = 0; i < zs_size_classes; i++) {
		class = pool->size_class[i];
		if (class->index != i)
			continue;

		spin_lock(&class->lock);
		list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
		spin_unlock(&class->lock);
	}


	list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
		list_del(&zspage->list);
		lock_zspage(zspage);

		get_zspage_mapping(zspage, &class_idx, &fullness);
		VM_BUG_ON(fullness != ZS_EMPTY);
		class = pool->size_class[class_idx];
		spin_lock(&class->lock);
		__free_zspage(pool, pool->size_class[class_idx], zspage);
		spin_unlock(&class->lock);
	}
};

static void kick_deferred_free(struct zs_pool *pool)
{
	schedule_work(&pool->free_work);
}

static void init_deferred_free(struct zs_pool *pool)
{
	INIT_WORK(&pool->free_work, async_free_zspage);
}

static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
{
	struct page *page = get_first_page(zspage);

	do {
		WARN_ON(!trylock_page(page));
		__SetPageMovable(page, pool->inode->i_mapping);
		unlock_page(page);
	} while ((page = get_next_page(page)) != NULL);
}
#endif

2243 2244 2245 2246 2247 2248 2249 2250
/*
 *
 * Based on the number of unused allocated objects calculate
 * and return the number of pages that we can free.
 */
static unsigned long zs_can_compact(struct size_class *class)
{
	unsigned long obj_wasted;
2251 2252
	unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
	unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2253

2254 2255
	if (obj_allocated <= obj_used)
		return 0;
2256

2257
	obj_wasted = obj_allocated - obj_used;
2258
	obj_wasted /= class->objs_per_zspage;
2259

2260
	return obj_wasted * class->pages_per_zspage;
2261 2262
}

2263
static void __zs_compact(struct zs_pool *pool, struct size_class *class)
M
Minchan Kim 已提交
2264 2265
{
	struct zs_compact_control cc;
2266 2267
	struct zspage *src_zspage;
	struct zspage *dst_zspage = NULL;
M
Minchan Kim 已提交
2268 2269

	spin_lock(&class->lock);
2270
	while ((src_zspage = isolate_zspage(class, true))) {
M
Minchan Kim 已提交
2271

2272 2273 2274
		if (!zs_can_compact(class))
			break;

2275
		cc.obj_idx = 0;
M
Minchan Kim 已提交
2276
		cc.s_page = get_first_page(src_zspage);
M
Minchan Kim 已提交
2277

2278
		while ((dst_zspage = isolate_zspage(class, false))) {
M
Minchan Kim 已提交
2279
			cc.d_page = get_first_page(dst_zspage);
M
Minchan Kim 已提交
2280
			/*
2281 2282
			 * If there is no more space in dst_page, resched
			 * and see if anyone had allocated another zspage.
M
Minchan Kim 已提交
2283 2284 2285 2286
			 */
			if (!migrate_zspage(pool, class, &cc))
				break;

2287
			putback_zspage(class, dst_zspage);
M
Minchan Kim 已提交
2288 2289 2290
		}

		/* Stop if we couldn't find slot */
2291
		if (dst_zspage == NULL)
M
Minchan Kim 已提交
2292 2293
			break;

2294 2295
		putback_zspage(class, dst_zspage);
		if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
M
Minchan Kim 已提交
2296
			free_zspage(pool, class, src_zspage);
2297
			pool->stats.pages_compacted += class->pages_per_zspage;
2298
		}
M
Minchan Kim 已提交
2299 2300 2301 2302 2303
		spin_unlock(&class->lock);
		cond_resched();
		spin_lock(&class->lock);
	}

2304
	if (src_zspage)
2305
		putback_zspage(class, src_zspage);
M
Minchan Kim 已提交
2306

2307
	spin_unlock(&class->lock);
M
Minchan Kim 已提交
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
}

unsigned long zs_compact(struct zs_pool *pool)
{
	int i;
	struct size_class *class;

	for (i = zs_size_classes - 1; i >= 0; i--) {
		class = pool->size_class[i];
		if (!class)
			continue;
		if (class->index != i)
			continue;
2321
		__zs_compact(pool, class);
M
Minchan Kim 已提交
2322 2323
	}

2324
	return pool->stats.pages_compacted;
M
Minchan Kim 已提交
2325 2326
}
EXPORT_SYMBOL_GPL(zs_compact);
2327

2328 2329 2330 2331 2332 2333
void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
{
	memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
}
EXPORT_SYMBOL_GPL(zs_pool_stats);

2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
		struct shrink_control *sc)
{
	unsigned long pages_freed;
	struct zs_pool *pool = container_of(shrinker, struct zs_pool,
			shrinker);

	pages_freed = pool->stats.pages_compacted;
	/*
	 * Compact classes and calculate compaction delta.
	 * Can run concurrently with a manually triggered
	 * (by user) compaction.
	 */
	pages_freed = zs_compact(pool) - pages_freed;

	return pages_freed ? pages_freed : SHRINK_STOP;
}

static unsigned long zs_shrinker_count(struct shrinker *shrinker,
		struct shrink_control *sc)
{
	int i;
	struct size_class *class;
	unsigned long pages_to_free = 0;
	struct zs_pool *pool = container_of(shrinker, struct zs_pool,
			shrinker);

	for (i = zs_size_classes - 1; i >= 0; i--) {
		class = pool->size_class[i];
		if (!class)
			continue;
		if (class->index != i)
			continue;

		pages_to_free += zs_can_compact(class);
	}

	return pages_to_free;
}

static void zs_unregister_shrinker(struct zs_pool *pool)
{
	if (pool->shrinker_enabled) {
		unregister_shrinker(&pool->shrinker);
		pool->shrinker_enabled = false;
	}
}

static int zs_register_shrinker(struct zs_pool *pool)
{
	pool->shrinker.scan_objects = zs_shrinker_scan;
	pool->shrinker.count_objects = zs_shrinker_count;
	pool->shrinker.batch = 0;
	pool->shrinker.seeks = DEFAULT_SEEKS;

	return register_shrinker(&pool->shrinker);
}

2392
/**
2393 2394
 * zs_create_pool - Creates an allocation pool to work from.
 * @flags: allocation flags used to allocate pool metadata
2395
 *
2396 2397
 * This function must be called before anything when using
 * the zsmalloc allocator.
2398
 *
2399 2400
 * On success, a pointer to the newly created pool is returned,
 * otherwise NULL.
2401
 */
2402
struct zs_pool *zs_create_pool(const char *name)
2403
{
2404 2405 2406
	int i;
	struct zs_pool *pool;
	struct size_class *prev_class = NULL;
2407

2408 2409 2410
	pool = kzalloc(sizeof(*pool), GFP_KERNEL);
	if (!pool)
		return NULL;
2411

M
Minchan Kim 已提交
2412
	init_deferred_free(pool);
2413 2414 2415 2416 2417 2418
	pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
			GFP_KERNEL);
	if (!pool->size_class) {
		kfree(pool);
		return NULL;
	}
2419

2420 2421 2422 2423
	pool->name = kstrdup(name, GFP_KERNEL);
	if (!pool->name)
		goto err;

2424
	if (create_cache(pool))
2425 2426
		goto err;

2427
	/*
2428 2429
	 * Iterate reversly, because, size of size_class that we want to use
	 * for merging should be larger or equal to current size.
2430
	 */
2431 2432 2433
	for (i = zs_size_classes - 1; i >= 0; i--) {
		int size;
		int pages_per_zspage;
2434
		int objs_per_zspage;
2435
		struct size_class *class;
2436
		int fullness = 0;
2437

2438 2439 2440 2441
		size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
		if (size > ZS_MAX_ALLOC_SIZE)
			size = ZS_MAX_ALLOC_SIZE;
		pages_per_zspage = get_pages_per_zspage(size);
2442
		objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2443

2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
		/*
		 * size_class is used for normal zsmalloc operation such
		 * as alloc/free for that size. Although it is natural that we
		 * have one size_class for each size, there is a chance that we
		 * can get more memory utilization if we use one size_class for
		 * many different sizes whose size_class have same
		 * characteristics. So, we makes size_class point to
		 * previous size_class if possible.
		 */
		if (prev_class) {
2454
			if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
				pool->size_class[i] = prev_class;
				continue;
			}
		}

		class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
		if (!class)
			goto err;

		class->size = size;
		class->index = i;
		class->pages_per_zspage = pages_per_zspage;
2467
		class->objs_per_zspage = objs_per_zspage;
2468 2469
		spin_lock_init(&class->lock);
		pool->size_class[i] = class;
M
Minchan Kim 已提交
2470 2471
		for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
							fullness++)
2472
			INIT_LIST_HEAD(&class->fullness_list[fullness]);
2473 2474

		prev_class = class;
2475 2476
	}

2477 2478
	/* debug only, don't abort if it fails */
	zs_pool_stat_create(pool, name);
2479

M
Minchan Kim 已提交
2480 2481 2482
	if (zs_register_migration(pool))
		goto err;

2483 2484 2485 2486 2487 2488
	/*
	 * Not critical, we still can use the pool
	 * and user can trigger compaction manually.
	 */
	if (zs_register_shrinker(pool) == 0)
		pool->shrinker_enabled = true;
2489 2490 2491 2492 2493
	return pool;

err:
	zs_destroy_pool(pool);
	return NULL;
2494
}
2495
EXPORT_SYMBOL_GPL(zs_create_pool);
2496

2497
void zs_destroy_pool(struct zs_pool *pool)
2498
{
2499
	int i;
2500

2501
	zs_unregister_shrinker(pool);
M
Minchan Kim 已提交
2502
	zs_unregister_migration(pool);
2503 2504
	zs_pool_stat_destroy(pool);

2505 2506 2507
	for (i = 0; i < zs_size_classes; i++) {
		int fg;
		struct size_class *class = pool->size_class[i];
2508

2509 2510
		if (!class)
			continue;
2511

2512 2513
		if (class->index != i)
			continue;
2514

M
Minchan Kim 已提交
2515
		for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2516
			if (!list_empty(&class->fullness_list[fg])) {
2517 2518 2519 2520 2521 2522
				pr_info("Freeing non-empty class with size %db, fullness group %d\n",
					class->size, fg);
			}
		}
		kfree(class);
	}
2523

2524
	destroy_cache(pool);
2525
	kfree(pool->size_class);
2526
	kfree(pool->name);
2527 2528 2529
	kfree(pool);
}
EXPORT_SYMBOL_GPL(zs_destroy_pool);
2530

2531 2532
static int __init zs_init(void)
{
M
Minchan Kim 已提交
2533 2534 2535 2536 2537 2538 2539
	int ret;

	ret = zsmalloc_mount();
	if (ret)
		goto out;

	ret = zs_register_cpu_notifier();
2540

2541 2542
	if (ret)
		goto notifier_fail;
2543 2544 2545 2546 2547 2548

	init_zs_size_classes();

#ifdef CONFIG_ZPOOL
	zpool_register_driver(&zs_zpool_driver);
#endif
2549

2550 2551
	zs_stat_init();

2552
	return 0;
2553 2554 2555

notifier_fail:
	zs_unregister_cpu_notifier();
M
Minchan Kim 已提交
2556 2557
	zsmalloc_unmount();
out:
2558
	return ret;
2559 2560
}

2561
static void __exit zs_exit(void)
2562
{
2563 2564 2565
#ifdef CONFIG_ZPOOL
	zpool_unregister_driver(&zs_zpool_driver);
#endif
M
Minchan Kim 已提交
2566
	zsmalloc_unmount();
2567
	zs_unregister_cpu_notifier();
2568 2569

	zs_stat_exit();
2570
}
2571 2572 2573 2574 2575 2576

module_init(zs_init);
module_exit(zs_exit);

MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");