xref: /openbmc/linux/drivers/block/zram/zram_drv.c (revision 27e45f2e)
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 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)
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 		/* A null bio means rw_page was used, we must fallback to bio */
1457 		if (!bio)
1458 			return -EOPNOTSUPP;
1459 
1460 		ret = zram_bvec_read_from_bdev(zram, page, index, bio,
1461 					       partial_io);
1462 	}
1463 
1464 	/* Should NEVER happen. Return bio error if it does. */
1465 	if (WARN_ON(ret < 0))
1466 		pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1467 
1468 	return ret;
1469 }
1470 
1471 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1472 			  u32 index, int offset, struct bio *bio)
1473 {
1474 	int ret;
1475 	struct page *page;
1476 
1477 	page = bvec->bv_page;
1478 	if (is_partial_io(bvec)) {
1479 		/* Use a temporary buffer to decompress the page */
1480 		page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1481 		if (!page)
1482 			return -ENOMEM;
1483 	}
1484 
1485 	ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec));
1486 	if (unlikely(ret))
1487 		goto out;
1488 
1489 	if (is_partial_io(bvec)) {
1490 		void *src = kmap_atomic(page);
1491 
1492 		memcpy_to_bvec(bvec, src + offset);
1493 		kunmap_atomic(src);
1494 	}
1495 out:
1496 	if (is_partial_io(bvec))
1497 		__free_page(page);
1498 
1499 	return ret;
1500 }
1501 
1502 static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1503 				u32 index, struct bio *bio)
1504 {
1505 	int ret = 0;
1506 	unsigned long alloced_pages;
1507 	unsigned long handle = -ENOMEM;
1508 	unsigned int comp_len = 0;
1509 	void *src, *dst, *mem;
1510 	struct zcomp_strm *zstrm;
1511 	struct page *page = bvec->bv_page;
1512 	unsigned long element = 0;
1513 	enum zram_pageflags flags = 0;
1514 
1515 	mem = kmap_atomic(page);
1516 	if (page_same_filled(mem, &element)) {
1517 		kunmap_atomic(mem);
1518 		/* Free memory associated with this sector now. */
1519 		flags = ZRAM_SAME;
1520 		atomic64_inc(&zram->stats.same_pages);
1521 		goto out;
1522 	}
1523 	kunmap_atomic(mem);
1524 
1525 compress_again:
1526 	zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
1527 	src = kmap_atomic(page);
1528 	ret = zcomp_compress(zstrm, src, &comp_len);
1529 	kunmap_atomic(src);
1530 
1531 	if (unlikely(ret)) {
1532 		zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1533 		pr_err("Compression failed! err=%d\n", ret);
1534 		zs_free(zram->mem_pool, handle);
1535 		return ret;
1536 	}
1537 
1538 	if (comp_len >= huge_class_size)
1539 		comp_len = PAGE_SIZE;
1540 	/*
1541 	 * handle allocation has 2 paths:
1542 	 * a) fast path is executed with preemption disabled (for
1543 	 *  per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
1544 	 *  since we can't sleep;
1545 	 * b) slow path enables preemption and attempts to allocate
1546 	 *  the page with __GFP_DIRECT_RECLAIM bit set. we have to
1547 	 *  put per-cpu compression stream and, thus, to re-do
1548 	 *  the compression once handle is allocated.
1549 	 *
1550 	 * if we have a 'non-null' handle here then we are coming
1551 	 * from the slow path and handle has already been allocated.
1552 	 */
1553 	if (IS_ERR_VALUE(handle))
1554 		handle = zs_malloc(zram->mem_pool, comp_len,
1555 				__GFP_KSWAPD_RECLAIM |
1556 				__GFP_NOWARN |
1557 				__GFP_HIGHMEM |
1558 				__GFP_MOVABLE);
1559 	if (IS_ERR_VALUE(handle)) {
1560 		zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1561 		atomic64_inc(&zram->stats.writestall);
1562 		handle = zs_malloc(zram->mem_pool, comp_len,
1563 				GFP_NOIO | __GFP_HIGHMEM |
1564 				__GFP_MOVABLE);
1565 		if (IS_ERR_VALUE(handle))
1566 			return PTR_ERR((void *)handle);
1567 
1568 		if (comp_len != PAGE_SIZE)
1569 			goto compress_again;
1570 		/*
1571 		 * If the page is not compressible, you need to acquire the
1572 		 * lock and execute the code below. The zcomp_stream_get()
1573 		 * call is needed to disable the cpu hotplug and grab the
1574 		 * zstrm buffer back. It is necessary that the dereferencing
1575 		 * of the zstrm variable below occurs correctly.
1576 		 */
1577 		zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
1578 	}
1579 
1580 	alloced_pages = zs_get_total_pages(zram->mem_pool);
1581 	update_used_max(zram, alloced_pages);
1582 
1583 	if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1584 		zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1585 		zs_free(zram->mem_pool, handle);
1586 		return -ENOMEM;
1587 	}
1588 
1589 	dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1590 
1591 	src = zstrm->buffer;
1592 	if (comp_len == PAGE_SIZE)
1593 		src = kmap_atomic(page);
1594 	memcpy(dst, src, comp_len);
1595 	if (comp_len == PAGE_SIZE)
1596 		kunmap_atomic(src);
1597 
1598 	zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1599 	zs_unmap_object(zram->mem_pool, handle);
1600 	atomic64_add(comp_len, &zram->stats.compr_data_size);
1601 out:
1602 	/*
1603 	 * Free memory associated with this sector
1604 	 * before overwriting unused sectors.
1605 	 */
1606 	zram_slot_lock(zram, index);
1607 	zram_free_page(zram, index);
1608 
1609 	if (comp_len == PAGE_SIZE) {
1610 		zram_set_flag(zram, index, ZRAM_HUGE);
1611 		atomic64_inc(&zram->stats.huge_pages);
1612 		atomic64_inc(&zram->stats.huge_pages_since);
1613 	}
1614 
1615 	if (flags) {
1616 		zram_set_flag(zram, index, flags);
1617 		zram_set_element(zram, index, element);
1618 	}  else {
1619 		zram_set_handle(zram, index, handle);
1620 		zram_set_obj_size(zram, index, comp_len);
1621 	}
1622 	zram_slot_unlock(zram, index);
1623 
1624 	/* Update stats */
1625 	atomic64_inc(&zram->stats.pages_stored);
1626 	return ret;
1627 }
1628 
1629 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1630 				u32 index, int offset, struct bio *bio)
1631 {
1632 	int ret;
1633 	struct page *page = NULL;
1634 	struct bio_vec vec;
1635 
1636 	vec = *bvec;
1637 	if (is_partial_io(bvec)) {
1638 		void *dst;
1639 		/*
1640 		 * This is a partial IO. We need to read the full page
1641 		 * before to write the changes.
1642 		 */
1643 		page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1644 		if (!page)
1645 			return -ENOMEM;
1646 
1647 		ret = __zram_bvec_read(zram, page, index, bio, true);
1648 		if (ret)
1649 			goto out;
1650 
1651 		dst = kmap_atomic(page);
1652 		memcpy_from_bvec(dst + offset, bvec);
1653 		kunmap_atomic(dst);
1654 
1655 		vec.bv_page = page;
1656 		vec.bv_len = PAGE_SIZE;
1657 		vec.bv_offset = 0;
1658 	}
1659 
1660 	ret = __zram_bvec_write(zram, &vec, index, bio);
1661 out:
1662 	if (is_partial_io(bvec))
1663 		__free_page(page);
1664 	return ret;
1665 }
1666 
1667 #ifdef CONFIG_ZRAM_MULTI_COMP
1668 /*
1669  * This function will decompress (unless it's ZRAM_HUGE) the page and then
1670  * attempt to compress it using provided compression algorithm priority
1671  * (which is potentially more effective).
1672  *
1673  * Corresponding ZRAM slot should be locked.
1674  */
1675 static int zram_recompress(struct zram *zram, u32 index, struct page *page,
1676 			   u32 threshold, u32 prio, u32 prio_max)
1677 {
1678 	struct zcomp_strm *zstrm = NULL;
1679 	unsigned long handle_old;
1680 	unsigned long handle_new;
1681 	unsigned int comp_len_old;
1682 	unsigned int comp_len_new;
1683 	unsigned int class_index_old;
1684 	unsigned int class_index_new;
1685 	u32 num_recomps = 0;
1686 	void *src, *dst;
1687 	int ret;
1688 
1689 	handle_old = zram_get_handle(zram, index);
1690 	if (!handle_old)
1691 		return -EINVAL;
1692 
1693 	comp_len_old = zram_get_obj_size(zram, index);
1694 	/*
1695 	 * Do not recompress objects that are already "small enough".
1696 	 */
1697 	if (comp_len_old < threshold)
1698 		return 0;
1699 
1700 	ret = zram_read_from_zspool(zram, page, index);
1701 	if (ret)
1702 		return ret;
1703 
1704 	class_index_old = zs_lookup_class_index(zram->mem_pool, comp_len_old);
1705 	/*
1706 	 * Iterate the secondary comp algorithms list (in order of priority)
1707 	 * and try to recompress the page.
1708 	 */
1709 	for (; prio < prio_max; prio++) {
1710 		if (!zram->comps[prio])
1711 			continue;
1712 
1713 		/*
1714 		 * Skip if the object is already re-compressed with a higher
1715 		 * priority algorithm (or same algorithm).
1716 		 */
1717 		if (prio <= zram_get_priority(zram, index))
1718 			continue;
1719 
1720 		num_recomps++;
1721 		zstrm = zcomp_stream_get(zram->comps[prio]);
1722 		src = kmap_atomic(page);
1723 		ret = zcomp_compress(zstrm, src, &comp_len_new);
1724 		kunmap_atomic(src);
1725 
1726 		if (ret) {
1727 			zcomp_stream_put(zram->comps[prio]);
1728 			return ret;
1729 		}
1730 
1731 		class_index_new = zs_lookup_class_index(zram->mem_pool,
1732 							comp_len_new);
1733 
1734 		/* Continue until we make progress */
1735 		if (class_index_new >= class_index_old ||
1736 		    (threshold && comp_len_new >= threshold)) {
1737 			zcomp_stream_put(zram->comps[prio]);
1738 			continue;
1739 		}
1740 
1741 		/* Recompression was successful so break out */
1742 		break;
1743 	}
1744 
1745 	/*
1746 	 * We did not try to recompress, e.g. when we have only one
1747 	 * secondary algorithm and the page is already recompressed
1748 	 * using that algorithm
1749 	 */
1750 	if (!zstrm)
1751 		return 0;
1752 
1753 	if (class_index_new >= class_index_old) {
1754 		/*
1755 		 * Secondary algorithms failed to re-compress the page
1756 		 * in a way that would save memory, mark the object as
1757 		 * incompressible so that we will not try to compress
1758 		 * it again.
1759 		 *
1760 		 * We need to make sure that all secondary algorithms have
1761 		 * failed, so we test if the number of recompressions matches
1762 		 * the number of active secondary algorithms.
1763 		 */
1764 		if (num_recomps == zram->num_active_comps - 1)
1765 			zram_set_flag(zram, index, ZRAM_INCOMPRESSIBLE);
1766 		return 0;
1767 	}
1768 
1769 	/* Successful recompression but above threshold */
1770 	if (threshold && comp_len_new >= threshold)
1771 		return 0;
1772 
1773 	/*
1774 	 * No direct reclaim (slow path) for handle allocation and no
1775 	 * re-compression attempt (unlike in __zram_bvec_write()) since
1776 	 * we already have stored that object in zsmalloc. If we cannot
1777 	 * alloc memory for recompressed object then we bail out and
1778 	 * simply keep the old (existing) object in zsmalloc.
1779 	 */
1780 	handle_new = zs_malloc(zram->mem_pool, comp_len_new,
1781 			       __GFP_KSWAPD_RECLAIM |
1782 			       __GFP_NOWARN |
1783 			       __GFP_HIGHMEM |
1784 			       __GFP_MOVABLE);
1785 	if (IS_ERR_VALUE(handle_new)) {
1786 		zcomp_stream_put(zram->comps[prio]);
1787 		return PTR_ERR((void *)handle_new);
1788 	}
1789 
1790 	dst = zs_map_object(zram->mem_pool, handle_new, ZS_MM_WO);
1791 	memcpy(dst, zstrm->buffer, comp_len_new);
1792 	zcomp_stream_put(zram->comps[prio]);
1793 
1794 	zs_unmap_object(zram->mem_pool, handle_new);
1795 
1796 	zram_free_page(zram, index);
1797 	zram_set_handle(zram, index, handle_new);
1798 	zram_set_obj_size(zram, index, comp_len_new);
1799 	zram_set_priority(zram, index, prio);
1800 
1801 	atomic64_add(comp_len_new, &zram->stats.compr_data_size);
1802 	atomic64_inc(&zram->stats.pages_stored);
1803 
1804 	return 0;
1805 }
1806 
1807 #define RECOMPRESS_IDLE		(1 << 0)
1808 #define RECOMPRESS_HUGE		(1 << 1)
1809 
1810 static ssize_t recompress_store(struct device *dev,
1811 				struct device_attribute *attr,
1812 				const char *buf, size_t len)
1813 {
1814 	u32 prio = ZRAM_SECONDARY_COMP, prio_max = ZRAM_MAX_COMPS;
1815 	struct zram *zram = dev_to_zram(dev);
1816 	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
1817 	char *args, *param, *val, *algo = NULL;
1818 	u32 mode = 0, threshold = 0;
1819 	unsigned long index;
1820 	struct page *page;
1821 	ssize_t ret;
1822 
1823 	args = skip_spaces(buf);
1824 	while (*args) {
1825 		args = next_arg(args, &param, &val);
1826 
1827 		if (!*val)
1828 			return -EINVAL;
1829 
1830 		if (!strcmp(param, "type")) {
1831 			if (!strcmp(val, "idle"))
1832 				mode = RECOMPRESS_IDLE;
1833 			if (!strcmp(val, "huge"))
1834 				mode = RECOMPRESS_HUGE;
1835 			if (!strcmp(val, "huge_idle"))
1836 				mode = RECOMPRESS_IDLE | RECOMPRESS_HUGE;
1837 			continue;
1838 		}
1839 
1840 		if (!strcmp(param, "threshold")) {
1841 			/*
1842 			 * We will re-compress only idle objects equal or
1843 			 * greater in size than watermark.
1844 			 */
1845 			ret = kstrtouint(val, 10, &threshold);
1846 			if (ret)
1847 				return ret;
1848 			continue;
1849 		}
1850 
1851 		if (!strcmp(param, "algo")) {
1852 			algo = val;
1853 			continue;
1854 		}
1855 	}
1856 
1857 	if (threshold >= PAGE_SIZE)
1858 		return -EINVAL;
1859 
1860 	down_read(&zram->init_lock);
1861 	if (!init_done(zram)) {
1862 		ret = -EINVAL;
1863 		goto release_init_lock;
1864 	}
1865 
1866 	if (algo) {
1867 		bool found = false;
1868 
1869 		for (; prio < ZRAM_MAX_COMPS; prio++) {
1870 			if (!zram->comp_algs[prio])
1871 				continue;
1872 
1873 			if (!strcmp(zram->comp_algs[prio], algo)) {
1874 				prio_max = min(prio + 1, ZRAM_MAX_COMPS);
1875 				found = true;
1876 				break;
1877 			}
1878 		}
1879 
1880 		if (!found) {
1881 			ret = -EINVAL;
1882 			goto release_init_lock;
1883 		}
1884 	}
1885 
1886 	page = alloc_page(GFP_KERNEL);
1887 	if (!page) {
1888 		ret = -ENOMEM;
1889 		goto release_init_lock;
1890 	}
1891 
1892 	ret = len;
1893 	for (index = 0; index < nr_pages; index++) {
1894 		int err = 0;
1895 
1896 		zram_slot_lock(zram, index);
1897 
1898 		if (!zram_allocated(zram, index))
1899 			goto next;
1900 
1901 		if (mode & RECOMPRESS_IDLE &&
1902 		    !zram_test_flag(zram, index, ZRAM_IDLE))
1903 			goto next;
1904 
1905 		if (mode & RECOMPRESS_HUGE &&
1906 		    !zram_test_flag(zram, index, ZRAM_HUGE))
1907 			goto next;
1908 
1909 		if (zram_test_flag(zram, index, ZRAM_WB) ||
1910 		    zram_test_flag(zram, index, ZRAM_UNDER_WB) ||
1911 		    zram_test_flag(zram, index, ZRAM_SAME) ||
1912 		    zram_test_flag(zram, index, ZRAM_INCOMPRESSIBLE))
1913 			goto next;
1914 
1915 		err = zram_recompress(zram, index, page, threshold,
1916 				      prio, prio_max);
1917 next:
1918 		zram_slot_unlock(zram, index);
1919 		if (err) {
1920 			ret = err;
1921 			break;
1922 		}
1923 
1924 		cond_resched();
1925 	}
1926 
1927 	__free_page(page);
1928 
1929 release_init_lock:
1930 	up_read(&zram->init_lock);
1931 	return ret;
1932 }
1933 #endif
1934 
1935 /*
1936  * zram_bio_discard - handler on discard request
1937  * @index: physical block index in PAGE_SIZE units
1938  * @offset: byte offset within physical block
1939  */
1940 static void zram_bio_discard(struct zram *zram, u32 index,
1941 			     int offset, struct bio *bio)
1942 {
1943 	size_t n = bio->bi_iter.bi_size;
1944 
1945 	/*
1946 	 * zram manages data in physical block size units. Because logical block
1947 	 * size isn't identical with physical block size on some arch, we
1948 	 * could get a discard request pointing to a specific offset within a
1949 	 * certain physical block.  Although we can handle this request by
1950 	 * reading that physiclal block and decompressing and partially zeroing
1951 	 * and re-compressing and then re-storing it, this isn't reasonable
1952 	 * because our intent with a discard request is to save memory.  So
1953 	 * skipping this logical block is appropriate here.
1954 	 */
1955 	if (offset) {
1956 		if (n <= (PAGE_SIZE - offset))
1957 			return;
1958 
1959 		n -= (PAGE_SIZE - offset);
1960 		index++;
1961 	}
1962 
1963 	while (n >= PAGE_SIZE) {
1964 		zram_slot_lock(zram, index);
1965 		zram_free_page(zram, index);
1966 		zram_slot_unlock(zram, index);
1967 		atomic64_inc(&zram->stats.notify_free);
1968 		index++;
1969 		n -= PAGE_SIZE;
1970 	}
1971 }
1972 
1973 /*
1974  * Returns errno if it has some problem. Otherwise return 0 or 1.
1975  * Returns 0 if IO request was done synchronously
1976  * Returns 1 if IO request was successfully submitted.
1977  */
1978 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
1979 			int offset, enum req_op op, struct bio *bio)
1980 {
1981 	int ret;
1982 
1983 	if (!op_is_write(op)) {
1984 		ret = zram_bvec_read(zram, bvec, index, offset, bio);
1985 		flush_dcache_page(bvec->bv_page);
1986 	} else {
1987 		ret = zram_bvec_write(zram, bvec, index, offset, bio);
1988 	}
1989 
1990 	zram_slot_lock(zram, index);
1991 	zram_accessed(zram, index);
1992 	zram_slot_unlock(zram, index);
1993 
1994 	if (unlikely(ret < 0)) {
1995 		if (!op_is_write(op))
1996 			atomic64_inc(&zram->stats.failed_reads);
1997 		else
1998 			atomic64_inc(&zram->stats.failed_writes);
1999 	}
2000 
2001 	return ret;
2002 }
2003 
2004 static void __zram_make_request(struct zram *zram, struct bio *bio)
2005 {
2006 	int offset;
2007 	u32 index;
2008 	struct bio_vec bvec;
2009 	struct bvec_iter iter;
2010 	unsigned long start_time;
2011 
2012 	index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
2013 	offset = (bio->bi_iter.bi_sector &
2014 		  (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
2015 
2016 	switch (bio_op(bio)) {
2017 	case REQ_OP_DISCARD:
2018 	case REQ_OP_WRITE_ZEROES:
2019 		zram_bio_discard(zram, index, offset, bio);
2020 		bio_endio(bio);
2021 		return;
2022 	default:
2023 		break;
2024 	}
2025 
2026 	start_time = bio_start_io_acct(bio);
2027 	bio_for_each_segment(bvec, bio, iter) {
2028 		struct bio_vec bv = bvec;
2029 		unsigned int unwritten = bvec.bv_len;
2030 
2031 		do {
2032 			bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
2033 							unwritten);
2034 			if (zram_bvec_rw(zram, &bv, index, offset,
2035 					 bio_op(bio), bio) < 0) {
2036 				bio->bi_status = BLK_STS_IOERR;
2037 				break;
2038 			}
2039 
2040 			bv.bv_offset += bv.bv_len;
2041 			unwritten -= bv.bv_len;
2042 
2043 			update_position(&index, &offset, &bv);
2044 		} while (unwritten);
2045 	}
2046 	bio_end_io_acct(bio, start_time);
2047 	bio_endio(bio);
2048 }
2049 
2050 /*
2051  * Handler function for all zram I/O requests.
2052  */
2053 static void zram_submit_bio(struct bio *bio)
2054 {
2055 	struct zram *zram = bio->bi_bdev->bd_disk->private_data;
2056 
2057 	if (!valid_io_request(zram, bio->bi_iter.bi_sector,
2058 					bio->bi_iter.bi_size)) {
2059 		atomic64_inc(&zram->stats.invalid_io);
2060 		bio_io_error(bio);
2061 		return;
2062 	}
2063 
2064 	__zram_make_request(zram, bio);
2065 }
2066 
2067 static void zram_slot_free_notify(struct block_device *bdev,
2068 				unsigned long index)
2069 {
2070 	struct zram *zram;
2071 
2072 	zram = bdev->bd_disk->private_data;
2073 
2074 	atomic64_inc(&zram->stats.notify_free);
2075 	if (!zram_slot_trylock(zram, index)) {
2076 		atomic64_inc(&zram->stats.miss_free);
2077 		return;
2078 	}
2079 
2080 	zram_free_page(zram, index);
2081 	zram_slot_unlock(zram, index);
2082 }
2083 
2084 static int zram_rw_page(struct block_device *bdev, sector_t sector,
2085 		       struct page *page, enum req_op op)
2086 {
2087 	int offset, ret;
2088 	u32 index;
2089 	struct zram *zram;
2090 	struct bio_vec bv;
2091 	unsigned long start_time;
2092 
2093 	if (PageTransHuge(page))
2094 		return -ENOTSUPP;
2095 	zram = bdev->bd_disk->private_data;
2096 
2097 	if (!valid_io_request(zram, sector, PAGE_SIZE)) {
2098 		atomic64_inc(&zram->stats.invalid_io);
2099 		ret = -EINVAL;
2100 		goto out;
2101 	}
2102 
2103 	index = sector >> SECTORS_PER_PAGE_SHIFT;
2104 	offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
2105 
2106 	bv.bv_page = page;
2107 	bv.bv_len = PAGE_SIZE;
2108 	bv.bv_offset = 0;
2109 
2110 	start_time = bdev_start_io_acct(bdev->bd_disk->part0,
2111 			SECTORS_PER_PAGE, op, jiffies);
2112 	ret = zram_bvec_rw(zram, &bv, index, offset, op, NULL);
2113 	bdev_end_io_acct(bdev->bd_disk->part0, op, start_time);
2114 out:
2115 	/*
2116 	 * If I/O fails, just return error(ie, non-zero) without
2117 	 * calling page_endio.
2118 	 * It causes resubmit the I/O with bio request by upper functions
2119 	 * of rw_page(e.g., swap_readpage, __swap_writepage) and
2120 	 * bio->bi_end_io does things to handle the error
2121 	 * (e.g., SetPageError, set_page_dirty and extra works).
2122 	 */
2123 	if (unlikely(ret < 0))
2124 		return ret;
2125 
2126 	switch (ret) {
2127 	case 0:
2128 		page_endio(page, op_is_write(op), 0);
2129 		break;
2130 	case 1:
2131 		ret = 0;
2132 		break;
2133 	default:
2134 		WARN_ON(1);
2135 	}
2136 	return ret;
2137 }
2138 
2139 static void zram_destroy_comps(struct zram *zram)
2140 {
2141 	u32 prio;
2142 
2143 	for (prio = 0; prio < ZRAM_MAX_COMPS; prio++) {
2144 		struct zcomp *comp = zram->comps[prio];
2145 
2146 		zram->comps[prio] = NULL;
2147 		if (!comp)
2148 			continue;
2149 		zcomp_destroy(comp);
2150 		zram->num_active_comps--;
2151 	}
2152 }
2153 
2154 static void zram_reset_device(struct zram *zram)
2155 {
2156 	down_write(&zram->init_lock);
2157 
2158 	zram->limit_pages = 0;
2159 
2160 	if (!init_done(zram)) {
2161 		up_write(&zram->init_lock);
2162 		return;
2163 	}
2164 
2165 	set_capacity_and_notify(zram->disk, 0);
2166 	part_stat_set_all(zram->disk->part0, 0);
2167 
2168 	/* I/O operation under all of CPU are done so let's free */
2169 	zram_meta_free(zram, zram->disksize);
2170 	zram->disksize = 0;
2171 	zram_destroy_comps(zram);
2172 	memset(&zram->stats, 0, sizeof(zram->stats));
2173 	reset_bdev(zram);
2174 
2175 	comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
2176 	up_write(&zram->init_lock);
2177 }
2178 
2179 static ssize_t disksize_store(struct device *dev,
2180 		struct device_attribute *attr, const char *buf, size_t len)
2181 {
2182 	u64 disksize;
2183 	struct zcomp *comp;
2184 	struct zram *zram = dev_to_zram(dev);
2185 	int err;
2186 	u32 prio;
2187 
2188 	disksize = memparse(buf, NULL);
2189 	if (!disksize)
2190 		return -EINVAL;
2191 
2192 	down_write(&zram->init_lock);
2193 	if (init_done(zram)) {
2194 		pr_info("Cannot change disksize for initialized device\n");
2195 		err = -EBUSY;
2196 		goto out_unlock;
2197 	}
2198 
2199 	disksize = PAGE_ALIGN(disksize);
2200 	if (!zram_meta_alloc(zram, disksize)) {
2201 		err = -ENOMEM;
2202 		goto out_unlock;
2203 	}
2204 
2205 	for (prio = 0; prio < ZRAM_MAX_COMPS; prio++) {
2206 		if (!zram->comp_algs[prio])
2207 			continue;
2208 
2209 		comp = zcomp_create(zram->comp_algs[prio]);
2210 		if (IS_ERR(comp)) {
2211 			pr_err("Cannot initialise %s compressing backend\n",
2212 			       zram->comp_algs[prio]);
2213 			err = PTR_ERR(comp);
2214 			goto out_free_comps;
2215 		}
2216 
2217 		zram->comps[prio] = comp;
2218 		zram->num_active_comps++;
2219 	}
2220 	zram->disksize = disksize;
2221 	set_capacity_and_notify(zram->disk, zram->disksize >> SECTOR_SHIFT);
2222 	up_write(&zram->init_lock);
2223 
2224 	return len;
2225 
2226 out_free_comps:
2227 	zram_destroy_comps(zram);
2228 	zram_meta_free(zram, disksize);
2229 out_unlock:
2230 	up_write(&zram->init_lock);
2231 	return err;
2232 }
2233 
2234 static ssize_t reset_store(struct device *dev,
2235 		struct device_attribute *attr, const char *buf, size_t len)
2236 {
2237 	int ret;
2238 	unsigned short do_reset;
2239 	struct zram *zram;
2240 	struct gendisk *disk;
2241 
2242 	ret = kstrtou16(buf, 10, &do_reset);
2243 	if (ret)
2244 		return ret;
2245 
2246 	if (!do_reset)
2247 		return -EINVAL;
2248 
2249 	zram = dev_to_zram(dev);
2250 	disk = zram->disk;
2251 
2252 	mutex_lock(&disk->open_mutex);
2253 	/* Do not reset an active device or claimed device */
2254 	if (disk_openers(disk) || zram->claim) {
2255 		mutex_unlock(&disk->open_mutex);
2256 		return -EBUSY;
2257 	}
2258 
2259 	/* From now on, anyone can't open /dev/zram[0-9] */
2260 	zram->claim = true;
2261 	mutex_unlock(&disk->open_mutex);
2262 
2263 	/* Make sure all the pending I/O are finished */
2264 	sync_blockdev(disk->part0);
2265 	zram_reset_device(zram);
2266 
2267 	mutex_lock(&disk->open_mutex);
2268 	zram->claim = false;
2269 	mutex_unlock(&disk->open_mutex);
2270 
2271 	return len;
2272 }
2273 
2274 static int zram_open(struct block_device *bdev, fmode_t mode)
2275 {
2276 	int ret = 0;
2277 	struct zram *zram;
2278 
2279 	WARN_ON(!mutex_is_locked(&bdev->bd_disk->open_mutex));
2280 
2281 	zram = bdev->bd_disk->private_data;
2282 	/* zram was claimed to reset so open request fails */
2283 	if (zram->claim)
2284 		ret = -EBUSY;
2285 
2286 	return ret;
2287 }
2288 
2289 static const struct block_device_operations zram_devops = {
2290 	.open = zram_open,
2291 	.submit_bio = zram_submit_bio,
2292 	.swap_slot_free_notify = zram_slot_free_notify,
2293 	.rw_page = zram_rw_page,
2294 	.owner = THIS_MODULE
2295 };
2296 
2297 static DEVICE_ATTR_WO(compact);
2298 static DEVICE_ATTR_RW(disksize);
2299 static DEVICE_ATTR_RO(initstate);
2300 static DEVICE_ATTR_WO(reset);
2301 static DEVICE_ATTR_WO(mem_limit);
2302 static DEVICE_ATTR_WO(mem_used_max);
2303 static DEVICE_ATTR_WO(idle);
2304 static DEVICE_ATTR_RW(max_comp_streams);
2305 static DEVICE_ATTR_RW(comp_algorithm);
2306 #ifdef CONFIG_ZRAM_WRITEBACK
2307 static DEVICE_ATTR_RW(backing_dev);
2308 static DEVICE_ATTR_WO(writeback);
2309 static DEVICE_ATTR_RW(writeback_limit);
2310 static DEVICE_ATTR_RW(writeback_limit_enable);
2311 #endif
2312 #ifdef CONFIG_ZRAM_MULTI_COMP
2313 static DEVICE_ATTR_RW(recomp_algorithm);
2314 static DEVICE_ATTR_WO(recompress);
2315 #endif
2316 
2317 static struct attribute *zram_disk_attrs[] = {
2318 	&dev_attr_disksize.attr,
2319 	&dev_attr_initstate.attr,
2320 	&dev_attr_reset.attr,
2321 	&dev_attr_compact.attr,
2322 	&dev_attr_mem_limit.attr,
2323 	&dev_attr_mem_used_max.attr,
2324 	&dev_attr_idle.attr,
2325 	&dev_attr_max_comp_streams.attr,
2326 	&dev_attr_comp_algorithm.attr,
2327 #ifdef CONFIG_ZRAM_WRITEBACK
2328 	&dev_attr_backing_dev.attr,
2329 	&dev_attr_writeback.attr,
2330 	&dev_attr_writeback_limit.attr,
2331 	&dev_attr_writeback_limit_enable.attr,
2332 #endif
2333 	&dev_attr_io_stat.attr,
2334 	&dev_attr_mm_stat.attr,
2335 #ifdef CONFIG_ZRAM_WRITEBACK
2336 	&dev_attr_bd_stat.attr,
2337 #endif
2338 	&dev_attr_debug_stat.attr,
2339 #ifdef CONFIG_ZRAM_MULTI_COMP
2340 	&dev_attr_recomp_algorithm.attr,
2341 	&dev_attr_recompress.attr,
2342 #endif
2343 	NULL,
2344 };
2345 
2346 ATTRIBUTE_GROUPS(zram_disk);
2347 
2348 /*
2349  * Allocate and initialize new zram device. the function returns
2350  * '>= 0' device_id upon success, and negative value otherwise.
2351  */
2352 static int zram_add(void)
2353 {
2354 	struct zram *zram;
2355 	int ret, device_id;
2356 
2357 	zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
2358 	if (!zram)
2359 		return -ENOMEM;
2360 
2361 	ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
2362 	if (ret < 0)
2363 		goto out_free_dev;
2364 	device_id = ret;
2365 
2366 	init_rwsem(&zram->init_lock);
2367 #ifdef CONFIG_ZRAM_WRITEBACK
2368 	spin_lock_init(&zram->wb_limit_lock);
2369 #endif
2370 
2371 	/* gendisk structure */
2372 	zram->disk = blk_alloc_disk(NUMA_NO_NODE);
2373 	if (!zram->disk) {
2374 		pr_err("Error allocating disk structure for device %d\n",
2375 			device_id);
2376 		ret = -ENOMEM;
2377 		goto out_free_idr;
2378 	}
2379 
2380 	zram->disk->major = zram_major;
2381 	zram->disk->first_minor = device_id;
2382 	zram->disk->minors = 1;
2383 	zram->disk->flags |= GENHD_FL_NO_PART;
2384 	zram->disk->fops = &zram_devops;
2385 	zram->disk->private_data = zram;
2386 	snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
2387 
2388 	/* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
2389 	set_capacity(zram->disk, 0);
2390 	/* zram devices sort of resembles non-rotational disks */
2391 	blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
2392 	blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
2393 
2394 	/*
2395 	 * To ensure that we always get PAGE_SIZE aligned
2396 	 * and n*PAGE_SIZED sized I/O requests.
2397 	 */
2398 	blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
2399 	blk_queue_logical_block_size(zram->disk->queue,
2400 					ZRAM_LOGICAL_BLOCK_SIZE);
2401 	blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
2402 	blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
2403 	zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
2404 	blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
2405 
2406 	/*
2407 	 * zram_bio_discard() will clear all logical blocks if logical block
2408 	 * size is identical with physical block size(PAGE_SIZE). But if it is
2409 	 * different, we will skip discarding some parts of logical blocks in
2410 	 * the part of the request range which isn't aligned to physical block
2411 	 * size.  So we can't ensure that all discarded logical blocks are
2412 	 * zeroed.
2413 	 */
2414 	if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
2415 		blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
2416 
2417 	blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, zram->disk->queue);
2418 	ret = device_add_disk(NULL, zram->disk, zram_disk_groups);
2419 	if (ret)
2420 		goto out_cleanup_disk;
2421 
2422 	comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
2423 
2424 	zram_debugfs_register(zram);
2425 	pr_info("Added device: %s\n", zram->disk->disk_name);
2426 	return device_id;
2427 
2428 out_cleanup_disk:
2429 	put_disk(zram->disk);
2430 out_free_idr:
2431 	idr_remove(&zram_index_idr, device_id);
2432 out_free_dev:
2433 	kfree(zram);
2434 	return ret;
2435 }
2436 
2437 static int zram_remove(struct zram *zram)
2438 {
2439 	bool claimed;
2440 
2441 	mutex_lock(&zram->disk->open_mutex);
2442 	if (disk_openers(zram->disk)) {
2443 		mutex_unlock(&zram->disk->open_mutex);
2444 		return -EBUSY;
2445 	}
2446 
2447 	claimed = zram->claim;
2448 	if (!claimed)
2449 		zram->claim = true;
2450 	mutex_unlock(&zram->disk->open_mutex);
2451 
2452 	zram_debugfs_unregister(zram);
2453 
2454 	if (claimed) {
2455 		/*
2456 		 * If we were claimed by reset_store(), del_gendisk() will
2457 		 * wait until reset_store() is done, so nothing need to do.
2458 		 */
2459 		;
2460 	} else {
2461 		/* Make sure all the pending I/O are finished */
2462 		sync_blockdev(zram->disk->part0);
2463 		zram_reset_device(zram);
2464 	}
2465 
2466 	pr_info("Removed device: %s\n", zram->disk->disk_name);
2467 
2468 	del_gendisk(zram->disk);
2469 
2470 	/* del_gendisk drains pending reset_store */
2471 	WARN_ON_ONCE(claimed && zram->claim);
2472 
2473 	/*
2474 	 * disksize_store() may be called in between zram_reset_device()
2475 	 * and del_gendisk(), so run the last reset to avoid leaking
2476 	 * anything allocated with disksize_store()
2477 	 */
2478 	zram_reset_device(zram);
2479 
2480 	put_disk(zram->disk);
2481 	kfree(zram);
2482 	return 0;
2483 }
2484 
2485 /* zram-control sysfs attributes */
2486 
2487 /*
2488  * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
2489  * sense that reading from this file does alter the state of your system -- it
2490  * creates a new un-initialized zram device and returns back this device's
2491  * device_id (or an error code if it fails to create a new device).
2492  */
2493 static ssize_t hot_add_show(struct class *class,
2494 			struct class_attribute *attr,
2495 			char *buf)
2496 {
2497 	int ret;
2498 
2499 	mutex_lock(&zram_index_mutex);
2500 	ret = zram_add();
2501 	mutex_unlock(&zram_index_mutex);
2502 
2503 	if (ret < 0)
2504 		return ret;
2505 	return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
2506 }
2507 static struct class_attribute class_attr_hot_add =
2508 	__ATTR(hot_add, 0400, hot_add_show, NULL);
2509 
2510 static ssize_t hot_remove_store(struct class *class,
2511 			struct class_attribute *attr,
2512 			const char *buf,
2513 			size_t count)
2514 {
2515 	struct zram *zram;
2516 	int ret, dev_id;
2517 
2518 	/* dev_id is gendisk->first_minor, which is `int' */
2519 	ret = kstrtoint(buf, 10, &dev_id);
2520 	if (ret)
2521 		return ret;
2522 	if (dev_id < 0)
2523 		return -EINVAL;
2524 
2525 	mutex_lock(&zram_index_mutex);
2526 
2527 	zram = idr_find(&zram_index_idr, dev_id);
2528 	if (zram) {
2529 		ret = zram_remove(zram);
2530 		if (!ret)
2531 			idr_remove(&zram_index_idr, dev_id);
2532 	} else {
2533 		ret = -ENODEV;
2534 	}
2535 
2536 	mutex_unlock(&zram_index_mutex);
2537 	return ret ? ret : count;
2538 }
2539 static CLASS_ATTR_WO(hot_remove);
2540 
2541 static struct attribute *zram_control_class_attrs[] = {
2542 	&class_attr_hot_add.attr,
2543 	&class_attr_hot_remove.attr,
2544 	NULL,
2545 };
2546 ATTRIBUTE_GROUPS(zram_control_class);
2547 
2548 static struct class zram_control_class = {
2549 	.name		= "zram-control",
2550 	.owner		= THIS_MODULE,
2551 	.class_groups	= zram_control_class_groups,
2552 };
2553 
2554 static int zram_remove_cb(int id, void *ptr, void *data)
2555 {
2556 	WARN_ON_ONCE(zram_remove(ptr));
2557 	return 0;
2558 }
2559 
2560 static void destroy_devices(void)
2561 {
2562 	class_unregister(&zram_control_class);
2563 	idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
2564 	zram_debugfs_destroy();
2565 	idr_destroy(&zram_index_idr);
2566 	unregister_blkdev(zram_major, "zram");
2567 	cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2568 }
2569 
2570 static int __init zram_init(void)
2571 {
2572 	int ret;
2573 
2574 	BUILD_BUG_ON(__NR_ZRAM_PAGEFLAGS > BITS_PER_LONG);
2575 
2576 	ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
2577 				      zcomp_cpu_up_prepare, zcomp_cpu_dead);
2578 	if (ret < 0)
2579 		return ret;
2580 
2581 	ret = class_register(&zram_control_class);
2582 	if (ret) {
2583 		pr_err("Unable to register zram-control class\n");
2584 		cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2585 		return ret;
2586 	}
2587 
2588 	zram_debugfs_create();
2589 	zram_major = register_blkdev(0, "zram");
2590 	if (zram_major <= 0) {
2591 		pr_err("Unable to get major number\n");
2592 		class_unregister(&zram_control_class);
2593 		cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2594 		return -EBUSY;
2595 	}
2596 
2597 	while (num_devices != 0) {
2598 		mutex_lock(&zram_index_mutex);
2599 		ret = zram_add();
2600 		mutex_unlock(&zram_index_mutex);
2601 		if (ret < 0)
2602 			goto out_error;
2603 		num_devices--;
2604 	}
2605 
2606 	return 0;
2607 
2608 out_error:
2609 	destroy_devices();
2610 	return ret;
2611 }
2612 
2613 static void __exit zram_exit(void)
2614 {
2615 	destroy_devices();
2616 }
2617 
2618 module_init(zram_init);
2619 module_exit(zram_exit);
2620 
2621 module_param(num_devices, uint, 0);
2622 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
2623 
2624 MODULE_LICENSE("Dual BSD/GPL");
2625 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2626 MODULE_DESCRIPTION("Compressed RAM Block Device");
2627