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