xref: /linux/drivers/block/zram/zram_drv.c (revision bfd5bb6f90af092aa345b15cd78143956a13c2a8)
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/genhd.h>
26 #include <linux/highmem.h>
27 #include <linux/slab.h>
28 #include <linux/backing-dev.h>
29 #include <linux/string.h>
30 #include <linux/vmalloc.h>
31 #include <linux/err.h>
32 #include <linux/idr.h>
33 #include <linux/sysfs.h>
34 #include <linux/debugfs.h>
35 #include <linux/cpuhotplug.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 = "lzo";
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 void zram_free_page(struct zram *zram, size_t index);
55 
56 static void zram_slot_lock(struct zram *zram, u32 index)
57 {
58 	bit_spin_lock(ZRAM_LOCK, &zram->table[index].value);
59 }
60 
61 static void zram_slot_unlock(struct zram *zram, u32 index)
62 {
63 	bit_spin_unlock(ZRAM_LOCK, &zram->table[index].value);
64 }
65 
66 static inline bool init_done(struct zram *zram)
67 {
68 	return zram->disksize;
69 }
70 
71 static inline bool zram_allocated(struct zram *zram, u32 index)
72 {
73 
74 	return (zram->table[index].value >> (ZRAM_FLAG_SHIFT + 1)) ||
75 					zram->table[index].handle;
76 }
77 
78 static inline struct zram *dev_to_zram(struct device *dev)
79 {
80 	return (struct zram *)dev_to_disk(dev)->private_data;
81 }
82 
83 static unsigned long zram_get_handle(struct zram *zram, u32 index)
84 {
85 	return zram->table[index].handle;
86 }
87 
88 static void zram_set_handle(struct zram *zram, u32 index, unsigned long handle)
89 {
90 	zram->table[index].handle = handle;
91 }
92 
93 /* flag operations require table entry bit_spin_lock() being held */
94 static bool zram_test_flag(struct zram *zram, u32 index,
95 			enum zram_pageflags flag)
96 {
97 	return zram->table[index].value & BIT(flag);
98 }
99 
100 static void zram_set_flag(struct zram *zram, u32 index,
101 			enum zram_pageflags flag)
102 {
103 	zram->table[index].value |= BIT(flag);
104 }
105 
106 static void zram_clear_flag(struct zram *zram, u32 index,
107 			enum zram_pageflags flag)
108 {
109 	zram->table[index].value &= ~BIT(flag);
110 }
111 
112 static inline void zram_set_element(struct zram *zram, u32 index,
113 			unsigned long element)
114 {
115 	zram->table[index].element = element;
116 }
117 
118 static unsigned long zram_get_element(struct zram *zram, u32 index)
119 {
120 	return zram->table[index].element;
121 }
122 
123 static size_t zram_get_obj_size(struct zram *zram, u32 index)
124 {
125 	return zram->table[index].value & (BIT(ZRAM_FLAG_SHIFT) - 1);
126 }
127 
128 static void zram_set_obj_size(struct zram *zram,
129 					u32 index, size_t size)
130 {
131 	unsigned long flags = zram->table[index].value >> ZRAM_FLAG_SHIFT;
132 
133 	zram->table[index].value = (flags << ZRAM_FLAG_SHIFT) | size;
134 }
135 
136 #if PAGE_SIZE != 4096
137 static inline bool is_partial_io(struct bio_vec *bvec)
138 {
139 	return bvec->bv_len != PAGE_SIZE;
140 }
141 #else
142 static inline bool is_partial_io(struct bio_vec *bvec)
143 {
144 	return false;
145 }
146 #endif
147 
148 /*
149  * Check if request is within bounds and aligned on zram logical blocks.
150  */
151 static inline bool valid_io_request(struct zram *zram,
152 		sector_t start, unsigned int size)
153 {
154 	u64 end, bound;
155 
156 	/* unaligned request */
157 	if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
158 		return false;
159 	if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
160 		return false;
161 
162 	end = start + (size >> SECTOR_SHIFT);
163 	bound = zram->disksize >> SECTOR_SHIFT;
164 	/* out of range range */
165 	if (unlikely(start >= bound || end > bound || start > end))
166 		return false;
167 
168 	/* I/O request is valid */
169 	return true;
170 }
171 
172 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
173 {
174 	*index  += (*offset + bvec->bv_len) / PAGE_SIZE;
175 	*offset = (*offset + bvec->bv_len) % PAGE_SIZE;
176 }
177 
178 static inline void update_used_max(struct zram *zram,
179 					const unsigned long pages)
180 {
181 	unsigned long old_max, cur_max;
182 
183 	old_max = atomic_long_read(&zram->stats.max_used_pages);
184 
185 	do {
186 		cur_max = old_max;
187 		if (pages > cur_max)
188 			old_max = atomic_long_cmpxchg(
189 				&zram->stats.max_used_pages, cur_max, pages);
190 	} while (old_max != cur_max);
191 }
192 
193 static inline void zram_fill_page(void *ptr, unsigned long len,
194 					unsigned long value)
195 {
196 	WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
197 	memset_l(ptr, value, len / sizeof(unsigned long));
198 }
199 
200 static bool page_same_filled(void *ptr, unsigned long *element)
201 {
202 	unsigned int pos;
203 	unsigned long *page;
204 	unsigned long val;
205 
206 	page = (unsigned long *)ptr;
207 	val = page[0];
208 
209 	for (pos = 1; pos < PAGE_SIZE / sizeof(*page); pos++) {
210 		if (val != page[pos])
211 			return false;
212 	}
213 
214 	*element = val;
215 
216 	return true;
217 }
218 
219 static ssize_t initstate_show(struct device *dev,
220 		struct device_attribute *attr, char *buf)
221 {
222 	u32 val;
223 	struct zram *zram = dev_to_zram(dev);
224 
225 	down_read(&zram->init_lock);
226 	val = init_done(zram);
227 	up_read(&zram->init_lock);
228 
229 	return scnprintf(buf, PAGE_SIZE, "%u\n", val);
230 }
231 
232 static ssize_t disksize_show(struct device *dev,
233 		struct device_attribute *attr, char *buf)
234 {
235 	struct zram *zram = dev_to_zram(dev);
236 
237 	return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
238 }
239 
240 static ssize_t mem_limit_store(struct device *dev,
241 		struct device_attribute *attr, const char *buf, size_t len)
242 {
243 	u64 limit;
244 	char *tmp;
245 	struct zram *zram = dev_to_zram(dev);
246 
247 	limit = memparse(buf, &tmp);
248 	if (buf == tmp) /* no chars parsed, invalid input */
249 		return -EINVAL;
250 
251 	down_write(&zram->init_lock);
252 	zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
253 	up_write(&zram->init_lock);
254 
255 	return len;
256 }
257 
258 static ssize_t mem_used_max_store(struct device *dev,
259 		struct device_attribute *attr, const char *buf, size_t len)
260 {
261 	int err;
262 	unsigned long val;
263 	struct zram *zram = dev_to_zram(dev);
264 
265 	err = kstrtoul(buf, 10, &val);
266 	if (err || val != 0)
267 		return -EINVAL;
268 
269 	down_read(&zram->init_lock);
270 	if (init_done(zram)) {
271 		atomic_long_set(&zram->stats.max_used_pages,
272 				zs_get_total_pages(zram->mem_pool));
273 	}
274 	up_read(&zram->init_lock);
275 
276 	return len;
277 }
278 
279 #ifdef CONFIG_ZRAM_WRITEBACK
280 static bool zram_wb_enabled(struct zram *zram)
281 {
282 	return zram->backing_dev;
283 }
284 
285 static void reset_bdev(struct zram *zram)
286 {
287 	struct block_device *bdev;
288 
289 	if (!zram_wb_enabled(zram))
290 		return;
291 
292 	bdev = zram->bdev;
293 	if (zram->old_block_size)
294 		set_blocksize(bdev, zram->old_block_size);
295 	blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
296 	/* hope filp_close flush all of IO */
297 	filp_close(zram->backing_dev, NULL);
298 	zram->backing_dev = NULL;
299 	zram->old_block_size = 0;
300 	zram->bdev = NULL;
301 
302 	kvfree(zram->bitmap);
303 	zram->bitmap = NULL;
304 }
305 
306 static ssize_t backing_dev_show(struct device *dev,
307 		struct device_attribute *attr, char *buf)
308 {
309 	struct zram *zram = dev_to_zram(dev);
310 	struct file *file = zram->backing_dev;
311 	char *p;
312 	ssize_t ret;
313 
314 	down_read(&zram->init_lock);
315 	if (!zram_wb_enabled(zram)) {
316 		memcpy(buf, "none\n", 5);
317 		up_read(&zram->init_lock);
318 		return 5;
319 	}
320 
321 	p = file_path(file, buf, PAGE_SIZE - 1);
322 	if (IS_ERR(p)) {
323 		ret = PTR_ERR(p);
324 		goto out;
325 	}
326 
327 	ret = strlen(p);
328 	memmove(buf, p, ret);
329 	buf[ret++] = '\n';
330 out:
331 	up_read(&zram->init_lock);
332 	return ret;
333 }
334 
335 static ssize_t backing_dev_store(struct device *dev,
336 		struct device_attribute *attr, const char *buf, size_t len)
337 {
338 	char *file_name;
339 	struct file *backing_dev = NULL;
340 	struct inode *inode;
341 	struct address_space *mapping;
342 	unsigned int bitmap_sz, old_block_size = 0;
343 	unsigned long nr_pages, *bitmap = NULL;
344 	struct block_device *bdev = NULL;
345 	int err;
346 	struct zram *zram = dev_to_zram(dev);
347 
348 	file_name = kmalloc(PATH_MAX, GFP_KERNEL);
349 	if (!file_name)
350 		return -ENOMEM;
351 
352 	down_write(&zram->init_lock);
353 	if (init_done(zram)) {
354 		pr_info("Can't setup backing device for initialized device\n");
355 		err = -EBUSY;
356 		goto out;
357 	}
358 
359 	strlcpy(file_name, buf, len);
360 
361 	backing_dev = filp_open(file_name, O_RDWR|O_LARGEFILE, 0);
362 	if (IS_ERR(backing_dev)) {
363 		err = PTR_ERR(backing_dev);
364 		backing_dev = NULL;
365 		goto out;
366 	}
367 
368 	mapping = backing_dev->f_mapping;
369 	inode = mapping->host;
370 
371 	/* Support only block device in this moment */
372 	if (!S_ISBLK(inode->i_mode)) {
373 		err = -ENOTBLK;
374 		goto out;
375 	}
376 
377 	bdev = bdgrab(I_BDEV(inode));
378 	err = blkdev_get(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL, zram);
379 	if (err < 0)
380 		goto out;
381 
382 	nr_pages = i_size_read(inode) >> PAGE_SHIFT;
383 	bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
384 	bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
385 	if (!bitmap) {
386 		err = -ENOMEM;
387 		goto out;
388 	}
389 
390 	old_block_size = block_size(bdev);
391 	err = set_blocksize(bdev, PAGE_SIZE);
392 	if (err)
393 		goto out;
394 
395 	reset_bdev(zram);
396 	spin_lock_init(&zram->bitmap_lock);
397 
398 	zram->old_block_size = old_block_size;
399 	zram->bdev = bdev;
400 	zram->backing_dev = backing_dev;
401 	zram->bitmap = bitmap;
402 	zram->nr_pages = nr_pages;
403 	up_write(&zram->init_lock);
404 
405 	pr_info("setup backing device %s\n", file_name);
406 	kfree(file_name);
407 
408 	return len;
409 out:
410 	if (bitmap)
411 		kvfree(bitmap);
412 
413 	if (bdev)
414 		blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
415 
416 	if (backing_dev)
417 		filp_close(backing_dev, NULL);
418 
419 	up_write(&zram->init_lock);
420 
421 	kfree(file_name);
422 
423 	return err;
424 }
425 
426 static unsigned long get_entry_bdev(struct zram *zram)
427 {
428 	unsigned long entry;
429 
430 	spin_lock(&zram->bitmap_lock);
431 	/* skip 0 bit to confuse zram.handle = 0 */
432 	entry = find_next_zero_bit(zram->bitmap, zram->nr_pages, 1);
433 	if (entry == zram->nr_pages) {
434 		spin_unlock(&zram->bitmap_lock);
435 		return 0;
436 	}
437 
438 	set_bit(entry, zram->bitmap);
439 	spin_unlock(&zram->bitmap_lock);
440 
441 	return entry;
442 }
443 
444 static void put_entry_bdev(struct zram *zram, unsigned long entry)
445 {
446 	int was_set;
447 
448 	spin_lock(&zram->bitmap_lock);
449 	was_set = test_and_clear_bit(entry, zram->bitmap);
450 	spin_unlock(&zram->bitmap_lock);
451 	WARN_ON_ONCE(!was_set);
452 }
453 
454 static void zram_page_end_io(struct bio *bio)
455 {
456 	struct page *page = bio_first_page_all(bio);
457 
458 	page_endio(page, op_is_write(bio_op(bio)),
459 			blk_status_to_errno(bio->bi_status));
460 	bio_put(bio);
461 }
462 
463 /*
464  * Returns 1 if the submission is successful.
465  */
466 static int read_from_bdev_async(struct zram *zram, struct bio_vec *bvec,
467 			unsigned long entry, struct bio *parent)
468 {
469 	struct bio *bio;
470 
471 	bio = bio_alloc(GFP_ATOMIC, 1);
472 	if (!bio)
473 		return -ENOMEM;
474 
475 	bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
476 	bio_set_dev(bio, zram->bdev);
477 	if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset)) {
478 		bio_put(bio);
479 		return -EIO;
480 	}
481 
482 	if (!parent) {
483 		bio->bi_opf = REQ_OP_READ;
484 		bio->bi_end_io = zram_page_end_io;
485 	} else {
486 		bio->bi_opf = parent->bi_opf;
487 		bio_chain(bio, parent);
488 	}
489 
490 	submit_bio(bio);
491 	return 1;
492 }
493 
494 struct zram_work {
495 	struct work_struct work;
496 	struct zram *zram;
497 	unsigned long entry;
498 	struct bio *bio;
499 };
500 
501 #if PAGE_SIZE != 4096
502 static void zram_sync_read(struct work_struct *work)
503 {
504 	struct bio_vec bvec;
505 	struct zram_work *zw = container_of(work, struct zram_work, work);
506 	struct zram *zram = zw->zram;
507 	unsigned long entry = zw->entry;
508 	struct bio *bio = zw->bio;
509 
510 	read_from_bdev_async(zram, &bvec, entry, bio);
511 }
512 
513 /*
514  * Block layer want one ->make_request_fn to be active at a time
515  * so if we use chained IO with parent IO in same context,
516  * it's a deadlock. To avoid, it, it uses worker thread context.
517  */
518 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
519 				unsigned long entry, struct bio *bio)
520 {
521 	struct zram_work work;
522 
523 	work.zram = zram;
524 	work.entry = entry;
525 	work.bio = bio;
526 
527 	INIT_WORK_ONSTACK(&work.work, zram_sync_read);
528 	queue_work(system_unbound_wq, &work.work);
529 	flush_work(&work.work);
530 	destroy_work_on_stack(&work.work);
531 
532 	return 1;
533 }
534 #else
535 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
536 				unsigned long entry, struct bio *bio)
537 {
538 	WARN_ON(1);
539 	return -EIO;
540 }
541 #endif
542 
543 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
544 			unsigned long entry, struct bio *parent, bool sync)
545 {
546 	if (sync)
547 		return read_from_bdev_sync(zram, bvec, entry, parent);
548 	else
549 		return read_from_bdev_async(zram, bvec, entry, parent);
550 }
551 
552 static int write_to_bdev(struct zram *zram, struct bio_vec *bvec,
553 					u32 index, struct bio *parent,
554 					unsigned long *pentry)
555 {
556 	struct bio *bio;
557 	unsigned long entry;
558 
559 	bio = bio_alloc(GFP_ATOMIC, 1);
560 	if (!bio)
561 		return -ENOMEM;
562 
563 	entry = get_entry_bdev(zram);
564 	if (!entry) {
565 		bio_put(bio);
566 		return -ENOSPC;
567 	}
568 
569 	bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
570 	bio_set_dev(bio, zram->bdev);
571 	if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len,
572 					bvec->bv_offset)) {
573 		bio_put(bio);
574 		put_entry_bdev(zram, entry);
575 		return -EIO;
576 	}
577 
578 	if (!parent) {
579 		bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
580 		bio->bi_end_io = zram_page_end_io;
581 	} else {
582 		bio->bi_opf = parent->bi_opf;
583 		bio_chain(bio, parent);
584 	}
585 
586 	submit_bio(bio);
587 	*pentry = entry;
588 
589 	return 0;
590 }
591 
592 static void zram_wb_clear(struct zram *zram, u32 index)
593 {
594 	unsigned long entry;
595 
596 	zram_clear_flag(zram, index, ZRAM_WB);
597 	entry = zram_get_element(zram, index);
598 	zram_set_element(zram, index, 0);
599 	put_entry_bdev(zram, entry);
600 }
601 
602 #else
603 static bool zram_wb_enabled(struct zram *zram) { return false; }
604 static inline void reset_bdev(struct zram *zram) {};
605 static int write_to_bdev(struct zram *zram, struct bio_vec *bvec,
606 					u32 index, struct bio *parent,
607 					unsigned long *pentry)
608 
609 {
610 	return -EIO;
611 }
612 
613 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
614 			unsigned long entry, struct bio *parent, bool sync)
615 {
616 	return -EIO;
617 }
618 static void zram_wb_clear(struct zram *zram, u32 index) {}
619 #endif
620 
621 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
622 
623 static struct dentry *zram_debugfs_root;
624 
625 static void zram_debugfs_create(void)
626 {
627 	zram_debugfs_root = debugfs_create_dir("zram", NULL);
628 }
629 
630 static void zram_debugfs_destroy(void)
631 {
632 	debugfs_remove_recursive(zram_debugfs_root);
633 }
634 
635 static void zram_accessed(struct zram *zram, u32 index)
636 {
637 	zram->table[index].ac_time = ktime_get_boottime();
638 }
639 
640 static void zram_reset_access(struct zram *zram, u32 index)
641 {
642 	zram->table[index].ac_time = 0;
643 }
644 
645 static ssize_t read_block_state(struct file *file, char __user *buf,
646 				size_t count, loff_t *ppos)
647 {
648 	char *kbuf;
649 	ssize_t index, written = 0;
650 	struct zram *zram = file->private_data;
651 	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
652 	struct timespec64 ts;
653 
654 	kbuf = kvmalloc(count, GFP_KERNEL);
655 	if (!kbuf)
656 		return -ENOMEM;
657 
658 	down_read(&zram->init_lock);
659 	if (!init_done(zram)) {
660 		up_read(&zram->init_lock);
661 		kvfree(kbuf);
662 		return -EINVAL;
663 	}
664 
665 	for (index = *ppos; index < nr_pages; index++) {
666 		int copied;
667 
668 		zram_slot_lock(zram, index);
669 		if (!zram_allocated(zram, index))
670 			goto next;
671 
672 		ts = ktime_to_timespec64(zram->table[index].ac_time);
673 		copied = snprintf(kbuf + written, count,
674 			"%12zd %12lld.%06lu %c%c%c\n",
675 			index, (s64)ts.tv_sec,
676 			ts.tv_nsec / NSEC_PER_USEC,
677 			zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
678 			zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
679 			zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.');
680 
681 		if (count < copied) {
682 			zram_slot_unlock(zram, index);
683 			break;
684 		}
685 		written += copied;
686 		count -= copied;
687 next:
688 		zram_slot_unlock(zram, index);
689 		*ppos += 1;
690 	}
691 
692 	up_read(&zram->init_lock);
693 	if (copy_to_user(buf, kbuf, written))
694 		written = -EFAULT;
695 	kvfree(kbuf);
696 
697 	return written;
698 }
699 
700 static const struct file_operations proc_zram_block_state_op = {
701 	.open = simple_open,
702 	.read = read_block_state,
703 	.llseek = default_llseek,
704 };
705 
706 static void zram_debugfs_register(struct zram *zram)
707 {
708 	if (!zram_debugfs_root)
709 		return;
710 
711 	zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
712 						zram_debugfs_root);
713 	debugfs_create_file("block_state", 0400, zram->debugfs_dir,
714 				zram, &proc_zram_block_state_op);
715 }
716 
717 static void zram_debugfs_unregister(struct zram *zram)
718 {
719 	debugfs_remove_recursive(zram->debugfs_dir);
720 }
721 #else
722 static void zram_debugfs_create(void) {};
723 static void zram_debugfs_destroy(void) {};
724 static void zram_accessed(struct zram *zram, u32 index) {};
725 static void zram_reset_access(struct zram *zram, u32 index) {};
726 static void zram_debugfs_register(struct zram *zram) {};
727 static void zram_debugfs_unregister(struct zram *zram) {};
728 #endif
729 
730 /*
731  * We switched to per-cpu streams and this attr is not needed anymore.
732  * However, we will keep it around for some time, because:
733  * a) we may revert per-cpu streams in the future
734  * b) it's visible to user space and we need to follow our 2 years
735  *    retirement rule; but we already have a number of 'soon to be
736  *    altered' attrs, so max_comp_streams need to wait for the next
737  *    layoff cycle.
738  */
739 static ssize_t max_comp_streams_show(struct device *dev,
740 		struct device_attribute *attr, char *buf)
741 {
742 	return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
743 }
744 
745 static ssize_t max_comp_streams_store(struct device *dev,
746 		struct device_attribute *attr, const char *buf, size_t len)
747 {
748 	return len;
749 }
750 
751 static ssize_t comp_algorithm_show(struct device *dev,
752 		struct device_attribute *attr, char *buf)
753 {
754 	size_t sz;
755 	struct zram *zram = dev_to_zram(dev);
756 
757 	down_read(&zram->init_lock);
758 	sz = zcomp_available_show(zram->compressor, buf);
759 	up_read(&zram->init_lock);
760 
761 	return sz;
762 }
763 
764 static ssize_t comp_algorithm_store(struct device *dev,
765 		struct device_attribute *attr, const char *buf, size_t len)
766 {
767 	struct zram *zram = dev_to_zram(dev);
768 	char compressor[ARRAY_SIZE(zram->compressor)];
769 	size_t sz;
770 
771 	strlcpy(compressor, buf, sizeof(compressor));
772 	/* ignore trailing newline */
773 	sz = strlen(compressor);
774 	if (sz > 0 && compressor[sz - 1] == '\n')
775 		compressor[sz - 1] = 0x00;
776 
777 	if (!zcomp_available_algorithm(compressor))
778 		return -EINVAL;
779 
780 	down_write(&zram->init_lock);
781 	if (init_done(zram)) {
782 		up_write(&zram->init_lock);
783 		pr_info("Can't change algorithm for initialized device\n");
784 		return -EBUSY;
785 	}
786 
787 	strcpy(zram->compressor, compressor);
788 	up_write(&zram->init_lock);
789 	return len;
790 }
791 
792 static ssize_t compact_store(struct device *dev,
793 		struct device_attribute *attr, const char *buf, size_t len)
794 {
795 	struct zram *zram = dev_to_zram(dev);
796 
797 	down_read(&zram->init_lock);
798 	if (!init_done(zram)) {
799 		up_read(&zram->init_lock);
800 		return -EINVAL;
801 	}
802 
803 	zs_compact(zram->mem_pool);
804 	up_read(&zram->init_lock);
805 
806 	return len;
807 }
808 
809 static ssize_t io_stat_show(struct device *dev,
810 		struct device_attribute *attr, char *buf)
811 {
812 	struct zram *zram = dev_to_zram(dev);
813 	ssize_t ret;
814 
815 	down_read(&zram->init_lock);
816 	ret = scnprintf(buf, PAGE_SIZE,
817 			"%8llu %8llu %8llu %8llu\n",
818 			(u64)atomic64_read(&zram->stats.failed_reads),
819 			(u64)atomic64_read(&zram->stats.failed_writes),
820 			(u64)atomic64_read(&zram->stats.invalid_io),
821 			(u64)atomic64_read(&zram->stats.notify_free));
822 	up_read(&zram->init_lock);
823 
824 	return ret;
825 }
826 
827 static ssize_t mm_stat_show(struct device *dev,
828 		struct device_attribute *attr, char *buf)
829 {
830 	struct zram *zram = dev_to_zram(dev);
831 	struct zs_pool_stats pool_stats;
832 	u64 orig_size, mem_used = 0;
833 	long max_used;
834 	ssize_t ret;
835 
836 	memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
837 
838 	down_read(&zram->init_lock);
839 	if (init_done(zram)) {
840 		mem_used = zs_get_total_pages(zram->mem_pool);
841 		zs_pool_stats(zram->mem_pool, &pool_stats);
842 	}
843 
844 	orig_size = atomic64_read(&zram->stats.pages_stored);
845 	max_used = atomic_long_read(&zram->stats.max_used_pages);
846 
847 	ret = scnprintf(buf, PAGE_SIZE,
848 			"%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu\n",
849 			orig_size << PAGE_SHIFT,
850 			(u64)atomic64_read(&zram->stats.compr_data_size),
851 			mem_used << PAGE_SHIFT,
852 			zram->limit_pages << PAGE_SHIFT,
853 			max_used << PAGE_SHIFT,
854 			(u64)atomic64_read(&zram->stats.same_pages),
855 			pool_stats.pages_compacted,
856 			(u64)atomic64_read(&zram->stats.huge_pages));
857 	up_read(&zram->init_lock);
858 
859 	return ret;
860 }
861 
862 static ssize_t debug_stat_show(struct device *dev,
863 		struct device_attribute *attr, char *buf)
864 {
865 	int version = 1;
866 	struct zram *zram = dev_to_zram(dev);
867 	ssize_t ret;
868 
869 	down_read(&zram->init_lock);
870 	ret = scnprintf(buf, PAGE_SIZE,
871 			"version: %d\n%8llu\n",
872 			version,
873 			(u64)atomic64_read(&zram->stats.writestall));
874 	up_read(&zram->init_lock);
875 
876 	return ret;
877 }
878 
879 static DEVICE_ATTR_RO(io_stat);
880 static DEVICE_ATTR_RO(mm_stat);
881 static DEVICE_ATTR_RO(debug_stat);
882 
883 static void zram_meta_free(struct zram *zram, u64 disksize)
884 {
885 	size_t num_pages = disksize >> PAGE_SHIFT;
886 	size_t index;
887 
888 	/* Free all pages that are still in this zram device */
889 	for (index = 0; index < num_pages; index++)
890 		zram_free_page(zram, index);
891 
892 	zs_destroy_pool(zram->mem_pool);
893 	vfree(zram->table);
894 }
895 
896 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
897 {
898 	size_t num_pages;
899 
900 	num_pages = disksize >> PAGE_SHIFT;
901 	zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
902 	if (!zram->table)
903 		return false;
904 
905 	zram->mem_pool = zs_create_pool(zram->disk->disk_name);
906 	if (!zram->mem_pool) {
907 		vfree(zram->table);
908 		return false;
909 	}
910 
911 	if (!huge_class_size)
912 		huge_class_size = zs_huge_class_size(zram->mem_pool);
913 	return true;
914 }
915 
916 /*
917  * To protect concurrent access to the same index entry,
918  * caller should hold this table index entry's bit_spinlock to
919  * indicate this index entry is accessing.
920  */
921 static void zram_free_page(struct zram *zram, size_t index)
922 {
923 	unsigned long handle;
924 
925 	zram_reset_access(zram, index);
926 
927 	if (zram_test_flag(zram, index, ZRAM_HUGE)) {
928 		zram_clear_flag(zram, index, ZRAM_HUGE);
929 		atomic64_dec(&zram->stats.huge_pages);
930 	}
931 
932 	if (zram_wb_enabled(zram) && zram_test_flag(zram, index, ZRAM_WB)) {
933 		zram_wb_clear(zram, index);
934 		atomic64_dec(&zram->stats.pages_stored);
935 		return;
936 	}
937 
938 	/*
939 	 * No memory is allocated for same element filled pages.
940 	 * Simply clear same page flag.
941 	 */
942 	if (zram_test_flag(zram, index, ZRAM_SAME)) {
943 		zram_clear_flag(zram, index, ZRAM_SAME);
944 		zram_set_element(zram, index, 0);
945 		atomic64_dec(&zram->stats.same_pages);
946 		atomic64_dec(&zram->stats.pages_stored);
947 		return;
948 	}
949 
950 	handle = zram_get_handle(zram, index);
951 	if (!handle)
952 		return;
953 
954 	zs_free(zram->mem_pool, handle);
955 
956 	atomic64_sub(zram_get_obj_size(zram, index),
957 			&zram->stats.compr_data_size);
958 	atomic64_dec(&zram->stats.pages_stored);
959 
960 	zram_set_handle(zram, index, 0);
961 	zram_set_obj_size(zram, index, 0);
962 }
963 
964 static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index,
965 				struct bio *bio, bool partial_io)
966 {
967 	int ret;
968 	unsigned long handle;
969 	unsigned int size;
970 	void *src, *dst;
971 
972 	if (zram_wb_enabled(zram)) {
973 		zram_slot_lock(zram, index);
974 		if (zram_test_flag(zram, index, ZRAM_WB)) {
975 			struct bio_vec bvec;
976 
977 			zram_slot_unlock(zram, index);
978 
979 			bvec.bv_page = page;
980 			bvec.bv_len = PAGE_SIZE;
981 			bvec.bv_offset = 0;
982 			return read_from_bdev(zram, &bvec,
983 					zram_get_element(zram, index),
984 					bio, partial_io);
985 		}
986 		zram_slot_unlock(zram, index);
987 	}
988 
989 	zram_slot_lock(zram, index);
990 	handle = zram_get_handle(zram, index);
991 	if (!handle || zram_test_flag(zram, index, ZRAM_SAME)) {
992 		unsigned long value;
993 		void *mem;
994 
995 		value = handle ? zram_get_element(zram, index) : 0;
996 		mem = kmap_atomic(page);
997 		zram_fill_page(mem, PAGE_SIZE, value);
998 		kunmap_atomic(mem);
999 		zram_slot_unlock(zram, index);
1000 		return 0;
1001 	}
1002 
1003 	size = zram_get_obj_size(zram, index);
1004 
1005 	src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
1006 	if (size == PAGE_SIZE) {
1007 		dst = kmap_atomic(page);
1008 		memcpy(dst, src, PAGE_SIZE);
1009 		kunmap_atomic(dst);
1010 		ret = 0;
1011 	} else {
1012 		struct zcomp_strm *zstrm = zcomp_stream_get(zram->comp);
1013 
1014 		dst = kmap_atomic(page);
1015 		ret = zcomp_decompress(zstrm, src, size, dst);
1016 		kunmap_atomic(dst);
1017 		zcomp_stream_put(zram->comp);
1018 	}
1019 	zs_unmap_object(zram->mem_pool, handle);
1020 	zram_slot_unlock(zram, index);
1021 
1022 	/* Should NEVER happen. Return bio error if it does. */
1023 	if (unlikely(ret))
1024 		pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1025 
1026 	return ret;
1027 }
1028 
1029 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1030 				u32 index, int offset, struct bio *bio)
1031 {
1032 	int ret;
1033 	struct page *page;
1034 
1035 	page = bvec->bv_page;
1036 	if (is_partial_io(bvec)) {
1037 		/* Use a temporary buffer to decompress the page */
1038 		page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1039 		if (!page)
1040 			return -ENOMEM;
1041 	}
1042 
1043 	ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec));
1044 	if (unlikely(ret))
1045 		goto out;
1046 
1047 	if (is_partial_io(bvec)) {
1048 		void *dst = kmap_atomic(bvec->bv_page);
1049 		void *src = kmap_atomic(page);
1050 
1051 		memcpy(dst + bvec->bv_offset, src + offset, bvec->bv_len);
1052 		kunmap_atomic(src);
1053 		kunmap_atomic(dst);
1054 	}
1055 out:
1056 	if (is_partial_io(bvec))
1057 		__free_page(page);
1058 
1059 	return ret;
1060 }
1061 
1062 static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1063 				u32 index, struct bio *bio)
1064 {
1065 	int ret = 0;
1066 	unsigned long alloced_pages;
1067 	unsigned long handle = 0;
1068 	unsigned int comp_len = 0;
1069 	void *src, *dst, *mem;
1070 	struct zcomp_strm *zstrm;
1071 	struct page *page = bvec->bv_page;
1072 	unsigned long element = 0;
1073 	enum zram_pageflags flags = 0;
1074 	bool allow_wb = true;
1075 
1076 	mem = kmap_atomic(page);
1077 	if (page_same_filled(mem, &element)) {
1078 		kunmap_atomic(mem);
1079 		/* Free memory associated with this sector now. */
1080 		flags = ZRAM_SAME;
1081 		atomic64_inc(&zram->stats.same_pages);
1082 		goto out;
1083 	}
1084 	kunmap_atomic(mem);
1085 
1086 compress_again:
1087 	zstrm = zcomp_stream_get(zram->comp);
1088 	src = kmap_atomic(page);
1089 	ret = zcomp_compress(zstrm, src, &comp_len);
1090 	kunmap_atomic(src);
1091 
1092 	if (unlikely(ret)) {
1093 		zcomp_stream_put(zram->comp);
1094 		pr_err("Compression failed! err=%d\n", ret);
1095 		zs_free(zram->mem_pool, handle);
1096 		return ret;
1097 	}
1098 
1099 	if (unlikely(comp_len >= huge_class_size)) {
1100 		comp_len = PAGE_SIZE;
1101 		if (zram_wb_enabled(zram) && allow_wb) {
1102 			zcomp_stream_put(zram->comp);
1103 			ret = write_to_bdev(zram, bvec, index, bio, &element);
1104 			if (!ret) {
1105 				flags = ZRAM_WB;
1106 				ret = 1;
1107 				goto out;
1108 			}
1109 			allow_wb = false;
1110 			goto compress_again;
1111 		}
1112 	}
1113 
1114 	/*
1115 	 * handle allocation has 2 paths:
1116 	 * a) fast path is executed with preemption disabled (for
1117 	 *  per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
1118 	 *  since we can't sleep;
1119 	 * b) slow path enables preemption and attempts to allocate
1120 	 *  the page with __GFP_DIRECT_RECLAIM bit set. we have to
1121 	 *  put per-cpu compression stream and, thus, to re-do
1122 	 *  the compression once handle is allocated.
1123 	 *
1124 	 * if we have a 'non-null' handle here then we are coming
1125 	 * from the slow path and handle has already been allocated.
1126 	 */
1127 	if (!handle)
1128 		handle = zs_malloc(zram->mem_pool, comp_len,
1129 				__GFP_KSWAPD_RECLAIM |
1130 				__GFP_NOWARN |
1131 				__GFP_HIGHMEM |
1132 				__GFP_MOVABLE);
1133 	if (!handle) {
1134 		zcomp_stream_put(zram->comp);
1135 		atomic64_inc(&zram->stats.writestall);
1136 		handle = zs_malloc(zram->mem_pool, comp_len,
1137 				GFP_NOIO | __GFP_HIGHMEM |
1138 				__GFP_MOVABLE);
1139 		if (handle)
1140 			goto compress_again;
1141 		return -ENOMEM;
1142 	}
1143 
1144 	alloced_pages = zs_get_total_pages(zram->mem_pool);
1145 	update_used_max(zram, alloced_pages);
1146 
1147 	if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1148 		zcomp_stream_put(zram->comp);
1149 		zs_free(zram->mem_pool, handle);
1150 		return -ENOMEM;
1151 	}
1152 
1153 	dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1154 
1155 	src = zstrm->buffer;
1156 	if (comp_len == PAGE_SIZE)
1157 		src = kmap_atomic(page);
1158 	memcpy(dst, src, comp_len);
1159 	if (comp_len == PAGE_SIZE)
1160 		kunmap_atomic(src);
1161 
1162 	zcomp_stream_put(zram->comp);
1163 	zs_unmap_object(zram->mem_pool, handle);
1164 	atomic64_add(comp_len, &zram->stats.compr_data_size);
1165 out:
1166 	/*
1167 	 * Free memory associated with this sector
1168 	 * before overwriting unused sectors.
1169 	 */
1170 	zram_slot_lock(zram, index);
1171 	zram_free_page(zram, index);
1172 
1173 	if (comp_len == PAGE_SIZE) {
1174 		zram_set_flag(zram, index, ZRAM_HUGE);
1175 		atomic64_inc(&zram->stats.huge_pages);
1176 	}
1177 
1178 	if (flags) {
1179 		zram_set_flag(zram, index, flags);
1180 		zram_set_element(zram, index, element);
1181 	}  else {
1182 		zram_set_handle(zram, index, handle);
1183 		zram_set_obj_size(zram, index, comp_len);
1184 	}
1185 	zram_slot_unlock(zram, index);
1186 
1187 	/* Update stats */
1188 	atomic64_inc(&zram->stats.pages_stored);
1189 	return ret;
1190 }
1191 
1192 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1193 				u32 index, int offset, struct bio *bio)
1194 {
1195 	int ret;
1196 	struct page *page = NULL;
1197 	void *src;
1198 	struct bio_vec vec;
1199 
1200 	vec = *bvec;
1201 	if (is_partial_io(bvec)) {
1202 		void *dst;
1203 		/*
1204 		 * This is a partial IO. We need to read the full page
1205 		 * before to write the changes.
1206 		 */
1207 		page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1208 		if (!page)
1209 			return -ENOMEM;
1210 
1211 		ret = __zram_bvec_read(zram, page, index, bio, true);
1212 		if (ret)
1213 			goto out;
1214 
1215 		src = kmap_atomic(bvec->bv_page);
1216 		dst = kmap_atomic(page);
1217 		memcpy(dst + offset, src + bvec->bv_offset, bvec->bv_len);
1218 		kunmap_atomic(dst);
1219 		kunmap_atomic(src);
1220 
1221 		vec.bv_page = page;
1222 		vec.bv_len = PAGE_SIZE;
1223 		vec.bv_offset = 0;
1224 	}
1225 
1226 	ret = __zram_bvec_write(zram, &vec, index, bio);
1227 out:
1228 	if (is_partial_io(bvec))
1229 		__free_page(page);
1230 	return ret;
1231 }
1232 
1233 /*
1234  * zram_bio_discard - handler on discard request
1235  * @index: physical block index in PAGE_SIZE units
1236  * @offset: byte offset within physical block
1237  */
1238 static void zram_bio_discard(struct zram *zram, u32 index,
1239 			     int offset, struct bio *bio)
1240 {
1241 	size_t n = bio->bi_iter.bi_size;
1242 
1243 	/*
1244 	 * zram manages data in physical block size units. Because logical block
1245 	 * size isn't identical with physical block size on some arch, we
1246 	 * could get a discard request pointing to a specific offset within a
1247 	 * certain physical block.  Although we can handle this request by
1248 	 * reading that physiclal block and decompressing and partially zeroing
1249 	 * and re-compressing and then re-storing it, this isn't reasonable
1250 	 * because our intent with a discard request is to save memory.  So
1251 	 * skipping this logical block is appropriate here.
1252 	 */
1253 	if (offset) {
1254 		if (n <= (PAGE_SIZE - offset))
1255 			return;
1256 
1257 		n -= (PAGE_SIZE - offset);
1258 		index++;
1259 	}
1260 
1261 	while (n >= PAGE_SIZE) {
1262 		zram_slot_lock(zram, index);
1263 		zram_free_page(zram, index);
1264 		zram_slot_unlock(zram, index);
1265 		atomic64_inc(&zram->stats.notify_free);
1266 		index++;
1267 		n -= PAGE_SIZE;
1268 	}
1269 }
1270 
1271 /*
1272  * Returns errno if it has some problem. Otherwise return 0 or 1.
1273  * Returns 0 if IO request was done synchronously
1274  * Returns 1 if IO request was successfully submitted.
1275  */
1276 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
1277 			int offset, bool is_write, struct bio *bio)
1278 {
1279 	unsigned long start_time = jiffies;
1280 	int rw_acct = is_write ? REQ_OP_WRITE : REQ_OP_READ;
1281 	struct request_queue *q = zram->disk->queue;
1282 	int ret;
1283 
1284 	generic_start_io_acct(q, rw_acct, bvec->bv_len >> SECTOR_SHIFT,
1285 			&zram->disk->part0);
1286 
1287 	if (!is_write) {
1288 		atomic64_inc(&zram->stats.num_reads);
1289 		ret = zram_bvec_read(zram, bvec, index, offset, bio);
1290 		flush_dcache_page(bvec->bv_page);
1291 	} else {
1292 		atomic64_inc(&zram->stats.num_writes);
1293 		ret = zram_bvec_write(zram, bvec, index, offset, bio);
1294 	}
1295 
1296 	generic_end_io_acct(q, rw_acct, &zram->disk->part0, start_time);
1297 
1298 	zram_slot_lock(zram, index);
1299 	zram_accessed(zram, index);
1300 	zram_slot_unlock(zram, index);
1301 
1302 	if (unlikely(ret < 0)) {
1303 		if (!is_write)
1304 			atomic64_inc(&zram->stats.failed_reads);
1305 		else
1306 			atomic64_inc(&zram->stats.failed_writes);
1307 	}
1308 
1309 	return ret;
1310 }
1311 
1312 static void __zram_make_request(struct zram *zram, struct bio *bio)
1313 {
1314 	int offset;
1315 	u32 index;
1316 	struct bio_vec bvec;
1317 	struct bvec_iter iter;
1318 
1319 	index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1320 	offset = (bio->bi_iter.bi_sector &
1321 		  (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1322 
1323 	switch (bio_op(bio)) {
1324 	case REQ_OP_DISCARD:
1325 	case REQ_OP_WRITE_ZEROES:
1326 		zram_bio_discard(zram, index, offset, bio);
1327 		bio_endio(bio);
1328 		return;
1329 	default:
1330 		break;
1331 	}
1332 
1333 	bio_for_each_segment(bvec, bio, iter) {
1334 		struct bio_vec bv = bvec;
1335 		unsigned int unwritten = bvec.bv_len;
1336 
1337 		do {
1338 			bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
1339 							unwritten);
1340 			if (zram_bvec_rw(zram, &bv, index, offset,
1341 					op_is_write(bio_op(bio)), bio) < 0)
1342 				goto out;
1343 
1344 			bv.bv_offset += bv.bv_len;
1345 			unwritten -= bv.bv_len;
1346 
1347 			update_position(&index, &offset, &bv);
1348 		} while (unwritten);
1349 	}
1350 
1351 	bio_endio(bio);
1352 	return;
1353 
1354 out:
1355 	bio_io_error(bio);
1356 }
1357 
1358 /*
1359  * Handler function for all zram I/O requests.
1360  */
1361 static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio)
1362 {
1363 	struct zram *zram = queue->queuedata;
1364 
1365 	if (!valid_io_request(zram, bio->bi_iter.bi_sector,
1366 					bio->bi_iter.bi_size)) {
1367 		atomic64_inc(&zram->stats.invalid_io);
1368 		goto error;
1369 	}
1370 
1371 	__zram_make_request(zram, bio);
1372 	return BLK_QC_T_NONE;
1373 
1374 error:
1375 	bio_io_error(bio);
1376 	return BLK_QC_T_NONE;
1377 }
1378 
1379 static void zram_slot_free_notify(struct block_device *bdev,
1380 				unsigned long index)
1381 {
1382 	struct zram *zram;
1383 
1384 	zram = bdev->bd_disk->private_data;
1385 
1386 	zram_slot_lock(zram, index);
1387 	zram_free_page(zram, index);
1388 	zram_slot_unlock(zram, index);
1389 	atomic64_inc(&zram->stats.notify_free);
1390 }
1391 
1392 static int zram_rw_page(struct block_device *bdev, sector_t sector,
1393 		       struct page *page, bool is_write)
1394 {
1395 	int offset, ret;
1396 	u32 index;
1397 	struct zram *zram;
1398 	struct bio_vec bv;
1399 
1400 	if (PageTransHuge(page))
1401 		return -ENOTSUPP;
1402 	zram = bdev->bd_disk->private_data;
1403 
1404 	if (!valid_io_request(zram, sector, PAGE_SIZE)) {
1405 		atomic64_inc(&zram->stats.invalid_io);
1406 		ret = -EINVAL;
1407 		goto out;
1408 	}
1409 
1410 	index = sector >> SECTORS_PER_PAGE_SHIFT;
1411 	offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1412 
1413 	bv.bv_page = page;
1414 	bv.bv_len = PAGE_SIZE;
1415 	bv.bv_offset = 0;
1416 
1417 	ret = zram_bvec_rw(zram, &bv, index, offset, is_write, NULL);
1418 out:
1419 	/*
1420 	 * If I/O fails, just return error(ie, non-zero) without
1421 	 * calling page_endio.
1422 	 * It causes resubmit the I/O with bio request by upper functions
1423 	 * of rw_page(e.g., swap_readpage, __swap_writepage) and
1424 	 * bio->bi_end_io does things to handle the error
1425 	 * (e.g., SetPageError, set_page_dirty and extra works).
1426 	 */
1427 	if (unlikely(ret < 0))
1428 		return ret;
1429 
1430 	switch (ret) {
1431 	case 0:
1432 		page_endio(page, is_write, 0);
1433 		break;
1434 	case 1:
1435 		ret = 0;
1436 		break;
1437 	default:
1438 		WARN_ON(1);
1439 	}
1440 	return ret;
1441 }
1442 
1443 static void zram_reset_device(struct zram *zram)
1444 {
1445 	struct zcomp *comp;
1446 	u64 disksize;
1447 
1448 	down_write(&zram->init_lock);
1449 
1450 	zram->limit_pages = 0;
1451 
1452 	if (!init_done(zram)) {
1453 		up_write(&zram->init_lock);
1454 		return;
1455 	}
1456 
1457 	comp = zram->comp;
1458 	disksize = zram->disksize;
1459 	zram->disksize = 0;
1460 
1461 	set_capacity(zram->disk, 0);
1462 	part_stat_set_all(&zram->disk->part0, 0);
1463 
1464 	up_write(&zram->init_lock);
1465 	/* I/O operation under all of CPU are done so let's free */
1466 	zram_meta_free(zram, disksize);
1467 	memset(&zram->stats, 0, sizeof(zram->stats));
1468 	zcomp_destroy(comp);
1469 	reset_bdev(zram);
1470 }
1471 
1472 static ssize_t disksize_store(struct device *dev,
1473 		struct device_attribute *attr, const char *buf, size_t len)
1474 {
1475 	u64 disksize;
1476 	struct zcomp *comp;
1477 	struct zram *zram = dev_to_zram(dev);
1478 	int err;
1479 
1480 	disksize = memparse(buf, NULL);
1481 	if (!disksize)
1482 		return -EINVAL;
1483 
1484 	down_write(&zram->init_lock);
1485 	if (init_done(zram)) {
1486 		pr_info("Cannot change disksize for initialized device\n");
1487 		err = -EBUSY;
1488 		goto out_unlock;
1489 	}
1490 
1491 	disksize = PAGE_ALIGN(disksize);
1492 	if (!zram_meta_alloc(zram, disksize)) {
1493 		err = -ENOMEM;
1494 		goto out_unlock;
1495 	}
1496 
1497 	comp = zcomp_create(zram->compressor);
1498 	if (IS_ERR(comp)) {
1499 		pr_err("Cannot initialise %s compressing backend\n",
1500 				zram->compressor);
1501 		err = PTR_ERR(comp);
1502 		goto out_free_meta;
1503 	}
1504 
1505 	zram->comp = comp;
1506 	zram->disksize = disksize;
1507 	set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
1508 
1509 	revalidate_disk(zram->disk);
1510 	up_write(&zram->init_lock);
1511 
1512 	return len;
1513 
1514 out_free_meta:
1515 	zram_meta_free(zram, disksize);
1516 out_unlock:
1517 	up_write(&zram->init_lock);
1518 	return err;
1519 }
1520 
1521 static ssize_t reset_store(struct device *dev,
1522 		struct device_attribute *attr, const char *buf, size_t len)
1523 {
1524 	int ret;
1525 	unsigned short do_reset;
1526 	struct zram *zram;
1527 	struct block_device *bdev;
1528 
1529 	ret = kstrtou16(buf, 10, &do_reset);
1530 	if (ret)
1531 		return ret;
1532 
1533 	if (!do_reset)
1534 		return -EINVAL;
1535 
1536 	zram = dev_to_zram(dev);
1537 	bdev = bdget_disk(zram->disk, 0);
1538 	if (!bdev)
1539 		return -ENOMEM;
1540 
1541 	mutex_lock(&bdev->bd_mutex);
1542 	/* Do not reset an active device or claimed device */
1543 	if (bdev->bd_openers || zram->claim) {
1544 		mutex_unlock(&bdev->bd_mutex);
1545 		bdput(bdev);
1546 		return -EBUSY;
1547 	}
1548 
1549 	/* From now on, anyone can't open /dev/zram[0-9] */
1550 	zram->claim = true;
1551 	mutex_unlock(&bdev->bd_mutex);
1552 
1553 	/* Make sure all the pending I/O are finished */
1554 	fsync_bdev(bdev);
1555 	zram_reset_device(zram);
1556 	revalidate_disk(zram->disk);
1557 	bdput(bdev);
1558 
1559 	mutex_lock(&bdev->bd_mutex);
1560 	zram->claim = false;
1561 	mutex_unlock(&bdev->bd_mutex);
1562 
1563 	return len;
1564 }
1565 
1566 static int zram_open(struct block_device *bdev, fmode_t mode)
1567 {
1568 	int ret = 0;
1569 	struct zram *zram;
1570 
1571 	WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
1572 
1573 	zram = bdev->bd_disk->private_data;
1574 	/* zram was claimed to reset so open request fails */
1575 	if (zram->claim)
1576 		ret = -EBUSY;
1577 
1578 	return ret;
1579 }
1580 
1581 static const struct block_device_operations zram_devops = {
1582 	.open = zram_open,
1583 	.swap_slot_free_notify = zram_slot_free_notify,
1584 	.rw_page = zram_rw_page,
1585 	.owner = THIS_MODULE
1586 };
1587 
1588 static DEVICE_ATTR_WO(compact);
1589 static DEVICE_ATTR_RW(disksize);
1590 static DEVICE_ATTR_RO(initstate);
1591 static DEVICE_ATTR_WO(reset);
1592 static DEVICE_ATTR_WO(mem_limit);
1593 static DEVICE_ATTR_WO(mem_used_max);
1594 static DEVICE_ATTR_RW(max_comp_streams);
1595 static DEVICE_ATTR_RW(comp_algorithm);
1596 #ifdef CONFIG_ZRAM_WRITEBACK
1597 static DEVICE_ATTR_RW(backing_dev);
1598 #endif
1599 
1600 static struct attribute *zram_disk_attrs[] = {
1601 	&dev_attr_disksize.attr,
1602 	&dev_attr_initstate.attr,
1603 	&dev_attr_reset.attr,
1604 	&dev_attr_compact.attr,
1605 	&dev_attr_mem_limit.attr,
1606 	&dev_attr_mem_used_max.attr,
1607 	&dev_attr_max_comp_streams.attr,
1608 	&dev_attr_comp_algorithm.attr,
1609 #ifdef CONFIG_ZRAM_WRITEBACK
1610 	&dev_attr_backing_dev.attr,
1611 #endif
1612 	&dev_attr_io_stat.attr,
1613 	&dev_attr_mm_stat.attr,
1614 	&dev_attr_debug_stat.attr,
1615 	NULL,
1616 };
1617 
1618 static const struct attribute_group zram_disk_attr_group = {
1619 	.attrs = zram_disk_attrs,
1620 };
1621 
1622 /*
1623  * Allocate and initialize new zram device. the function returns
1624  * '>= 0' device_id upon success, and negative value otherwise.
1625  */
1626 static int zram_add(void)
1627 {
1628 	struct zram *zram;
1629 	struct request_queue *queue;
1630 	int ret, device_id;
1631 
1632 	zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1633 	if (!zram)
1634 		return -ENOMEM;
1635 
1636 	ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1637 	if (ret < 0)
1638 		goto out_free_dev;
1639 	device_id = ret;
1640 
1641 	init_rwsem(&zram->init_lock);
1642 
1643 	queue = blk_alloc_queue(GFP_KERNEL);
1644 	if (!queue) {
1645 		pr_err("Error allocating disk queue for device %d\n",
1646 			device_id);
1647 		ret = -ENOMEM;
1648 		goto out_free_idr;
1649 	}
1650 
1651 	blk_queue_make_request(queue, zram_make_request);
1652 
1653 	/* gendisk structure */
1654 	zram->disk = alloc_disk(1);
1655 	if (!zram->disk) {
1656 		pr_err("Error allocating disk structure for device %d\n",
1657 			device_id);
1658 		ret = -ENOMEM;
1659 		goto out_free_queue;
1660 	}
1661 
1662 	zram->disk->major = zram_major;
1663 	zram->disk->first_minor = device_id;
1664 	zram->disk->fops = &zram_devops;
1665 	zram->disk->queue = queue;
1666 	zram->disk->queue->queuedata = zram;
1667 	zram->disk->private_data = zram;
1668 	snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1669 
1670 	/* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1671 	set_capacity(zram->disk, 0);
1672 	/* zram devices sort of resembles non-rotational disks */
1673 	blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
1674 	blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1675 
1676 	/*
1677 	 * To ensure that we always get PAGE_SIZE aligned
1678 	 * and n*PAGE_SIZED sized I/O requests.
1679 	 */
1680 	blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1681 	blk_queue_logical_block_size(zram->disk->queue,
1682 					ZRAM_LOGICAL_BLOCK_SIZE);
1683 	blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1684 	blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1685 	zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1686 	blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1687 	blk_queue_flag_set(QUEUE_FLAG_DISCARD, zram->disk->queue);
1688 
1689 	/*
1690 	 * zram_bio_discard() will clear all logical blocks if logical block
1691 	 * size is identical with physical block size(PAGE_SIZE). But if it is
1692 	 * different, we will skip discarding some parts of logical blocks in
1693 	 * the part of the request range which isn't aligned to physical block
1694 	 * size.  So we can't ensure that all discarded logical blocks are
1695 	 * zeroed.
1696 	 */
1697 	if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1698 		blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
1699 
1700 	zram->disk->queue->backing_dev_info->capabilities |=
1701 			(BDI_CAP_STABLE_WRITES | BDI_CAP_SYNCHRONOUS_IO);
1702 	add_disk(zram->disk);
1703 
1704 	ret = sysfs_create_group(&disk_to_dev(zram->disk)->kobj,
1705 				&zram_disk_attr_group);
1706 	if (ret < 0) {
1707 		pr_err("Error creating sysfs group for device %d\n",
1708 				device_id);
1709 		goto out_free_disk;
1710 	}
1711 	strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1712 
1713 	zram_debugfs_register(zram);
1714 	pr_info("Added device: %s\n", zram->disk->disk_name);
1715 	return device_id;
1716 
1717 out_free_disk:
1718 	del_gendisk(zram->disk);
1719 	put_disk(zram->disk);
1720 out_free_queue:
1721 	blk_cleanup_queue(queue);
1722 out_free_idr:
1723 	idr_remove(&zram_index_idr, device_id);
1724 out_free_dev:
1725 	kfree(zram);
1726 	return ret;
1727 }
1728 
1729 static int zram_remove(struct zram *zram)
1730 {
1731 	struct block_device *bdev;
1732 
1733 	bdev = bdget_disk(zram->disk, 0);
1734 	if (!bdev)
1735 		return -ENOMEM;
1736 
1737 	mutex_lock(&bdev->bd_mutex);
1738 	if (bdev->bd_openers || zram->claim) {
1739 		mutex_unlock(&bdev->bd_mutex);
1740 		bdput(bdev);
1741 		return -EBUSY;
1742 	}
1743 
1744 	zram->claim = true;
1745 	mutex_unlock(&bdev->bd_mutex);
1746 
1747 	zram_debugfs_unregister(zram);
1748 	/*
1749 	 * Remove sysfs first, so no one will perform a disksize
1750 	 * store while we destroy the devices. This also helps during
1751 	 * hot_remove -- zram_reset_device() is the last holder of
1752 	 * ->init_lock, no later/concurrent disksize_store() or any
1753 	 * other sysfs handlers are possible.
1754 	 */
1755 	sysfs_remove_group(&disk_to_dev(zram->disk)->kobj,
1756 			&zram_disk_attr_group);
1757 
1758 	/* Make sure all the pending I/O are finished */
1759 	fsync_bdev(bdev);
1760 	zram_reset_device(zram);
1761 	bdput(bdev);
1762 
1763 	pr_info("Removed device: %s\n", zram->disk->disk_name);
1764 
1765 	del_gendisk(zram->disk);
1766 	blk_cleanup_queue(zram->disk->queue);
1767 	put_disk(zram->disk);
1768 	kfree(zram);
1769 	return 0;
1770 }
1771 
1772 /* zram-control sysfs attributes */
1773 
1774 /*
1775  * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
1776  * sense that reading from this file does alter the state of your system -- it
1777  * creates a new un-initialized zram device and returns back this device's
1778  * device_id (or an error code if it fails to create a new device).
1779  */
1780 static ssize_t hot_add_show(struct class *class,
1781 			struct class_attribute *attr,
1782 			char *buf)
1783 {
1784 	int ret;
1785 
1786 	mutex_lock(&zram_index_mutex);
1787 	ret = zram_add();
1788 	mutex_unlock(&zram_index_mutex);
1789 
1790 	if (ret < 0)
1791 		return ret;
1792 	return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
1793 }
1794 static CLASS_ATTR_RO(hot_add);
1795 
1796 static ssize_t hot_remove_store(struct class *class,
1797 			struct class_attribute *attr,
1798 			const char *buf,
1799 			size_t count)
1800 {
1801 	struct zram *zram;
1802 	int ret, dev_id;
1803 
1804 	/* dev_id is gendisk->first_minor, which is `int' */
1805 	ret = kstrtoint(buf, 10, &dev_id);
1806 	if (ret)
1807 		return ret;
1808 	if (dev_id < 0)
1809 		return -EINVAL;
1810 
1811 	mutex_lock(&zram_index_mutex);
1812 
1813 	zram = idr_find(&zram_index_idr, dev_id);
1814 	if (zram) {
1815 		ret = zram_remove(zram);
1816 		if (!ret)
1817 			idr_remove(&zram_index_idr, dev_id);
1818 	} else {
1819 		ret = -ENODEV;
1820 	}
1821 
1822 	mutex_unlock(&zram_index_mutex);
1823 	return ret ? ret : count;
1824 }
1825 static CLASS_ATTR_WO(hot_remove);
1826 
1827 static struct attribute *zram_control_class_attrs[] = {
1828 	&class_attr_hot_add.attr,
1829 	&class_attr_hot_remove.attr,
1830 	NULL,
1831 };
1832 ATTRIBUTE_GROUPS(zram_control_class);
1833 
1834 static struct class zram_control_class = {
1835 	.name		= "zram-control",
1836 	.owner		= THIS_MODULE,
1837 	.class_groups	= zram_control_class_groups,
1838 };
1839 
1840 static int zram_remove_cb(int id, void *ptr, void *data)
1841 {
1842 	zram_remove(ptr);
1843 	return 0;
1844 }
1845 
1846 static void destroy_devices(void)
1847 {
1848 	class_unregister(&zram_control_class);
1849 	idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
1850 	zram_debugfs_destroy();
1851 	idr_destroy(&zram_index_idr);
1852 	unregister_blkdev(zram_major, "zram");
1853 	cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1854 }
1855 
1856 static int __init zram_init(void)
1857 {
1858 	int ret;
1859 
1860 	ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
1861 				      zcomp_cpu_up_prepare, zcomp_cpu_dead);
1862 	if (ret < 0)
1863 		return ret;
1864 
1865 	ret = class_register(&zram_control_class);
1866 	if (ret) {
1867 		pr_err("Unable to register zram-control class\n");
1868 		cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1869 		return ret;
1870 	}
1871 
1872 	zram_debugfs_create();
1873 	zram_major = register_blkdev(0, "zram");
1874 	if (zram_major <= 0) {
1875 		pr_err("Unable to get major number\n");
1876 		class_unregister(&zram_control_class);
1877 		cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1878 		return -EBUSY;
1879 	}
1880 
1881 	while (num_devices != 0) {
1882 		mutex_lock(&zram_index_mutex);
1883 		ret = zram_add();
1884 		mutex_unlock(&zram_index_mutex);
1885 		if (ret < 0)
1886 			goto out_error;
1887 		num_devices--;
1888 	}
1889 
1890 	return 0;
1891 
1892 out_error:
1893 	destroy_devices();
1894 	return ret;
1895 }
1896 
1897 static void __exit zram_exit(void)
1898 {
1899 	destroy_devices();
1900 }
1901 
1902 module_init(zram_init);
1903 module_exit(zram_exit);
1904 
1905 module_param(num_devices, uint, 0);
1906 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
1907 
1908 MODULE_LICENSE("Dual BSD/GPL");
1909 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
1910 MODULE_DESCRIPTION("Compressed RAM Block Device");
1911