xref: /linux/drivers/block/zram/zram_drv.c (revision 20dfee95936413708701eb151f419597fdd9d948)
1 /*
2  * Compressed RAM block device
3  *
4  * Copyright (C) 2008, 2009, 2010  Nitin Gupta
5  *               2012, 2013 Minchan Kim
6  *
7  * This code is released using a dual license strategy: BSD/GPL
8  * You can choose the licence 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 #define KMSG_COMPONENT "zram"
16 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
17 
18 #include <linux/module.h>
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/bitops.h>
22 #include <linux/blkdev.h>
23 #include <linux/buffer_head.h>
24 #include <linux/device.h>
25 #include <linux/highmem.h>
26 #include <linux/slab.h>
27 #include <linux/backing-dev.h>
28 #include <linux/string.h>
29 #include <linux/vmalloc.h>
30 #include <linux/err.h>
31 #include <linux/idr.h>
32 #include <linux/sysfs.h>
33 #include <linux/debugfs.h>
34 #include <linux/cpuhotplug.h>
35 #include <linux/part_stat.h>
36 
37 #include "zram_drv.h"
38 
39 static DEFINE_IDR(zram_index_idr);
40 /* idr index must be protected */
41 static DEFINE_MUTEX(zram_index_mutex);
42 
43 static int zram_major;
44 static const char *default_compressor = CONFIG_ZRAM_DEF_COMP;
45 
46 /* Module params (documentation at end) */
47 static unsigned int num_devices = 1;
48 /*
49  * Pages that compress to sizes equals or greater than this are stored
50  * uncompressed in memory.
51  */
52 static size_t huge_class_size;
53 
54 static const struct block_device_operations zram_devops;
55 
56 static void zram_free_page(struct zram *zram, size_t index);
57 static int zram_read_page(struct zram *zram, struct page *page, u32 index,
58 			  struct bio *parent);
59 
60 static int zram_slot_trylock(struct zram *zram, u32 index)
61 {
62 	return bit_spin_trylock(ZRAM_LOCK, &zram->table[index].flags);
63 }
64 
65 static void zram_slot_lock(struct zram *zram, u32 index)
66 {
67 	bit_spin_lock(ZRAM_LOCK, &zram->table[index].flags);
68 }
69 
70 static void zram_slot_unlock(struct zram *zram, u32 index)
71 {
72 	bit_spin_unlock(ZRAM_LOCK, &zram->table[index].flags);
73 }
74 
75 static inline bool init_done(struct zram *zram)
76 {
77 	return zram->disksize;
78 }
79 
80 static inline struct zram *dev_to_zram(struct device *dev)
81 {
82 	return (struct zram *)dev_to_disk(dev)->private_data;
83 }
84 
85 static unsigned long zram_get_handle(struct zram *zram, u32 index)
86 {
87 	return zram->table[index].handle;
88 }
89 
90 static void zram_set_handle(struct zram *zram, u32 index, unsigned long handle)
91 {
92 	zram->table[index].handle = handle;
93 }
94 
95 /* flag operations require table entry bit_spin_lock() being held */
96 static bool zram_test_flag(struct zram *zram, u32 index,
97 			enum zram_pageflags flag)
98 {
99 	return zram->table[index].flags & BIT(flag);
100 }
101 
102 static void zram_set_flag(struct zram *zram, u32 index,
103 			enum zram_pageflags flag)
104 {
105 	zram->table[index].flags |= BIT(flag);
106 }
107 
108 static void zram_clear_flag(struct zram *zram, u32 index,
109 			enum zram_pageflags flag)
110 {
111 	zram->table[index].flags &= ~BIT(flag);
112 }
113 
114 static inline void zram_set_element(struct zram *zram, u32 index,
115 			unsigned long element)
116 {
117 	zram->table[index].element = element;
118 }
119 
120 static unsigned long zram_get_element(struct zram *zram, u32 index)
121 {
122 	return zram->table[index].element;
123 }
124 
125 static size_t zram_get_obj_size(struct zram *zram, u32 index)
126 {
127 	return zram->table[index].flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
128 }
129 
130 static void zram_set_obj_size(struct zram *zram,
131 					u32 index, size_t size)
132 {
133 	unsigned long flags = zram->table[index].flags >> ZRAM_FLAG_SHIFT;
134 
135 	zram->table[index].flags = (flags << ZRAM_FLAG_SHIFT) | size;
136 }
137 
138 static inline bool zram_allocated(struct zram *zram, u32 index)
139 {
140 	return zram_get_obj_size(zram, index) ||
141 			zram_test_flag(zram, index, ZRAM_SAME) ||
142 			zram_test_flag(zram, index, ZRAM_WB);
143 }
144 
145 #if PAGE_SIZE != 4096
146 static inline bool is_partial_io(struct bio_vec *bvec)
147 {
148 	return bvec->bv_len != PAGE_SIZE;
149 }
150 #define ZRAM_PARTIAL_IO		1
151 #else
152 static inline bool is_partial_io(struct bio_vec *bvec)
153 {
154 	return false;
155 }
156 #endif
157 
158 static inline void zram_set_priority(struct zram *zram, u32 index, u32 prio)
159 {
160 	prio &= ZRAM_COMP_PRIORITY_MASK;
161 	/*
162 	 * Clear previous priority value first, in case if we recompress
163 	 * further an already recompressed page
164 	 */
165 	zram->table[index].flags &= ~(ZRAM_COMP_PRIORITY_MASK <<
166 				      ZRAM_COMP_PRIORITY_BIT1);
167 	zram->table[index].flags |= (prio << ZRAM_COMP_PRIORITY_BIT1);
168 }
169 
170 static inline u32 zram_get_priority(struct zram *zram, u32 index)
171 {
172 	u32 prio = zram->table[index].flags >> ZRAM_COMP_PRIORITY_BIT1;
173 
174 	return prio & ZRAM_COMP_PRIORITY_MASK;
175 }
176 
177 static void zram_accessed(struct zram *zram, u32 index)
178 {
179 	zram_clear_flag(zram, index, ZRAM_IDLE);
180 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
181 	zram->table[index].ac_time = ktime_get_boottime();
182 #endif
183 }
184 
185 static inline void update_used_max(struct zram *zram,
186 					const unsigned long pages)
187 {
188 	unsigned long cur_max = atomic_long_read(&zram->stats.max_used_pages);
189 
190 	do {
191 		if (cur_max >= pages)
192 			return;
193 	} while (!atomic_long_try_cmpxchg(&zram->stats.max_used_pages,
194 					  &cur_max, pages));
195 }
196 
197 static inline void zram_fill_page(void *ptr, unsigned long len,
198 					unsigned long value)
199 {
200 	WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
201 	memset_l(ptr, value, len / sizeof(unsigned long));
202 }
203 
204 static bool page_same_filled(void *ptr, unsigned long *element)
205 {
206 	unsigned long *page;
207 	unsigned long val;
208 	unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
209 
210 	page = (unsigned long *)ptr;
211 	val = page[0];
212 
213 	if (val != page[last_pos])
214 		return false;
215 
216 	for (pos = 1; pos < last_pos; pos++) {
217 		if (val != page[pos])
218 			return false;
219 	}
220 
221 	*element = val;
222 
223 	return true;
224 }
225 
226 static ssize_t initstate_show(struct device *dev,
227 		struct device_attribute *attr, char *buf)
228 {
229 	u32 val;
230 	struct zram *zram = dev_to_zram(dev);
231 
232 	down_read(&zram->init_lock);
233 	val = init_done(zram);
234 	up_read(&zram->init_lock);
235 
236 	return scnprintf(buf, PAGE_SIZE, "%u\n", val);
237 }
238 
239 static ssize_t disksize_show(struct device *dev,
240 		struct device_attribute *attr, char *buf)
241 {
242 	struct zram *zram = dev_to_zram(dev);
243 
244 	return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
245 }
246 
247 static ssize_t mem_limit_store(struct device *dev,
248 		struct device_attribute *attr, const char *buf, size_t len)
249 {
250 	u64 limit;
251 	char *tmp;
252 	struct zram *zram = dev_to_zram(dev);
253 
254 	limit = memparse(buf, &tmp);
255 	if (buf == tmp) /* no chars parsed, invalid input */
256 		return -EINVAL;
257 
258 	down_write(&zram->init_lock);
259 	zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
260 	up_write(&zram->init_lock);
261 
262 	return len;
263 }
264 
265 static ssize_t mem_used_max_store(struct device *dev,
266 		struct device_attribute *attr, const char *buf, size_t len)
267 {
268 	int err;
269 	unsigned long val;
270 	struct zram *zram = dev_to_zram(dev);
271 
272 	err = kstrtoul(buf, 10, &val);
273 	if (err || val != 0)
274 		return -EINVAL;
275 
276 	down_read(&zram->init_lock);
277 	if (init_done(zram)) {
278 		atomic_long_set(&zram->stats.max_used_pages,
279 				zs_get_total_pages(zram->mem_pool));
280 	}
281 	up_read(&zram->init_lock);
282 
283 	return len;
284 }
285 
286 /*
287  * Mark all pages which are older than or equal to cutoff as IDLE.
288  * Callers should hold the zram init lock in read mode
289  */
290 static void mark_idle(struct zram *zram, ktime_t cutoff)
291 {
292 	int is_idle = 1;
293 	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
294 	int index;
295 
296 	for (index = 0; index < nr_pages; index++) {
297 		/*
298 		 * Do not mark ZRAM_UNDER_WB slot as ZRAM_IDLE to close race.
299 		 * See the comment in writeback_store.
300 		 */
301 		zram_slot_lock(zram, index);
302 		if (zram_allocated(zram, index) &&
303 				!zram_test_flag(zram, index, ZRAM_UNDER_WB)) {
304 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
305 			is_idle = !cutoff || ktime_after(cutoff,
306 							 zram->table[index].ac_time);
307 #endif
308 			if (is_idle)
309 				zram_set_flag(zram, index, ZRAM_IDLE);
310 		}
311 		zram_slot_unlock(zram, index);
312 	}
313 }
314 
315 static ssize_t idle_store(struct device *dev,
316 		struct device_attribute *attr, const char *buf, size_t len)
317 {
318 	struct zram *zram = dev_to_zram(dev);
319 	ktime_t cutoff_time = 0;
320 	ssize_t rv = -EINVAL;
321 
322 	if (!sysfs_streq(buf, "all")) {
323 		/*
324 		 * If it did not parse as 'all' try to treat it as an integer
325 		 * when we have memory tracking enabled.
326 		 */
327 		u64 age_sec;
328 
329 		if (IS_ENABLED(CONFIG_ZRAM_TRACK_ENTRY_ACTIME) && !kstrtoull(buf, 0, &age_sec))
330 			cutoff_time = ktime_sub(ktime_get_boottime(),
331 					ns_to_ktime(age_sec * NSEC_PER_SEC));
332 		else
333 			goto out;
334 	}
335 
336 	down_read(&zram->init_lock);
337 	if (!init_done(zram))
338 		goto out_unlock;
339 
340 	/*
341 	 * A cutoff_time of 0 marks everything as idle, this is the
342 	 * "all" behavior.
343 	 */
344 	mark_idle(zram, cutoff_time);
345 	rv = len;
346 
347 out_unlock:
348 	up_read(&zram->init_lock);
349 out:
350 	return rv;
351 }
352 
353 #ifdef CONFIG_ZRAM_WRITEBACK
354 static ssize_t writeback_limit_enable_store(struct device *dev,
355 		struct device_attribute *attr, const char *buf, size_t len)
356 {
357 	struct zram *zram = dev_to_zram(dev);
358 	u64 val;
359 	ssize_t ret = -EINVAL;
360 
361 	if (kstrtoull(buf, 10, &val))
362 		return ret;
363 
364 	down_read(&zram->init_lock);
365 	spin_lock(&zram->wb_limit_lock);
366 	zram->wb_limit_enable = val;
367 	spin_unlock(&zram->wb_limit_lock);
368 	up_read(&zram->init_lock);
369 	ret = len;
370 
371 	return ret;
372 }
373 
374 static ssize_t writeback_limit_enable_show(struct device *dev,
375 		struct device_attribute *attr, char *buf)
376 {
377 	bool val;
378 	struct zram *zram = dev_to_zram(dev);
379 
380 	down_read(&zram->init_lock);
381 	spin_lock(&zram->wb_limit_lock);
382 	val = zram->wb_limit_enable;
383 	spin_unlock(&zram->wb_limit_lock);
384 	up_read(&zram->init_lock);
385 
386 	return scnprintf(buf, PAGE_SIZE, "%d\n", val);
387 }
388 
389 static ssize_t writeback_limit_store(struct device *dev,
390 		struct device_attribute *attr, const char *buf, size_t len)
391 {
392 	struct zram *zram = dev_to_zram(dev);
393 	u64 val;
394 	ssize_t ret = -EINVAL;
395 
396 	if (kstrtoull(buf, 10, &val))
397 		return ret;
398 
399 	down_read(&zram->init_lock);
400 	spin_lock(&zram->wb_limit_lock);
401 	zram->bd_wb_limit = val;
402 	spin_unlock(&zram->wb_limit_lock);
403 	up_read(&zram->init_lock);
404 	ret = len;
405 
406 	return ret;
407 }
408 
409 static ssize_t writeback_limit_show(struct device *dev,
410 		struct device_attribute *attr, char *buf)
411 {
412 	u64 val;
413 	struct zram *zram = dev_to_zram(dev);
414 
415 	down_read(&zram->init_lock);
416 	spin_lock(&zram->wb_limit_lock);
417 	val = zram->bd_wb_limit;
418 	spin_unlock(&zram->wb_limit_lock);
419 	up_read(&zram->init_lock);
420 
421 	return scnprintf(buf, PAGE_SIZE, "%llu\n", val);
422 }
423 
424 static void reset_bdev(struct zram *zram)
425 {
426 	if (!zram->backing_dev)
427 		return;
428 
429 	/* hope filp_close flush all of IO */
430 	filp_close(zram->backing_dev, NULL);
431 	zram->backing_dev = NULL;
432 	zram->bdev = NULL;
433 	zram->disk->fops = &zram_devops;
434 	kvfree(zram->bitmap);
435 	zram->bitmap = NULL;
436 }
437 
438 static ssize_t backing_dev_show(struct device *dev,
439 		struct device_attribute *attr, char *buf)
440 {
441 	struct file *file;
442 	struct zram *zram = dev_to_zram(dev);
443 	char *p;
444 	ssize_t ret;
445 
446 	down_read(&zram->init_lock);
447 	file = zram->backing_dev;
448 	if (!file) {
449 		memcpy(buf, "none\n", 5);
450 		up_read(&zram->init_lock);
451 		return 5;
452 	}
453 
454 	p = file_path(file, buf, PAGE_SIZE - 1);
455 	if (IS_ERR(p)) {
456 		ret = PTR_ERR(p);
457 		goto out;
458 	}
459 
460 	ret = strlen(p);
461 	memmove(buf, p, ret);
462 	buf[ret++] = '\n';
463 out:
464 	up_read(&zram->init_lock);
465 	return ret;
466 }
467 
468 static ssize_t backing_dev_store(struct device *dev,
469 		struct device_attribute *attr, const char *buf, size_t len)
470 {
471 	char *file_name;
472 	size_t sz;
473 	struct file *backing_dev = NULL;
474 	struct inode *inode;
475 	unsigned int bitmap_sz;
476 	unsigned long nr_pages, *bitmap = NULL;
477 	int err;
478 	struct zram *zram = dev_to_zram(dev);
479 
480 	file_name = kmalloc(PATH_MAX, GFP_KERNEL);
481 	if (!file_name)
482 		return -ENOMEM;
483 
484 	down_write(&zram->init_lock);
485 	if (init_done(zram)) {
486 		pr_info("Can't setup backing device for initialized device\n");
487 		err = -EBUSY;
488 		goto out;
489 	}
490 
491 	strscpy(file_name, buf, PATH_MAX);
492 	/* ignore trailing newline */
493 	sz = strlen(file_name);
494 	if (sz > 0 && file_name[sz - 1] == '\n')
495 		file_name[sz - 1] = 0x00;
496 
497 	backing_dev = filp_open(file_name, O_RDWR | O_LARGEFILE | O_EXCL, 0);
498 	if (IS_ERR(backing_dev)) {
499 		err = PTR_ERR(backing_dev);
500 		backing_dev = NULL;
501 		goto out;
502 	}
503 
504 	inode = backing_dev->f_mapping->host;
505 
506 	/* Support only block device in this moment */
507 	if (!S_ISBLK(inode->i_mode)) {
508 		err = -ENOTBLK;
509 		goto out;
510 	}
511 
512 	nr_pages = i_size_read(inode) >> PAGE_SHIFT;
513 	bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
514 	bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
515 	if (!bitmap) {
516 		err = -ENOMEM;
517 		goto out;
518 	}
519 
520 	reset_bdev(zram);
521 
522 	zram->bdev = I_BDEV(inode);
523 	zram->backing_dev = backing_dev;
524 	zram->bitmap = bitmap;
525 	zram->nr_pages = nr_pages;
526 	up_write(&zram->init_lock);
527 
528 	pr_info("setup backing device %s\n", file_name);
529 	kfree(file_name);
530 
531 	return len;
532 out:
533 	kvfree(bitmap);
534 
535 	if (backing_dev)
536 		filp_close(backing_dev, NULL);
537 
538 	up_write(&zram->init_lock);
539 
540 	kfree(file_name);
541 
542 	return err;
543 }
544 
545 static unsigned long alloc_block_bdev(struct zram *zram)
546 {
547 	unsigned long blk_idx = 1;
548 retry:
549 	/* skip 0 bit to confuse zram.handle = 0 */
550 	blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, blk_idx);
551 	if (blk_idx == zram->nr_pages)
552 		return 0;
553 
554 	if (test_and_set_bit(blk_idx, zram->bitmap))
555 		goto retry;
556 
557 	atomic64_inc(&zram->stats.bd_count);
558 	return blk_idx;
559 }
560 
561 static void free_block_bdev(struct zram *zram, unsigned long blk_idx)
562 {
563 	int was_set;
564 
565 	was_set = test_and_clear_bit(blk_idx, zram->bitmap);
566 	WARN_ON_ONCE(!was_set);
567 	atomic64_dec(&zram->stats.bd_count);
568 }
569 
570 static void read_from_bdev_async(struct zram *zram, struct page *page,
571 			unsigned long entry, struct bio *parent)
572 {
573 	struct bio *bio;
574 
575 	bio = bio_alloc(zram->bdev, 1, parent->bi_opf, GFP_NOIO);
576 	bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
577 	__bio_add_page(bio, page, PAGE_SIZE, 0);
578 	bio_chain(bio, parent);
579 	submit_bio(bio);
580 }
581 
582 #define PAGE_WB_SIG "page_index="
583 
584 #define PAGE_WRITEBACK			0
585 #define HUGE_WRITEBACK			(1<<0)
586 #define IDLE_WRITEBACK			(1<<1)
587 #define INCOMPRESSIBLE_WRITEBACK	(1<<2)
588 
589 static ssize_t writeback_store(struct device *dev,
590 		struct device_attribute *attr, const char *buf, size_t len)
591 {
592 	struct zram *zram = dev_to_zram(dev);
593 	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
594 	unsigned long index = 0;
595 	struct bio bio;
596 	struct bio_vec bio_vec;
597 	struct page *page;
598 	ssize_t ret = len;
599 	int mode, err;
600 	unsigned long blk_idx = 0;
601 
602 	if (sysfs_streq(buf, "idle"))
603 		mode = IDLE_WRITEBACK;
604 	else if (sysfs_streq(buf, "huge"))
605 		mode = HUGE_WRITEBACK;
606 	else if (sysfs_streq(buf, "huge_idle"))
607 		mode = IDLE_WRITEBACK | HUGE_WRITEBACK;
608 	else if (sysfs_streq(buf, "incompressible"))
609 		mode = INCOMPRESSIBLE_WRITEBACK;
610 	else {
611 		if (strncmp(buf, PAGE_WB_SIG, sizeof(PAGE_WB_SIG) - 1))
612 			return -EINVAL;
613 
614 		if (kstrtol(buf + sizeof(PAGE_WB_SIG) - 1, 10, &index) ||
615 				index >= nr_pages)
616 			return -EINVAL;
617 
618 		nr_pages = 1;
619 		mode = PAGE_WRITEBACK;
620 	}
621 
622 	down_read(&zram->init_lock);
623 	if (!init_done(zram)) {
624 		ret = -EINVAL;
625 		goto release_init_lock;
626 	}
627 
628 	if (!zram->backing_dev) {
629 		ret = -ENODEV;
630 		goto release_init_lock;
631 	}
632 
633 	page = alloc_page(GFP_KERNEL);
634 	if (!page) {
635 		ret = -ENOMEM;
636 		goto release_init_lock;
637 	}
638 
639 	for (; nr_pages != 0; index++, nr_pages--) {
640 		spin_lock(&zram->wb_limit_lock);
641 		if (zram->wb_limit_enable && !zram->bd_wb_limit) {
642 			spin_unlock(&zram->wb_limit_lock);
643 			ret = -EIO;
644 			break;
645 		}
646 		spin_unlock(&zram->wb_limit_lock);
647 
648 		if (!blk_idx) {
649 			blk_idx = alloc_block_bdev(zram);
650 			if (!blk_idx) {
651 				ret = -ENOSPC;
652 				break;
653 			}
654 		}
655 
656 		zram_slot_lock(zram, index);
657 		if (!zram_allocated(zram, index))
658 			goto next;
659 
660 		if (zram_test_flag(zram, index, ZRAM_WB) ||
661 				zram_test_flag(zram, index, ZRAM_SAME) ||
662 				zram_test_flag(zram, index, ZRAM_UNDER_WB))
663 			goto next;
664 
665 		if (mode & IDLE_WRITEBACK &&
666 		    !zram_test_flag(zram, index, ZRAM_IDLE))
667 			goto next;
668 		if (mode & HUGE_WRITEBACK &&
669 		    !zram_test_flag(zram, index, ZRAM_HUGE))
670 			goto next;
671 		if (mode & INCOMPRESSIBLE_WRITEBACK &&
672 		    !zram_test_flag(zram, index, ZRAM_INCOMPRESSIBLE))
673 			goto next;
674 
675 		/*
676 		 * Clearing ZRAM_UNDER_WB is duty of caller.
677 		 * IOW, zram_free_page never clear it.
678 		 */
679 		zram_set_flag(zram, index, ZRAM_UNDER_WB);
680 		/* Need for hugepage writeback racing */
681 		zram_set_flag(zram, index, ZRAM_IDLE);
682 		zram_slot_unlock(zram, index);
683 		if (zram_read_page(zram, page, index, NULL)) {
684 			zram_slot_lock(zram, index);
685 			zram_clear_flag(zram, index, ZRAM_UNDER_WB);
686 			zram_clear_flag(zram, index, ZRAM_IDLE);
687 			zram_slot_unlock(zram, index);
688 			continue;
689 		}
690 
691 		bio_init(&bio, zram->bdev, &bio_vec, 1,
692 			 REQ_OP_WRITE | REQ_SYNC);
693 		bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
694 		__bio_add_page(&bio, page, PAGE_SIZE, 0);
695 
696 		/*
697 		 * XXX: A single page IO would be inefficient for write
698 		 * but it would be not bad as starter.
699 		 */
700 		err = submit_bio_wait(&bio);
701 		if (err) {
702 			zram_slot_lock(zram, index);
703 			zram_clear_flag(zram, index, ZRAM_UNDER_WB);
704 			zram_clear_flag(zram, index, ZRAM_IDLE);
705 			zram_slot_unlock(zram, index);
706 			/*
707 			 * BIO errors are not fatal, we continue and simply
708 			 * attempt to writeback the remaining objects (pages).
709 			 * At the same time we need to signal user-space that
710 			 * some writes (at least one, but also could be all of
711 			 * them) were not successful and we do so by returning
712 			 * the most recent BIO error.
713 			 */
714 			ret = err;
715 			continue;
716 		}
717 
718 		atomic64_inc(&zram->stats.bd_writes);
719 		/*
720 		 * We released zram_slot_lock so need to check if the slot was
721 		 * changed. If there is freeing for the slot, we can catch it
722 		 * easily by zram_allocated.
723 		 * A subtle case is the slot is freed/reallocated/marked as
724 		 * ZRAM_IDLE again. To close the race, idle_store doesn't
725 		 * mark ZRAM_IDLE once it found the slot was ZRAM_UNDER_WB.
726 		 * Thus, we could close the race by checking ZRAM_IDLE bit.
727 		 */
728 		zram_slot_lock(zram, index);
729 		if (!zram_allocated(zram, index) ||
730 			  !zram_test_flag(zram, index, ZRAM_IDLE)) {
731 			zram_clear_flag(zram, index, ZRAM_UNDER_WB);
732 			zram_clear_flag(zram, index, ZRAM_IDLE);
733 			goto next;
734 		}
735 
736 		zram_free_page(zram, index);
737 		zram_clear_flag(zram, index, ZRAM_UNDER_WB);
738 		zram_set_flag(zram, index, ZRAM_WB);
739 		zram_set_element(zram, index, blk_idx);
740 		blk_idx = 0;
741 		atomic64_inc(&zram->stats.pages_stored);
742 		spin_lock(&zram->wb_limit_lock);
743 		if (zram->wb_limit_enable && zram->bd_wb_limit > 0)
744 			zram->bd_wb_limit -=  1UL << (PAGE_SHIFT - 12);
745 		spin_unlock(&zram->wb_limit_lock);
746 next:
747 		zram_slot_unlock(zram, index);
748 	}
749 
750 	if (blk_idx)
751 		free_block_bdev(zram, blk_idx);
752 	__free_page(page);
753 release_init_lock:
754 	up_read(&zram->init_lock);
755 
756 	return ret;
757 }
758 
759 struct zram_work {
760 	struct work_struct work;
761 	struct zram *zram;
762 	unsigned long entry;
763 	struct page *page;
764 	int error;
765 };
766 
767 static void zram_sync_read(struct work_struct *work)
768 {
769 	struct zram_work *zw = container_of(work, struct zram_work, work);
770 	struct bio_vec bv;
771 	struct bio bio;
772 
773 	bio_init(&bio, zw->zram->bdev, &bv, 1, REQ_OP_READ);
774 	bio.bi_iter.bi_sector = zw->entry * (PAGE_SIZE >> 9);
775 	__bio_add_page(&bio, zw->page, PAGE_SIZE, 0);
776 	zw->error = submit_bio_wait(&bio);
777 }
778 
779 /*
780  * Block layer want one ->submit_bio to be active at a time, so if we use
781  * chained IO with parent IO in same context, it's a deadlock. To avoid that,
782  * use a worker thread context.
783  */
784 static int read_from_bdev_sync(struct zram *zram, struct page *page,
785 				unsigned long entry)
786 {
787 	struct zram_work work;
788 
789 	work.page = page;
790 	work.zram = zram;
791 	work.entry = entry;
792 
793 	INIT_WORK_ONSTACK(&work.work, zram_sync_read);
794 	queue_work(system_unbound_wq, &work.work);
795 	flush_work(&work.work);
796 	destroy_work_on_stack(&work.work);
797 
798 	return work.error;
799 }
800 
801 static int read_from_bdev(struct zram *zram, struct page *page,
802 			unsigned long entry, struct bio *parent)
803 {
804 	atomic64_inc(&zram->stats.bd_reads);
805 	if (!parent) {
806 		if (WARN_ON_ONCE(!IS_ENABLED(ZRAM_PARTIAL_IO)))
807 			return -EIO;
808 		return read_from_bdev_sync(zram, page, entry);
809 	}
810 	read_from_bdev_async(zram, page, entry, parent);
811 	return 0;
812 }
813 #else
814 static inline void reset_bdev(struct zram *zram) {};
815 static int read_from_bdev(struct zram *zram, struct page *page,
816 			unsigned long entry, struct bio *parent)
817 {
818 	return -EIO;
819 }
820 
821 static void free_block_bdev(struct zram *zram, unsigned long blk_idx) {};
822 #endif
823 
824 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
825 
826 static struct dentry *zram_debugfs_root;
827 
828 static void zram_debugfs_create(void)
829 {
830 	zram_debugfs_root = debugfs_create_dir("zram", NULL);
831 }
832 
833 static void zram_debugfs_destroy(void)
834 {
835 	debugfs_remove_recursive(zram_debugfs_root);
836 }
837 
838 static ssize_t read_block_state(struct file *file, char __user *buf,
839 				size_t count, loff_t *ppos)
840 {
841 	char *kbuf;
842 	ssize_t index, written = 0;
843 	struct zram *zram = file->private_data;
844 	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
845 	struct timespec64 ts;
846 
847 	kbuf = kvmalloc(count, GFP_KERNEL);
848 	if (!kbuf)
849 		return -ENOMEM;
850 
851 	down_read(&zram->init_lock);
852 	if (!init_done(zram)) {
853 		up_read(&zram->init_lock);
854 		kvfree(kbuf);
855 		return -EINVAL;
856 	}
857 
858 	for (index = *ppos; index < nr_pages; index++) {
859 		int copied;
860 
861 		zram_slot_lock(zram, index);
862 		if (!zram_allocated(zram, index))
863 			goto next;
864 
865 		ts = ktime_to_timespec64(zram->table[index].ac_time);
866 		copied = snprintf(kbuf + written, count,
867 			"%12zd %12lld.%06lu %c%c%c%c%c%c\n",
868 			index, (s64)ts.tv_sec,
869 			ts.tv_nsec / NSEC_PER_USEC,
870 			zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
871 			zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
872 			zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
873 			zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
874 			zram_get_priority(zram, index) ? 'r' : '.',
875 			zram_test_flag(zram, index,
876 				       ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
877 
878 		if (count <= copied) {
879 			zram_slot_unlock(zram, index);
880 			break;
881 		}
882 		written += copied;
883 		count -= copied;
884 next:
885 		zram_slot_unlock(zram, index);
886 		*ppos += 1;
887 	}
888 
889 	up_read(&zram->init_lock);
890 	if (copy_to_user(buf, kbuf, written))
891 		written = -EFAULT;
892 	kvfree(kbuf);
893 
894 	return written;
895 }
896 
897 static const struct file_operations proc_zram_block_state_op = {
898 	.open = simple_open,
899 	.read = read_block_state,
900 	.llseek = default_llseek,
901 };
902 
903 static void zram_debugfs_register(struct zram *zram)
904 {
905 	if (!zram_debugfs_root)
906 		return;
907 
908 	zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
909 						zram_debugfs_root);
910 	debugfs_create_file("block_state", 0400, zram->debugfs_dir,
911 				zram, &proc_zram_block_state_op);
912 }
913 
914 static void zram_debugfs_unregister(struct zram *zram)
915 {
916 	debugfs_remove_recursive(zram->debugfs_dir);
917 }
918 #else
919 static void zram_debugfs_create(void) {};
920 static void zram_debugfs_destroy(void) {};
921 static void zram_debugfs_register(struct zram *zram) {};
922 static void zram_debugfs_unregister(struct zram *zram) {};
923 #endif
924 
925 /*
926  * We switched to per-cpu streams and this attr is not needed anymore.
927  * However, we will keep it around for some time, because:
928  * a) we may revert per-cpu streams in the future
929  * b) it's visible to user space and we need to follow our 2 years
930  *    retirement rule; but we already have a number of 'soon to be
931  *    altered' attrs, so max_comp_streams need to wait for the next
932  *    layoff cycle.
933  */
934 static ssize_t max_comp_streams_show(struct device *dev,
935 		struct device_attribute *attr, char *buf)
936 {
937 	return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
938 }
939 
940 static ssize_t max_comp_streams_store(struct device *dev,
941 		struct device_attribute *attr, const char *buf, size_t len)
942 {
943 	return len;
944 }
945 
946 static void comp_algorithm_set(struct zram *zram, u32 prio, const char *alg)
947 {
948 	/* Do not free statically defined compression algorithms */
949 	if (zram->comp_algs[prio] != default_compressor)
950 		kfree(zram->comp_algs[prio]);
951 
952 	zram->comp_algs[prio] = alg;
953 }
954 
955 static ssize_t __comp_algorithm_show(struct zram *zram, u32 prio, char *buf)
956 {
957 	ssize_t sz;
958 
959 	down_read(&zram->init_lock);
960 	sz = zcomp_available_show(zram->comp_algs[prio], buf);
961 	up_read(&zram->init_lock);
962 
963 	return sz;
964 }
965 
966 static int __comp_algorithm_store(struct zram *zram, u32 prio, const char *buf)
967 {
968 	char *compressor;
969 	size_t sz;
970 
971 	sz = strlen(buf);
972 	if (sz >= CRYPTO_MAX_ALG_NAME)
973 		return -E2BIG;
974 
975 	compressor = kstrdup(buf, GFP_KERNEL);
976 	if (!compressor)
977 		return -ENOMEM;
978 
979 	/* ignore trailing newline */
980 	if (sz > 0 && compressor[sz - 1] == '\n')
981 		compressor[sz - 1] = 0x00;
982 
983 	if (!zcomp_available_algorithm(compressor)) {
984 		kfree(compressor);
985 		return -EINVAL;
986 	}
987 
988 	down_write(&zram->init_lock);
989 	if (init_done(zram)) {
990 		up_write(&zram->init_lock);
991 		kfree(compressor);
992 		pr_info("Can't change algorithm for initialized device\n");
993 		return -EBUSY;
994 	}
995 
996 	comp_algorithm_set(zram, prio, compressor);
997 	up_write(&zram->init_lock);
998 	return 0;
999 }
1000 
1001 static ssize_t comp_algorithm_show(struct device *dev,
1002 				   struct device_attribute *attr,
1003 				   char *buf)
1004 {
1005 	struct zram *zram = dev_to_zram(dev);
1006 
1007 	return __comp_algorithm_show(zram, ZRAM_PRIMARY_COMP, buf);
1008 }
1009 
1010 static ssize_t comp_algorithm_store(struct device *dev,
1011 				    struct device_attribute *attr,
1012 				    const char *buf,
1013 				    size_t len)
1014 {
1015 	struct zram *zram = dev_to_zram(dev);
1016 	int ret;
1017 
1018 	ret = __comp_algorithm_store(zram, ZRAM_PRIMARY_COMP, buf);
1019 	return ret ? ret : len;
1020 }
1021 
1022 #ifdef CONFIG_ZRAM_MULTI_COMP
1023 static ssize_t recomp_algorithm_show(struct device *dev,
1024 				     struct device_attribute *attr,
1025 				     char *buf)
1026 {
1027 	struct zram *zram = dev_to_zram(dev);
1028 	ssize_t sz = 0;
1029 	u32 prio;
1030 
1031 	for (prio = ZRAM_SECONDARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
1032 		if (!zram->comp_algs[prio])
1033 			continue;
1034 
1035 		sz += scnprintf(buf + sz, PAGE_SIZE - sz - 2, "#%d: ", prio);
1036 		sz += __comp_algorithm_show(zram, prio, buf + sz);
1037 	}
1038 
1039 	return sz;
1040 }
1041 
1042 static ssize_t recomp_algorithm_store(struct device *dev,
1043 				      struct device_attribute *attr,
1044 				      const char *buf,
1045 				      size_t len)
1046 {
1047 	struct zram *zram = dev_to_zram(dev);
1048 	int prio = ZRAM_SECONDARY_COMP;
1049 	char *args, *param, *val;
1050 	char *alg = NULL;
1051 	int ret;
1052 
1053 	args = skip_spaces(buf);
1054 	while (*args) {
1055 		args = next_arg(args, &param, &val);
1056 
1057 		if (!val || !*val)
1058 			return -EINVAL;
1059 
1060 		if (!strcmp(param, "algo")) {
1061 			alg = val;
1062 			continue;
1063 		}
1064 
1065 		if (!strcmp(param, "priority")) {
1066 			ret = kstrtoint(val, 10, &prio);
1067 			if (ret)
1068 				return ret;
1069 			continue;
1070 		}
1071 	}
1072 
1073 	if (!alg)
1074 		return -EINVAL;
1075 
1076 	if (prio < ZRAM_SECONDARY_COMP || prio >= ZRAM_MAX_COMPS)
1077 		return -EINVAL;
1078 
1079 	ret = __comp_algorithm_store(zram, prio, alg);
1080 	return ret ? ret : len;
1081 }
1082 #endif
1083 
1084 static ssize_t compact_store(struct device *dev,
1085 		struct device_attribute *attr, const char *buf, size_t len)
1086 {
1087 	struct zram *zram = dev_to_zram(dev);
1088 
1089 	down_read(&zram->init_lock);
1090 	if (!init_done(zram)) {
1091 		up_read(&zram->init_lock);
1092 		return -EINVAL;
1093 	}
1094 
1095 	zs_compact(zram->mem_pool);
1096 	up_read(&zram->init_lock);
1097 
1098 	return len;
1099 }
1100 
1101 static ssize_t io_stat_show(struct device *dev,
1102 		struct device_attribute *attr, char *buf)
1103 {
1104 	struct zram *zram = dev_to_zram(dev);
1105 	ssize_t ret;
1106 
1107 	down_read(&zram->init_lock);
1108 	ret = scnprintf(buf, PAGE_SIZE,
1109 			"%8llu %8llu 0 %8llu\n",
1110 			(u64)atomic64_read(&zram->stats.failed_reads),
1111 			(u64)atomic64_read(&zram->stats.failed_writes),
1112 			(u64)atomic64_read(&zram->stats.notify_free));
1113 	up_read(&zram->init_lock);
1114 
1115 	return ret;
1116 }
1117 
1118 static ssize_t mm_stat_show(struct device *dev,
1119 		struct device_attribute *attr, char *buf)
1120 {
1121 	struct zram *zram = dev_to_zram(dev);
1122 	struct zs_pool_stats pool_stats;
1123 	u64 orig_size, mem_used = 0;
1124 	long max_used;
1125 	ssize_t ret;
1126 
1127 	memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1128 
1129 	down_read(&zram->init_lock);
1130 	if (init_done(zram)) {
1131 		mem_used = zs_get_total_pages(zram->mem_pool);
1132 		zs_pool_stats(zram->mem_pool, &pool_stats);
1133 	}
1134 
1135 	orig_size = atomic64_read(&zram->stats.pages_stored);
1136 	max_used = atomic_long_read(&zram->stats.max_used_pages);
1137 
1138 	ret = scnprintf(buf, PAGE_SIZE,
1139 			"%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu %8llu\n",
1140 			orig_size << PAGE_SHIFT,
1141 			(u64)atomic64_read(&zram->stats.compr_data_size),
1142 			mem_used << PAGE_SHIFT,
1143 			zram->limit_pages << PAGE_SHIFT,
1144 			max_used << PAGE_SHIFT,
1145 			(u64)atomic64_read(&zram->stats.same_pages),
1146 			atomic_long_read(&pool_stats.pages_compacted),
1147 			(u64)atomic64_read(&zram->stats.huge_pages),
1148 			(u64)atomic64_read(&zram->stats.huge_pages_since));
1149 	up_read(&zram->init_lock);
1150 
1151 	return ret;
1152 }
1153 
1154 #ifdef CONFIG_ZRAM_WRITEBACK
1155 #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
1156 static ssize_t bd_stat_show(struct device *dev,
1157 		struct device_attribute *attr, char *buf)
1158 {
1159 	struct zram *zram = dev_to_zram(dev);
1160 	ssize_t ret;
1161 
1162 	down_read(&zram->init_lock);
1163 	ret = scnprintf(buf, PAGE_SIZE,
1164 		"%8llu %8llu %8llu\n",
1165 			FOUR_K((u64)atomic64_read(&zram->stats.bd_count)),
1166 			FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)),
1167 			FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)));
1168 	up_read(&zram->init_lock);
1169 
1170 	return ret;
1171 }
1172 #endif
1173 
1174 static ssize_t debug_stat_show(struct device *dev,
1175 		struct device_attribute *attr, char *buf)
1176 {
1177 	int version = 1;
1178 	struct zram *zram = dev_to_zram(dev);
1179 	ssize_t ret;
1180 
1181 	down_read(&zram->init_lock);
1182 	ret = scnprintf(buf, PAGE_SIZE,
1183 			"version: %d\n%8llu %8llu\n",
1184 			version,
1185 			(u64)atomic64_read(&zram->stats.writestall),
1186 			(u64)atomic64_read(&zram->stats.miss_free));
1187 	up_read(&zram->init_lock);
1188 
1189 	return ret;
1190 }
1191 
1192 static DEVICE_ATTR_RO(io_stat);
1193 static DEVICE_ATTR_RO(mm_stat);
1194 #ifdef CONFIG_ZRAM_WRITEBACK
1195 static DEVICE_ATTR_RO(bd_stat);
1196 #endif
1197 static DEVICE_ATTR_RO(debug_stat);
1198 
1199 static void zram_meta_free(struct zram *zram, u64 disksize)
1200 {
1201 	size_t num_pages = disksize >> PAGE_SHIFT;
1202 	size_t index;
1203 
1204 	/* Free all pages that are still in this zram device */
1205 	for (index = 0; index < num_pages; index++)
1206 		zram_free_page(zram, index);
1207 
1208 	zs_destroy_pool(zram->mem_pool);
1209 	vfree(zram->table);
1210 }
1211 
1212 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
1213 {
1214 	size_t num_pages;
1215 
1216 	num_pages = disksize >> PAGE_SHIFT;
1217 	zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
1218 	if (!zram->table)
1219 		return false;
1220 
1221 	zram->mem_pool = zs_create_pool(zram->disk->disk_name);
1222 	if (!zram->mem_pool) {
1223 		vfree(zram->table);
1224 		return false;
1225 	}
1226 
1227 	if (!huge_class_size)
1228 		huge_class_size = zs_huge_class_size(zram->mem_pool);
1229 	return true;
1230 }
1231 
1232 /*
1233  * To protect concurrent access to the same index entry,
1234  * caller should hold this table index entry's bit_spinlock to
1235  * indicate this index entry is accessing.
1236  */
1237 static void zram_free_page(struct zram *zram, size_t index)
1238 {
1239 	unsigned long handle;
1240 
1241 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
1242 	zram->table[index].ac_time = 0;
1243 #endif
1244 	if (zram_test_flag(zram, index, ZRAM_IDLE))
1245 		zram_clear_flag(zram, index, ZRAM_IDLE);
1246 
1247 	if (zram_test_flag(zram, index, ZRAM_HUGE)) {
1248 		zram_clear_flag(zram, index, ZRAM_HUGE);
1249 		atomic64_dec(&zram->stats.huge_pages);
1250 	}
1251 
1252 	if (zram_test_flag(zram, index, ZRAM_INCOMPRESSIBLE))
1253 		zram_clear_flag(zram, index, ZRAM_INCOMPRESSIBLE);
1254 
1255 	zram_set_priority(zram, index, 0);
1256 
1257 	if (zram_test_flag(zram, index, ZRAM_WB)) {
1258 		zram_clear_flag(zram, index, ZRAM_WB);
1259 		free_block_bdev(zram, zram_get_element(zram, index));
1260 		goto out;
1261 	}
1262 
1263 	/*
1264 	 * No memory is allocated for same element filled pages.
1265 	 * Simply clear same page flag.
1266 	 */
1267 	if (zram_test_flag(zram, index, ZRAM_SAME)) {
1268 		zram_clear_flag(zram, index, ZRAM_SAME);
1269 		atomic64_dec(&zram->stats.same_pages);
1270 		goto out;
1271 	}
1272 
1273 	handle = zram_get_handle(zram, index);
1274 	if (!handle)
1275 		return;
1276 
1277 	zs_free(zram->mem_pool, handle);
1278 
1279 	atomic64_sub(zram_get_obj_size(zram, index),
1280 			&zram->stats.compr_data_size);
1281 out:
1282 	atomic64_dec(&zram->stats.pages_stored);
1283 	zram_set_handle(zram, index, 0);
1284 	zram_set_obj_size(zram, index, 0);
1285 	WARN_ON_ONCE(zram->table[index].flags &
1286 		~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB));
1287 }
1288 
1289 /*
1290  * Reads (decompresses if needed) a page from zspool (zsmalloc).
1291  * Corresponding ZRAM slot should be locked.
1292  */
1293 static int zram_read_from_zspool(struct zram *zram, struct page *page,
1294 				 u32 index)
1295 {
1296 	struct zcomp_strm *zstrm;
1297 	unsigned long handle;
1298 	unsigned int size;
1299 	void *src, *dst;
1300 	u32 prio;
1301 	int ret;
1302 
1303 	handle = zram_get_handle(zram, index);
1304 	if (!handle || zram_test_flag(zram, index, ZRAM_SAME)) {
1305 		unsigned long value;
1306 		void *mem;
1307 
1308 		value = handle ? zram_get_element(zram, index) : 0;
1309 		mem = kmap_local_page(page);
1310 		zram_fill_page(mem, PAGE_SIZE, value);
1311 		kunmap_local(mem);
1312 		return 0;
1313 	}
1314 
1315 	size = zram_get_obj_size(zram, index);
1316 
1317 	if (size != PAGE_SIZE) {
1318 		prio = zram_get_priority(zram, index);
1319 		zstrm = zcomp_stream_get(zram->comps[prio]);
1320 	}
1321 
1322 	src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
1323 	if (size == PAGE_SIZE) {
1324 		dst = kmap_local_page(page);
1325 		copy_page(dst, src);
1326 		kunmap_local(dst);
1327 		ret = 0;
1328 	} else {
1329 		dst = kmap_local_page(page);
1330 		ret = zcomp_decompress(zstrm, src, size, dst);
1331 		kunmap_local(dst);
1332 		zcomp_stream_put(zram->comps[prio]);
1333 	}
1334 	zs_unmap_object(zram->mem_pool, handle);
1335 	return ret;
1336 }
1337 
1338 static int zram_read_page(struct zram *zram, struct page *page, u32 index,
1339 			  struct bio *parent)
1340 {
1341 	int ret;
1342 
1343 	zram_slot_lock(zram, index);
1344 	if (!zram_test_flag(zram, index, ZRAM_WB)) {
1345 		/* Slot should be locked through out the function call */
1346 		ret = zram_read_from_zspool(zram, page, index);
1347 		zram_slot_unlock(zram, index);
1348 	} else {
1349 		/*
1350 		 * The slot should be unlocked before reading from the backing
1351 		 * device.
1352 		 */
1353 		zram_slot_unlock(zram, index);
1354 
1355 		ret = read_from_bdev(zram, page, zram_get_element(zram, index),
1356 				     parent);
1357 	}
1358 
1359 	/* Should NEVER happen. Return bio error if it does. */
1360 	if (WARN_ON(ret < 0))
1361 		pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1362 
1363 	return ret;
1364 }
1365 
1366 /*
1367  * Use a temporary buffer to decompress the page, as the decompressor
1368  * always expects a full page for the output.
1369  */
1370 static int zram_bvec_read_partial(struct zram *zram, struct bio_vec *bvec,
1371 				  u32 index, int offset)
1372 {
1373 	struct page *page = alloc_page(GFP_NOIO);
1374 	int ret;
1375 
1376 	if (!page)
1377 		return -ENOMEM;
1378 	ret = zram_read_page(zram, page, index, NULL);
1379 	if (likely(!ret))
1380 		memcpy_to_bvec(bvec, page_address(page) + offset);
1381 	__free_page(page);
1382 	return ret;
1383 }
1384 
1385 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1386 			  u32 index, int offset, struct bio *bio)
1387 {
1388 	if (is_partial_io(bvec))
1389 		return zram_bvec_read_partial(zram, bvec, index, offset);
1390 	return zram_read_page(zram, bvec->bv_page, index, bio);
1391 }
1392 
1393 static int zram_write_page(struct zram *zram, struct page *page, u32 index)
1394 {
1395 	int ret = 0;
1396 	unsigned long alloced_pages;
1397 	unsigned long handle = -ENOMEM;
1398 	unsigned int comp_len = 0;
1399 	void *src, *dst, *mem;
1400 	struct zcomp_strm *zstrm;
1401 	unsigned long element = 0;
1402 	enum zram_pageflags flags = 0;
1403 
1404 	mem = kmap_local_page(page);
1405 	if (page_same_filled(mem, &element)) {
1406 		kunmap_local(mem);
1407 		/* Free memory associated with this sector now. */
1408 		flags = ZRAM_SAME;
1409 		atomic64_inc(&zram->stats.same_pages);
1410 		goto out;
1411 	}
1412 	kunmap_local(mem);
1413 
1414 compress_again:
1415 	zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
1416 	src = kmap_local_page(page);
1417 	ret = zcomp_compress(zstrm, src, &comp_len);
1418 	kunmap_local(src);
1419 
1420 	if (unlikely(ret)) {
1421 		zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1422 		pr_err("Compression failed! err=%d\n", ret);
1423 		zs_free(zram->mem_pool, handle);
1424 		return ret;
1425 	}
1426 
1427 	if (comp_len >= huge_class_size)
1428 		comp_len = PAGE_SIZE;
1429 	/*
1430 	 * handle allocation has 2 paths:
1431 	 * a) fast path is executed with preemption disabled (for
1432 	 *  per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
1433 	 *  since we can't sleep;
1434 	 * b) slow path enables preemption and attempts to allocate
1435 	 *  the page with __GFP_DIRECT_RECLAIM bit set. we have to
1436 	 *  put per-cpu compression stream and, thus, to re-do
1437 	 *  the compression once handle is allocated.
1438 	 *
1439 	 * if we have a 'non-null' handle here then we are coming
1440 	 * from the slow path and handle has already been allocated.
1441 	 */
1442 	if (IS_ERR_VALUE(handle))
1443 		handle = zs_malloc(zram->mem_pool, comp_len,
1444 				__GFP_KSWAPD_RECLAIM |
1445 				__GFP_NOWARN |
1446 				__GFP_HIGHMEM |
1447 				__GFP_MOVABLE);
1448 	if (IS_ERR_VALUE(handle)) {
1449 		zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1450 		atomic64_inc(&zram->stats.writestall);
1451 		handle = zs_malloc(zram->mem_pool, comp_len,
1452 				GFP_NOIO | __GFP_HIGHMEM |
1453 				__GFP_MOVABLE);
1454 		if (IS_ERR_VALUE(handle))
1455 			return PTR_ERR((void *)handle);
1456 
1457 		if (comp_len != PAGE_SIZE)
1458 			goto compress_again;
1459 		/*
1460 		 * If the page is not compressible, you need to acquire the
1461 		 * lock and execute the code below. The zcomp_stream_get()
1462 		 * call is needed to disable the cpu hotplug and grab the
1463 		 * zstrm buffer back. It is necessary that the dereferencing
1464 		 * of the zstrm variable below occurs correctly.
1465 		 */
1466 		zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
1467 	}
1468 
1469 	alloced_pages = zs_get_total_pages(zram->mem_pool);
1470 	update_used_max(zram, alloced_pages);
1471 
1472 	if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1473 		zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1474 		zs_free(zram->mem_pool, handle);
1475 		return -ENOMEM;
1476 	}
1477 
1478 	dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1479 
1480 	src = zstrm->buffer;
1481 	if (comp_len == PAGE_SIZE)
1482 		src = kmap_local_page(page);
1483 	memcpy(dst, src, comp_len);
1484 	if (comp_len == PAGE_SIZE)
1485 		kunmap_local(src);
1486 
1487 	zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1488 	zs_unmap_object(zram->mem_pool, handle);
1489 	atomic64_add(comp_len, &zram->stats.compr_data_size);
1490 out:
1491 	/*
1492 	 * Free memory associated with this sector
1493 	 * before overwriting unused sectors.
1494 	 */
1495 	zram_slot_lock(zram, index);
1496 	zram_free_page(zram, index);
1497 
1498 	if (comp_len == PAGE_SIZE) {
1499 		zram_set_flag(zram, index, ZRAM_HUGE);
1500 		atomic64_inc(&zram->stats.huge_pages);
1501 		atomic64_inc(&zram->stats.huge_pages_since);
1502 	}
1503 
1504 	if (flags) {
1505 		zram_set_flag(zram, index, flags);
1506 		zram_set_element(zram, index, element);
1507 	}  else {
1508 		zram_set_handle(zram, index, handle);
1509 		zram_set_obj_size(zram, index, comp_len);
1510 	}
1511 	zram_slot_unlock(zram, index);
1512 
1513 	/* Update stats */
1514 	atomic64_inc(&zram->stats.pages_stored);
1515 	return ret;
1516 }
1517 
1518 /*
1519  * This is a partial IO. Read the full page before writing the changes.
1520  */
1521 static int zram_bvec_write_partial(struct zram *zram, struct bio_vec *bvec,
1522 				   u32 index, int offset, struct bio *bio)
1523 {
1524 	struct page *page = alloc_page(GFP_NOIO);
1525 	int ret;
1526 
1527 	if (!page)
1528 		return -ENOMEM;
1529 
1530 	ret = zram_read_page(zram, page, index, bio);
1531 	if (!ret) {
1532 		memcpy_from_bvec(page_address(page) + offset, bvec);
1533 		ret = zram_write_page(zram, page, index);
1534 	}
1535 	__free_page(page);
1536 	return ret;
1537 }
1538 
1539 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1540 			   u32 index, int offset, struct bio *bio)
1541 {
1542 	if (is_partial_io(bvec))
1543 		return zram_bvec_write_partial(zram, bvec, index, offset, bio);
1544 	return zram_write_page(zram, bvec->bv_page, index);
1545 }
1546 
1547 #ifdef CONFIG_ZRAM_MULTI_COMP
1548 /*
1549  * This function will decompress (unless it's ZRAM_HUGE) the page and then
1550  * attempt to compress it using provided compression algorithm priority
1551  * (which is potentially more effective).
1552  *
1553  * Corresponding ZRAM slot should be locked.
1554  */
1555 static int zram_recompress(struct zram *zram, u32 index, struct page *page,
1556 			   u64 *num_recomp_pages, u32 threshold, u32 prio,
1557 			   u32 prio_max)
1558 {
1559 	struct zcomp_strm *zstrm = NULL;
1560 	unsigned long handle_old;
1561 	unsigned long handle_new;
1562 	unsigned int comp_len_old;
1563 	unsigned int comp_len_new;
1564 	unsigned int class_index_old;
1565 	unsigned int class_index_new;
1566 	u32 num_recomps = 0;
1567 	void *src, *dst;
1568 	int ret;
1569 
1570 	handle_old = zram_get_handle(zram, index);
1571 	if (!handle_old)
1572 		return -EINVAL;
1573 
1574 	comp_len_old = zram_get_obj_size(zram, index);
1575 	/*
1576 	 * Do not recompress objects that are already "small enough".
1577 	 */
1578 	if (comp_len_old < threshold)
1579 		return 0;
1580 
1581 	ret = zram_read_from_zspool(zram, page, index);
1582 	if (ret)
1583 		return ret;
1584 
1585 	class_index_old = zs_lookup_class_index(zram->mem_pool, comp_len_old);
1586 	/*
1587 	 * Iterate the secondary comp algorithms list (in order of priority)
1588 	 * and try to recompress the page.
1589 	 */
1590 	for (; prio < prio_max; prio++) {
1591 		if (!zram->comps[prio])
1592 			continue;
1593 
1594 		/*
1595 		 * Skip if the object is already re-compressed with a higher
1596 		 * priority algorithm (or same algorithm).
1597 		 */
1598 		if (prio <= zram_get_priority(zram, index))
1599 			continue;
1600 
1601 		num_recomps++;
1602 		zstrm = zcomp_stream_get(zram->comps[prio]);
1603 		src = kmap_local_page(page);
1604 		ret = zcomp_compress(zstrm, src, &comp_len_new);
1605 		kunmap_local(src);
1606 
1607 		if (ret) {
1608 			zcomp_stream_put(zram->comps[prio]);
1609 			return ret;
1610 		}
1611 
1612 		class_index_new = zs_lookup_class_index(zram->mem_pool,
1613 							comp_len_new);
1614 
1615 		/* Continue until we make progress */
1616 		if (class_index_new >= class_index_old ||
1617 		    (threshold && comp_len_new >= threshold)) {
1618 			zcomp_stream_put(zram->comps[prio]);
1619 			continue;
1620 		}
1621 
1622 		/* Recompression was successful so break out */
1623 		break;
1624 	}
1625 
1626 	/*
1627 	 * We did not try to recompress, e.g. when we have only one
1628 	 * secondary algorithm and the page is already recompressed
1629 	 * using that algorithm
1630 	 */
1631 	if (!zstrm)
1632 		return 0;
1633 
1634 	/*
1635 	 * Decrement the limit (if set) on pages we can recompress, even
1636 	 * when current recompression was unsuccessful or did not compress
1637 	 * the page below the threshold, because we still spent resources
1638 	 * on it.
1639 	 */
1640 	if (*num_recomp_pages)
1641 		*num_recomp_pages -= 1;
1642 
1643 	if (class_index_new >= class_index_old) {
1644 		/*
1645 		 * Secondary algorithms failed to re-compress the page
1646 		 * in a way that would save memory, mark the object as
1647 		 * incompressible so that we will not try to compress
1648 		 * it again.
1649 		 *
1650 		 * We need to make sure that all secondary algorithms have
1651 		 * failed, so we test if the number of recompressions matches
1652 		 * the number of active secondary algorithms.
1653 		 */
1654 		if (num_recomps == zram->num_active_comps - 1)
1655 			zram_set_flag(zram, index, ZRAM_INCOMPRESSIBLE);
1656 		return 0;
1657 	}
1658 
1659 	/* Successful recompression but above threshold */
1660 	if (threshold && comp_len_new >= threshold)
1661 		return 0;
1662 
1663 	/*
1664 	 * No direct reclaim (slow path) for handle allocation and no
1665 	 * re-compression attempt (unlike in zram_write_bvec()) since
1666 	 * we already have stored that object in zsmalloc. If we cannot
1667 	 * alloc memory for recompressed object then we bail out and
1668 	 * simply keep the old (existing) object in zsmalloc.
1669 	 */
1670 	handle_new = zs_malloc(zram->mem_pool, comp_len_new,
1671 			       __GFP_KSWAPD_RECLAIM |
1672 			       __GFP_NOWARN |
1673 			       __GFP_HIGHMEM |
1674 			       __GFP_MOVABLE);
1675 	if (IS_ERR_VALUE(handle_new)) {
1676 		zcomp_stream_put(zram->comps[prio]);
1677 		return PTR_ERR((void *)handle_new);
1678 	}
1679 
1680 	dst = zs_map_object(zram->mem_pool, handle_new, ZS_MM_WO);
1681 	memcpy(dst, zstrm->buffer, comp_len_new);
1682 	zcomp_stream_put(zram->comps[prio]);
1683 
1684 	zs_unmap_object(zram->mem_pool, handle_new);
1685 
1686 	zram_free_page(zram, index);
1687 	zram_set_handle(zram, index, handle_new);
1688 	zram_set_obj_size(zram, index, comp_len_new);
1689 	zram_set_priority(zram, index, prio);
1690 
1691 	atomic64_add(comp_len_new, &zram->stats.compr_data_size);
1692 	atomic64_inc(&zram->stats.pages_stored);
1693 
1694 	return 0;
1695 }
1696 
1697 #define RECOMPRESS_IDLE		(1 << 0)
1698 #define RECOMPRESS_HUGE		(1 << 1)
1699 
1700 static ssize_t recompress_store(struct device *dev,
1701 				struct device_attribute *attr,
1702 				const char *buf, size_t len)
1703 {
1704 	u32 prio = ZRAM_SECONDARY_COMP, prio_max = ZRAM_MAX_COMPS;
1705 	struct zram *zram = dev_to_zram(dev);
1706 	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
1707 	char *args, *param, *val, *algo = NULL;
1708 	u64 num_recomp_pages = ULLONG_MAX;
1709 	u32 mode = 0, threshold = 0;
1710 	unsigned long index;
1711 	struct page *page;
1712 	ssize_t ret;
1713 
1714 	args = skip_spaces(buf);
1715 	while (*args) {
1716 		args = next_arg(args, &param, &val);
1717 
1718 		if (!val || !*val)
1719 			return -EINVAL;
1720 
1721 		if (!strcmp(param, "type")) {
1722 			if (!strcmp(val, "idle"))
1723 				mode = RECOMPRESS_IDLE;
1724 			if (!strcmp(val, "huge"))
1725 				mode = RECOMPRESS_HUGE;
1726 			if (!strcmp(val, "huge_idle"))
1727 				mode = RECOMPRESS_IDLE | RECOMPRESS_HUGE;
1728 			continue;
1729 		}
1730 
1731 		if (!strcmp(param, "max_pages")) {
1732 			/*
1733 			 * Limit the number of entries (pages) we attempt to
1734 			 * recompress.
1735 			 */
1736 			ret = kstrtoull(val, 10, &num_recomp_pages);
1737 			if (ret)
1738 				return ret;
1739 			continue;
1740 		}
1741 
1742 		if (!strcmp(param, "threshold")) {
1743 			/*
1744 			 * We will re-compress only idle objects equal or
1745 			 * greater in size than watermark.
1746 			 */
1747 			ret = kstrtouint(val, 10, &threshold);
1748 			if (ret)
1749 				return ret;
1750 			continue;
1751 		}
1752 
1753 		if (!strcmp(param, "algo")) {
1754 			algo = val;
1755 			continue;
1756 		}
1757 	}
1758 
1759 	if (threshold >= huge_class_size)
1760 		return -EINVAL;
1761 
1762 	down_read(&zram->init_lock);
1763 	if (!init_done(zram)) {
1764 		ret = -EINVAL;
1765 		goto release_init_lock;
1766 	}
1767 
1768 	if (algo) {
1769 		bool found = false;
1770 
1771 		for (; prio < ZRAM_MAX_COMPS; prio++) {
1772 			if (!zram->comp_algs[prio])
1773 				continue;
1774 
1775 			if (!strcmp(zram->comp_algs[prio], algo)) {
1776 				prio_max = min(prio + 1, ZRAM_MAX_COMPS);
1777 				found = true;
1778 				break;
1779 			}
1780 		}
1781 
1782 		if (!found) {
1783 			ret = -EINVAL;
1784 			goto release_init_lock;
1785 		}
1786 	}
1787 
1788 	page = alloc_page(GFP_KERNEL);
1789 	if (!page) {
1790 		ret = -ENOMEM;
1791 		goto release_init_lock;
1792 	}
1793 
1794 	ret = len;
1795 	for (index = 0; index < nr_pages; index++) {
1796 		int err = 0;
1797 
1798 		if (!num_recomp_pages)
1799 			break;
1800 
1801 		zram_slot_lock(zram, index);
1802 
1803 		if (!zram_allocated(zram, index))
1804 			goto next;
1805 
1806 		if (mode & RECOMPRESS_IDLE &&
1807 		    !zram_test_flag(zram, index, ZRAM_IDLE))
1808 			goto next;
1809 
1810 		if (mode & RECOMPRESS_HUGE &&
1811 		    !zram_test_flag(zram, index, ZRAM_HUGE))
1812 			goto next;
1813 
1814 		if (zram_test_flag(zram, index, ZRAM_WB) ||
1815 		    zram_test_flag(zram, index, ZRAM_UNDER_WB) ||
1816 		    zram_test_flag(zram, index, ZRAM_SAME) ||
1817 		    zram_test_flag(zram, index, ZRAM_INCOMPRESSIBLE))
1818 			goto next;
1819 
1820 		err = zram_recompress(zram, index, page, &num_recomp_pages,
1821 				      threshold, prio, prio_max);
1822 next:
1823 		zram_slot_unlock(zram, index);
1824 		if (err) {
1825 			ret = err;
1826 			break;
1827 		}
1828 
1829 		cond_resched();
1830 	}
1831 
1832 	__free_page(page);
1833 
1834 release_init_lock:
1835 	up_read(&zram->init_lock);
1836 	return ret;
1837 }
1838 #endif
1839 
1840 static void zram_bio_discard(struct zram *zram, struct bio *bio)
1841 {
1842 	size_t n = bio->bi_iter.bi_size;
1843 	u32 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1844 	u32 offset = (bio->bi_iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
1845 			SECTOR_SHIFT;
1846 
1847 	/*
1848 	 * zram manages data in physical block size units. Because logical block
1849 	 * size isn't identical with physical block size on some arch, we
1850 	 * could get a discard request pointing to a specific offset within a
1851 	 * certain physical block.  Although we can handle this request by
1852 	 * reading that physiclal block and decompressing and partially zeroing
1853 	 * and re-compressing and then re-storing it, this isn't reasonable
1854 	 * because our intent with a discard request is to save memory.  So
1855 	 * skipping this logical block is appropriate here.
1856 	 */
1857 	if (offset) {
1858 		if (n <= (PAGE_SIZE - offset))
1859 			return;
1860 
1861 		n -= (PAGE_SIZE - offset);
1862 		index++;
1863 	}
1864 
1865 	while (n >= PAGE_SIZE) {
1866 		zram_slot_lock(zram, index);
1867 		zram_free_page(zram, index);
1868 		zram_slot_unlock(zram, index);
1869 		atomic64_inc(&zram->stats.notify_free);
1870 		index++;
1871 		n -= PAGE_SIZE;
1872 	}
1873 
1874 	bio_endio(bio);
1875 }
1876 
1877 static void zram_bio_read(struct zram *zram, struct bio *bio)
1878 {
1879 	unsigned long start_time = bio_start_io_acct(bio);
1880 	struct bvec_iter iter = bio->bi_iter;
1881 
1882 	do {
1883 		u32 index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1884 		u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
1885 				SECTOR_SHIFT;
1886 		struct bio_vec bv = bio_iter_iovec(bio, iter);
1887 
1888 		bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
1889 
1890 		if (zram_bvec_read(zram, &bv, index, offset, bio) < 0) {
1891 			atomic64_inc(&zram->stats.failed_reads);
1892 			bio->bi_status = BLK_STS_IOERR;
1893 			break;
1894 		}
1895 		flush_dcache_page(bv.bv_page);
1896 
1897 		zram_slot_lock(zram, index);
1898 		zram_accessed(zram, index);
1899 		zram_slot_unlock(zram, index);
1900 
1901 		bio_advance_iter_single(bio, &iter, bv.bv_len);
1902 	} while (iter.bi_size);
1903 
1904 	bio_end_io_acct(bio, start_time);
1905 	bio_endio(bio);
1906 }
1907 
1908 static void zram_bio_write(struct zram *zram, struct bio *bio)
1909 {
1910 	unsigned long start_time = bio_start_io_acct(bio);
1911 	struct bvec_iter iter = bio->bi_iter;
1912 
1913 	do {
1914 		u32 index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1915 		u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
1916 				SECTOR_SHIFT;
1917 		struct bio_vec bv = bio_iter_iovec(bio, iter);
1918 
1919 		bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
1920 
1921 		if (zram_bvec_write(zram, &bv, index, offset, bio) < 0) {
1922 			atomic64_inc(&zram->stats.failed_writes);
1923 			bio->bi_status = BLK_STS_IOERR;
1924 			break;
1925 		}
1926 
1927 		zram_slot_lock(zram, index);
1928 		zram_accessed(zram, index);
1929 		zram_slot_unlock(zram, index);
1930 
1931 		bio_advance_iter_single(bio, &iter, bv.bv_len);
1932 	} while (iter.bi_size);
1933 
1934 	bio_end_io_acct(bio, start_time);
1935 	bio_endio(bio);
1936 }
1937 
1938 /*
1939  * Handler function for all zram I/O requests.
1940  */
1941 static void zram_submit_bio(struct bio *bio)
1942 {
1943 	struct zram *zram = bio->bi_bdev->bd_disk->private_data;
1944 
1945 	switch (bio_op(bio)) {
1946 	case REQ_OP_READ:
1947 		zram_bio_read(zram, bio);
1948 		break;
1949 	case REQ_OP_WRITE:
1950 		zram_bio_write(zram, bio);
1951 		break;
1952 	case REQ_OP_DISCARD:
1953 	case REQ_OP_WRITE_ZEROES:
1954 		zram_bio_discard(zram, bio);
1955 		break;
1956 	default:
1957 		WARN_ON_ONCE(1);
1958 		bio_endio(bio);
1959 	}
1960 }
1961 
1962 static void zram_slot_free_notify(struct block_device *bdev,
1963 				unsigned long index)
1964 {
1965 	struct zram *zram;
1966 
1967 	zram = bdev->bd_disk->private_data;
1968 
1969 	atomic64_inc(&zram->stats.notify_free);
1970 	if (!zram_slot_trylock(zram, index)) {
1971 		atomic64_inc(&zram->stats.miss_free);
1972 		return;
1973 	}
1974 
1975 	zram_free_page(zram, index);
1976 	zram_slot_unlock(zram, index);
1977 }
1978 
1979 static void zram_destroy_comps(struct zram *zram)
1980 {
1981 	u32 prio;
1982 
1983 	for (prio = 0; prio < ZRAM_MAX_COMPS; prio++) {
1984 		struct zcomp *comp = zram->comps[prio];
1985 
1986 		zram->comps[prio] = NULL;
1987 		if (!comp)
1988 			continue;
1989 		zcomp_destroy(comp);
1990 		zram->num_active_comps--;
1991 	}
1992 }
1993 
1994 static void zram_reset_device(struct zram *zram)
1995 {
1996 	down_write(&zram->init_lock);
1997 
1998 	zram->limit_pages = 0;
1999 
2000 	if (!init_done(zram)) {
2001 		up_write(&zram->init_lock);
2002 		return;
2003 	}
2004 
2005 	set_capacity_and_notify(zram->disk, 0);
2006 	part_stat_set_all(zram->disk->part0, 0);
2007 
2008 	/* I/O operation under all of CPU are done so let's free */
2009 	zram_meta_free(zram, zram->disksize);
2010 	zram->disksize = 0;
2011 	zram_destroy_comps(zram);
2012 	memset(&zram->stats, 0, sizeof(zram->stats));
2013 	reset_bdev(zram);
2014 
2015 	comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
2016 	up_write(&zram->init_lock);
2017 }
2018 
2019 static ssize_t disksize_store(struct device *dev,
2020 		struct device_attribute *attr, const char *buf, size_t len)
2021 {
2022 	u64 disksize;
2023 	struct zcomp *comp;
2024 	struct zram *zram = dev_to_zram(dev);
2025 	int err;
2026 	u32 prio;
2027 
2028 	disksize = memparse(buf, NULL);
2029 	if (!disksize)
2030 		return -EINVAL;
2031 
2032 	down_write(&zram->init_lock);
2033 	if (init_done(zram)) {
2034 		pr_info("Cannot change disksize for initialized device\n");
2035 		err = -EBUSY;
2036 		goto out_unlock;
2037 	}
2038 
2039 	disksize = PAGE_ALIGN(disksize);
2040 	if (!zram_meta_alloc(zram, disksize)) {
2041 		err = -ENOMEM;
2042 		goto out_unlock;
2043 	}
2044 
2045 	for (prio = 0; prio < ZRAM_MAX_COMPS; prio++) {
2046 		if (!zram->comp_algs[prio])
2047 			continue;
2048 
2049 		comp = zcomp_create(zram->comp_algs[prio]);
2050 		if (IS_ERR(comp)) {
2051 			pr_err("Cannot initialise %s compressing backend\n",
2052 			       zram->comp_algs[prio]);
2053 			err = PTR_ERR(comp);
2054 			goto out_free_comps;
2055 		}
2056 
2057 		zram->comps[prio] = comp;
2058 		zram->num_active_comps++;
2059 	}
2060 	zram->disksize = disksize;
2061 	set_capacity_and_notify(zram->disk, zram->disksize >> SECTOR_SHIFT);
2062 	up_write(&zram->init_lock);
2063 
2064 	return len;
2065 
2066 out_free_comps:
2067 	zram_destroy_comps(zram);
2068 	zram_meta_free(zram, disksize);
2069 out_unlock:
2070 	up_write(&zram->init_lock);
2071 	return err;
2072 }
2073 
2074 static ssize_t reset_store(struct device *dev,
2075 		struct device_attribute *attr, const char *buf, size_t len)
2076 {
2077 	int ret;
2078 	unsigned short do_reset;
2079 	struct zram *zram;
2080 	struct gendisk *disk;
2081 
2082 	ret = kstrtou16(buf, 10, &do_reset);
2083 	if (ret)
2084 		return ret;
2085 
2086 	if (!do_reset)
2087 		return -EINVAL;
2088 
2089 	zram = dev_to_zram(dev);
2090 	disk = zram->disk;
2091 
2092 	mutex_lock(&disk->open_mutex);
2093 	/* Do not reset an active device or claimed device */
2094 	if (disk_openers(disk) || zram->claim) {
2095 		mutex_unlock(&disk->open_mutex);
2096 		return -EBUSY;
2097 	}
2098 
2099 	/* From now on, anyone can't open /dev/zram[0-9] */
2100 	zram->claim = true;
2101 	mutex_unlock(&disk->open_mutex);
2102 
2103 	/* Make sure all the pending I/O are finished */
2104 	sync_blockdev(disk->part0);
2105 	zram_reset_device(zram);
2106 
2107 	mutex_lock(&disk->open_mutex);
2108 	zram->claim = false;
2109 	mutex_unlock(&disk->open_mutex);
2110 
2111 	return len;
2112 }
2113 
2114 static int zram_open(struct gendisk *disk, blk_mode_t mode)
2115 {
2116 	struct zram *zram = disk->private_data;
2117 
2118 	WARN_ON(!mutex_is_locked(&disk->open_mutex));
2119 
2120 	/* zram was claimed to reset so open request fails */
2121 	if (zram->claim)
2122 		return -EBUSY;
2123 	return 0;
2124 }
2125 
2126 static const struct block_device_operations zram_devops = {
2127 	.open = zram_open,
2128 	.submit_bio = zram_submit_bio,
2129 	.swap_slot_free_notify = zram_slot_free_notify,
2130 	.owner = THIS_MODULE
2131 };
2132 
2133 static DEVICE_ATTR_WO(compact);
2134 static DEVICE_ATTR_RW(disksize);
2135 static DEVICE_ATTR_RO(initstate);
2136 static DEVICE_ATTR_WO(reset);
2137 static DEVICE_ATTR_WO(mem_limit);
2138 static DEVICE_ATTR_WO(mem_used_max);
2139 static DEVICE_ATTR_WO(idle);
2140 static DEVICE_ATTR_RW(max_comp_streams);
2141 static DEVICE_ATTR_RW(comp_algorithm);
2142 #ifdef CONFIG_ZRAM_WRITEBACK
2143 static DEVICE_ATTR_RW(backing_dev);
2144 static DEVICE_ATTR_WO(writeback);
2145 static DEVICE_ATTR_RW(writeback_limit);
2146 static DEVICE_ATTR_RW(writeback_limit_enable);
2147 #endif
2148 #ifdef CONFIG_ZRAM_MULTI_COMP
2149 static DEVICE_ATTR_RW(recomp_algorithm);
2150 static DEVICE_ATTR_WO(recompress);
2151 #endif
2152 
2153 static struct attribute *zram_disk_attrs[] = {
2154 	&dev_attr_disksize.attr,
2155 	&dev_attr_initstate.attr,
2156 	&dev_attr_reset.attr,
2157 	&dev_attr_compact.attr,
2158 	&dev_attr_mem_limit.attr,
2159 	&dev_attr_mem_used_max.attr,
2160 	&dev_attr_idle.attr,
2161 	&dev_attr_max_comp_streams.attr,
2162 	&dev_attr_comp_algorithm.attr,
2163 #ifdef CONFIG_ZRAM_WRITEBACK
2164 	&dev_attr_backing_dev.attr,
2165 	&dev_attr_writeback.attr,
2166 	&dev_attr_writeback_limit.attr,
2167 	&dev_attr_writeback_limit_enable.attr,
2168 #endif
2169 	&dev_attr_io_stat.attr,
2170 	&dev_attr_mm_stat.attr,
2171 #ifdef CONFIG_ZRAM_WRITEBACK
2172 	&dev_attr_bd_stat.attr,
2173 #endif
2174 	&dev_attr_debug_stat.attr,
2175 #ifdef CONFIG_ZRAM_MULTI_COMP
2176 	&dev_attr_recomp_algorithm.attr,
2177 	&dev_attr_recompress.attr,
2178 #endif
2179 	NULL,
2180 };
2181 
2182 ATTRIBUTE_GROUPS(zram_disk);
2183 
2184 /*
2185  * Allocate and initialize new zram device. the function returns
2186  * '>= 0' device_id upon success, and negative value otherwise.
2187  */
2188 static int zram_add(void)
2189 {
2190 	struct queue_limits lim = {
2191 		.logical_block_size		= ZRAM_LOGICAL_BLOCK_SIZE,
2192 		/*
2193 		 * To ensure that we always get PAGE_SIZE aligned and
2194 		 * n*PAGE_SIZED sized I/O requests.
2195 		 */
2196 		.physical_block_size		= PAGE_SIZE,
2197 		.io_min				= PAGE_SIZE,
2198 		.io_opt				= PAGE_SIZE,
2199 		.max_hw_discard_sectors		= UINT_MAX,
2200 		/*
2201 		 * zram_bio_discard() will clear all logical blocks if logical
2202 		 * block size is identical with physical block size(PAGE_SIZE).
2203 		 * But if it is different, we will skip discarding some parts of
2204 		 * logical blocks in the part of the request range which isn't
2205 		 * aligned to physical block size.  So we can't ensure that all
2206 		 * discarded logical blocks are zeroed.
2207 		 */
2208 #if ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE
2209 		.max_write_zeroes_sectors	= UINT_MAX,
2210 #endif
2211 	};
2212 	struct zram *zram;
2213 	int ret, device_id;
2214 
2215 	zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
2216 	if (!zram)
2217 		return -ENOMEM;
2218 
2219 	ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
2220 	if (ret < 0)
2221 		goto out_free_dev;
2222 	device_id = ret;
2223 
2224 	init_rwsem(&zram->init_lock);
2225 #ifdef CONFIG_ZRAM_WRITEBACK
2226 	spin_lock_init(&zram->wb_limit_lock);
2227 #endif
2228 
2229 	/* gendisk structure */
2230 	zram->disk = blk_alloc_disk(&lim, NUMA_NO_NODE);
2231 	if (IS_ERR(zram->disk)) {
2232 		pr_err("Error allocating disk structure for device %d\n",
2233 			device_id);
2234 		ret = PTR_ERR(zram->disk);
2235 		goto out_free_idr;
2236 	}
2237 
2238 	zram->disk->major = zram_major;
2239 	zram->disk->first_minor = device_id;
2240 	zram->disk->minors = 1;
2241 	zram->disk->flags |= GENHD_FL_NO_PART;
2242 	zram->disk->fops = &zram_devops;
2243 	zram->disk->private_data = zram;
2244 	snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
2245 
2246 	/* Actual capacity set using sysfs (/sys/block/zram<id>/disksize */
2247 	set_capacity(zram->disk, 0);
2248 	/* zram devices sort of resembles non-rotational disks */
2249 	blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
2250 	blk_queue_flag_set(QUEUE_FLAG_SYNCHRONOUS, zram->disk->queue);
2251 	blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, zram->disk->queue);
2252 	ret = device_add_disk(NULL, zram->disk, zram_disk_groups);
2253 	if (ret)
2254 		goto out_cleanup_disk;
2255 
2256 	comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
2257 
2258 	zram_debugfs_register(zram);
2259 	pr_info("Added device: %s\n", zram->disk->disk_name);
2260 	return device_id;
2261 
2262 out_cleanup_disk:
2263 	put_disk(zram->disk);
2264 out_free_idr:
2265 	idr_remove(&zram_index_idr, device_id);
2266 out_free_dev:
2267 	kfree(zram);
2268 	return ret;
2269 }
2270 
2271 static int zram_remove(struct zram *zram)
2272 {
2273 	bool claimed;
2274 
2275 	mutex_lock(&zram->disk->open_mutex);
2276 	if (disk_openers(zram->disk)) {
2277 		mutex_unlock(&zram->disk->open_mutex);
2278 		return -EBUSY;
2279 	}
2280 
2281 	claimed = zram->claim;
2282 	if (!claimed)
2283 		zram->claim = true;
2284 	mutex_unlock(&zram->disk->open_mutex);
2285 
2286 	zram_debugfs_unregister(zram);
2287 
2288 	if (claimed) {
2289 		/*
2290 		 * If we were claimed by reset_store(), del_gendisk() will
2291 		 * wait until reset_store() is done, so nothing need to do.
2292 		 */
2293 		;
2294 	} else {
2295 		/* Make sure all the pending I/O are finished */
2296 		sync_blockdev(zram->disk->part0);
2297 		zram_reset_device(zram);
2298 	}
2299 
2300 	pr_info("Removed device: %s\n", zram->disk->disk_name);
2301 
2302 	del_gendisk(zram->disk);
2303 
2304 	/* del_gendisk drains pending reset_store */
2305 	WARN_ON_ONCE(claimed && zram->claim);
2306 
2307 	/*
2308 	 * disksize_store() may be called in between zram_reset_device()
2309 	 * and del_gendisk(), so run the last reset to avoid leaking
2310 	 * anything allocated with disksize_store()
2311 	 */
2312 	zram_reset_device(zram);
2313 
2314 	put_disk(zram->disk);
2315 	kfree(zram);
2316 	return 0;
2317 }
2318 
2319 /* zram-control sysfs attributes */
2320 
2321 /*
2322  * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
2323  * sense that reading from this file does alter the state of your system -- it
2324  * creates a new un-initialized zram device and returns back this device's
2325  * device_id (or an error code if it fails to create a new device).
2326  */
2327 static ssize_t hot_add_show(const struct class *class,
2328 			const struct class_attribute *attr,
2329 			char *buf)
2330 {
2331 	int ret;
2332 
2333 	mutex_lock(&zram_index_mutex);
2334 	ret = zram_add();
2335 	mutex_unlock(&zram_index_mutex);
2336 
2337 	if (ret < 0)
2338 		return ret;
2339 	return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
2340 }
2341 /* This attribute must be set to 0400, so CLASS_ATTR_RO() can not be used */
2342 static struct class_attribute class_attr_hot_add =
2343 	__ATTR(hot_add, 0400, hot_add_show, NULL);
2344 
2345 static ssize_t hot_remove_store(const struct class *class,
2346 			const struct class_attribute *attr,
2347 			const char *buf,
2348 			size_t count)
2349 {
2350 	struct zram *zram;
2351 	int ret, dev_id;
2352 
2353 	/* dev_id is gendisk->first_minor, which is `int' */
2354 	ret = kstrtoint(buf, 10, &dev_id);
2355 	if (ret)
2356 		return ret;
2357 	if (dev_id < 0)
2358 		return -EINVAL;
2359 
2360 	mutex_lock(&zram_index_mutex);
2361 
2362 	zram = idr_find(&zram_index_idr, dev_id);
2363 	if (zram) {
2364 		ret = zram_remove(zram);
2365 		if (!ret)
2366 			idr_remove(&zram_index_idr, dev_id);
2367 	} else {
2368 		ret = -ENODEV;
2369 	}
2370 
2371 	mutex_unlock(&zram_index_mutex);
2372 	return ret ? ret : count;
2373 }
2374 static CLASS_ATTR_WO(hot_remove);
2375 
2376 static struct attribute *zram_control_class_attrs[] = {
2377 	&class_attr_hot_add.attr,
2378 	&class_attr_hot_remove.attr,
2379 	NULL,
2380 };
2381 ATTRIBUTE_GROUPS(zram_control_class);
2382 
2383 static struct class zram_control_class = {
2384 	.name		= "zram-control",
2385 	.class_groups	= zram_control_class_groups,
2386 };
2387 
2388 static int zram_remove_cb(int id, void *ptr, void *data)
2389 {
2390 	WARN_ON_ONCE(zram_remove(ptr));
2391 	return 0;
2392 }
2393 
2394 static void destroy_devices(void)
2395 {
2396 	class_unregister(&zram_control_class);
2397 	idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
2398 	zram_debugfs_destroy();
2399 	idr_destroy(&zram_index_idr);
2400 	unregister_blkdev(zram_major, "zram");
2401 	cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2402 }
2403 
2404 static int __init zram_init(void)
2405 {
2406 	int ret;
2407 
2408 	BUILD_BUG_ON(__NR_ZRAM_PAGEFLAGS > BITS_PER_LONG);
2409 
2410 	ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
2411 				      zcomp_cpu_up_prepare, zcomp_cpu_dead);
2412 	if (ret < 0)
2413 		return ret;
2414 
2415 	ret = class_register(&zram_control_class);
2416 	if (ret) {
2417 		pr_err("Unable to register zram-control class\n");
2418 		cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2419 		return ret;
2420 	}
2421 
2422 	zram_debugfs_create();
2423 	zram_major = register_blkdev(0, "zram");
2424 	if (zram_major <= 0) {
2425 		pr_err("Unable to get major number\n");
2426 		class_unregister(&zram_control_class);
2427 		cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2428 		return -EBUSY;
2429 	}
2430 
2431 	while (num_devices != 0) {
2432 		mutex_lock(&zram_index_mutex);
2433 		ret = zram_add();
2434 		mutex_unlock(&zram_index_mutex);
2435 		if (ret < 0)
2436 			goto out_error;
2437 		num_devices--;
2438 	}
2439 
2440 	return 0;
2441 
2442 out_error:
2443 	destroy_devices();
2444 	return ret;
2445 }
2446 
2447 static void __exit zram_exit(void)
2448 {
2449 	destroy_devices();
2450 }
2451 
2452 module_init(zram_init);
2453 module_exit(zram_exit);
2454 
2455 module_param(num_devices, uint, 0);
2456 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
2457 
2458 MODULE_LICENSE("Dual BSD/GPL");
2459 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2460 MODULE_DESCRIPTION("Compressed RAM Block Device");
2461