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