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