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