xref: /linux/drivers/block/zram/zram_drv.c (revision 803f6a03f243ef544d8a9fe6c9314247b34cf02b)
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 pr_fmt(fmt) "zram: " fmt
16 
17 #include <linux/module.h>
18 #include <linux/kernel.h>
19 #include <linux/bio.h>
20 #include <linux/bitops.h>
21 #include <linux/blkdev.h>
22 #include <linux/buffer_head.h>
23 #include <linux/device.h>
24 #include <linux/highmem.h>
25 #include <linux/slab.h>
26 #include <linux/backing-dev.h>
27 #include <linux/string.h>
28 #include <linux/vmalloc.h>
29 #include <linux/err.h>
30 #include <linux/idr.h>
31 #include <linux/sysfs.h>
32 #include <linux/debugfs.h>
33 #include <linux/cpuhotplug.h>
34 #include <linux/part_stat.h>
35 #include <linux/scatterlist.h>
36 #include <linux/kernel_read_file.h>
37 #include <linux/rcupdate.h>
38 
39 #include "zram_drv.h"
40 
41 static DEFINE_IDR(zram_index_idr);
42 /* idr index must be protected */
43 static DEFINE_MUTEX(zram_index_mutex);
44 
45 static int zram_major;
46 static const char *default_compressor = CONFIG_ZRAM_DEF_COMP;
47 
48 #define ZRAM_MAX_ALGO_NAME_SZ	128
49 
50 /* Module params (documentation at end) */
51 static unsigned int num_devices = 1;
52 /*
53  * Pages that compress to sizes equals or greater than this are stored
54  * uncompressed in memory.
55  */
56 static size_t huge_class_size;
57 
58 static const struct block_device_operations zram_devops;
59 
60 static void slot_free(struct zram *zram, unsigned long index);
61 
62 /*
63  * entry locking rules:
64  *
65  * 1) Lock is exclusive
66  *
67  * 2) lock() function can sleep waiting for the lock
68  *
69  * 3) Lock owner can sleep
70  *
71  * 4) Use TRY lock variant when in atomic context
72  *    - must check return value and handle locking failers
73  */
74 static __must_check bool slot_trylock(struct zram *zram, unsigned long index)
75 {
76 	unsigned long *lock = &zram->table[index].__lock;
77 
78 	if (!test_and_set_bit_lock(ZRAM_ENTRY_LOCK_BIT, lock)) {
79 		mutex_acquire(&zram->table_lock_map, 0, 1, _RET_IP_);
80 		lock_acquired(&zram->table_lock_map, _RET_IP_);
81 		return true;
82 	}
83 
84 	return false;
85 }
86 
87 static void slot_lock(struct zram *zram, unsigned long index)
88 {
89 	unsigned long *lock = &zram->table[index].__lock;
90 
91 	mutex_acquire(&zram->table_lock_map, 0, 0, _RET_IP_);
92 	wait_on_bit_lock(lock, ZRAM_ENTRY_LOCK_BIT, TASK_UNINTERRUPTIBLE);
93 	lock_acquired(&zram->table_lock_map, _RET_IP_);
94 }
95 
96 static void slot_unlock(struct zram *zram, unsigned long index)
97 {
98 	unsigned long *lock = &zram->table[index].__lock;
99 
100 	mutex_release(&zram->table_lock_map, _RET_IP_);
101 	clear_and_wake_up_bit(ZRAM_ENTRY_LOCK_BIT, lock);
102 }
103 
104 static inline bool init_done(struct zram *zram)
105 {
106 	return zram->disksize;
107 }
108 
109 static inline struct zram *dev_to_zram(struct device *dev)
110 {
111 	return (struct zram *)dev_to_disk(dev)->private_data;
112 }
113 
114 static unsigned long get_slot_handle(struct zram *zram, unsigned long index)
115 {
116 	return zram->table[index].handle;
117 }
118 
119 static void set_slot_handle(struct zram *zram, unsigned long index,
120 			    unsigned long handle)
121 {
122 	zram->table[index].handle = handle;
123 }
124 
125 static bool test_slot_flag(struct zram *zram, unsigned long index,
126 			   enum zram_pageflags flag)
127 {
128 	return zram->table[index].attr.flags & BIT(flag);
129 }
130 
131 static void set_slot_flag(struct zram *zram, unsigned long index,
132 			  enum zram_pageflags flag)
133 {
134 	zram->table[index].attr.flags |= BIT(flag);
135 }
136 
137 static void clear_slot_flag(struct zram *zram, unsigned long index,
138 			    enum zram_pageflags flag)
139 {
140 	zram->table[index].attr.flags &= ~BIT(flag);
141 }
142 
143 static size_t get_slot_size(struct zram *zram, unsigned long index)
144 {
145 	return zram->table[index].attr.flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
146 }
147 
148 static void set_slot_size(struct zram *zram, unsigned long index, size_t size)
149 {
150 	unsigned long flags = zram->table[index].attr.flags >> ZRAM_FLAG_SHIFT;
151 
152 	zram->table[index].attr.flags = (flags << ZRAM_FLAG_SHIFT) | size;
153 }
154 
155 static inline bool slot_allocated(struct zram *zram, unsigned long index)
156 {
157 	return get_slot_size(zram, index) ||
158 		test_slot_flag(zram, index, ZRAM_SAME) ||
159 		test_slot_flag(zram, index, ZRAM_WB);
160 }
161 
162 static inline void set_slot_comp_priority(struct zram *zram,
163 					  unsigned long index, u32 prio)
164 {
165 	prio &= ZRAM_COMP_PRIORITY_MASK;
166 	/*
167 	 * Clear previous priority value first, in case if we recompress
168 	 * further an already recompressed page
169 	 */
170 	zram->table[index].attr.flags &= ~(ZRAM_COMP_PRIORITY_MASK <<
171 					   ZRAM_COMP_PRIORITY_BIT1);
172 	zram->table[index].attr.flags |= (prio << ZRAM_COMP_PRIORITY_BIT1);
173 }
174 
175 static inline u32 get_slot_comp_priority(struct zram *zram, unsigned long index)
176 {
177 	u32 prio = zram->table[index].attr.flags >> ZRAM_COMP_PRIORITY_BIT1;
178 
179 	return prio & ZRAM_COMP_PRIORITY_MASK;
180 }
181 
182 static void mark_slot_accessed(struct zram *zram, unsigned long index)
183 {
184 	clear_slot_flag(zram, index, ZRAM_IDLE);
185 	clear_slot_flag(zram, index, ZRAM_PP_SLOT);
186 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
187 	zram->table[index].attr.ac_time = (u32)ktime_get_boottime_seconds();
188 #endif
189 }
190 
191 static inline void update_used_max(struct zram *zram, const unsigned long pages)
192 {
193 	unsigned long cur_max = atomic_long_read(&zram->stats.max_used_pages);
194 
195 	do {
196 		if (cur_max >= pages)
197 			return;
198 	} while (!atomic_long_try_cmpxchg(&zram->stats.max_used_pages,
199 					  &cur_max, pages));
200 }
201 
202 static bool zram_can_store_page(struct zram *zram)
203 {
204 	unsigned long alloced_pages;
205 
206 	alloced_pages = zs_get_total_pages(zram->mem_pool);
207 	update_used_max(zram, alloced_pages);
208 
209 	return !zram->limit_pages || alloced_pages <= zram->limit_pages;
210 }
211 
212 #if PAGE_SIZE != 4096
213 static inline bool is_partial_io(struct bio_vec *bvec)
214 {
215 	return bvec->bv_len != PAGE_SIZE;
216 }
217 #define ZRAM_PARTIAL_IO		1
218 #else
219 static inline bool is_partial_io(struct bio_vec *bvec)
220 {
221 	return false;
222 }
223 #endif
224 
225 #if defined CONFIG_ZRAM_WRITEBACK || defined CONFIG_ZRAM_MULTI_COMP
226 struct zram_pp_slot {
227 	unsigned long		index;
228 	struct list_head	entry;
229 };
230 
231 /*
232  * A post-processing bucket is, essentially, a size class, this defines
233  * the range (in bytes) of pp-slots sizes in particular bucket.
234  */
235 #define PP_BUCKET_SIZE_RANGE	64
236 #define NUM_PP_BUCKETS		((PAGE_SIZE / PP_BUCKET_SIZE_RANGE) + 1)
237 
238 struct zram_pp_ctl {
239 	struct list_head	pp_buckets[NUM_PP_BUCKETS];
240 };
241 
242 static struct zram_pp_ctl *init_pp_ctl(void)
243 {
244 	struct zram_pp_ctl *ctl;
245 	u32 idx;
246 
247 	ctl = kmalloc_obj(*ctl);
248 	if (!ctl)
249 		return NULL;
250 
251 	for (idx = 0; idx < NUM_PP_BUCKETS; idx++)
252 		INIT_LIST_HEAD(&ctl->pp_buckets[idx]);
253 	return ctl;
254 }
255 
256 static void release_pp_slot(struct zram *zram, struct zram_pp_slot *pps)
257 {
258 	list_del_init(&pps->entry);
259 
260 	slot_lock(zram, pps->index);
261 	clear_slot_flag(zram, pps->index, ZRAM_PP_SLOT);
262 	slot_unlock(zram, pps->index);
263 
264 	kfree(pps);
265 }
266 
267 static void release_pp_ctl(struct zram *zram, struct zram_pp_ctl *ctl)
268 {
269 	u32 idx;
270 
271 	if (!ctl)
272 		return;
273 
274 	for (idx = 0; idx < NUM_PP_BUCKETS; idx++) {
275 		while (!list_empty(&ctl->pp_buckets[idx])) {
276 			struct zram_pp_slot *pps;
277 
278 			pps = list_first_entry(&ctl->pp_buckets[idx],
279 					       struct zram_pp_slot,
280 					       entry);
281 			release_pp_slot(zram, pps);
282 		}
283 	}
284 
285 	kfree(ctl);
286 }
287 
288 static bool place_pp_slot(struct zram *zram, struct zram_pp_ctl *ctl,
289 			  unsigned long index)
290 {
291 	struct zram_pp_slot *pps;
292 	u32 bid;
293 
294 	pps = kmalloc_obj(*pps, GFP_NOIO | __GFP_NOWARN);
295 	if (!pps)
296 		return false;
297 
298 	INIT_LIST_HEAD(&pps->entry);
299 	pps->index = index;
300 
301 	bid = get_slot_size(zram, pps->index) / PP_BUCKET_SIZE_RANGE;
302 	list_add(&pps->entry, &ctl->pp_buckets[bid]);
303 
304 	set_slot_flag(zram, pps->index, ZRAM_PP_SLOT);
305 	return true;
306 }
307 
308 static struct zram_pp_slot *select_pp_slot(struct zram_pp_ctl *ctl)
309 {
310 	struct zram_pp_slot *pps = NULL;
311 	s32 idx = NUM_PP_BUCKETS - 1;
312 
313 	/* The higher the bucket id the more optimal slot post-processing is */
314 	while (idx >= 0) {
315 		pps = list_first_entry_or_null(&ctl->pp_buckets[idx],
316 					       struct zram_pp_slot,
317 					       entry);
318 		if (pps)
319 			break;
320 
321 		idx--;
322 	}
323 	return pps;
324 }
325 #endif
326 
327 static inline void zram_fill_page(void *ptr, unsigned long len,
328 					unsigned long value)
329 {
330 	WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
331 	memset_l(ptr, value, len / sizeof(unsigned long));
332 }
333 
334 static bool page_same_filled(void *ptr, unsigned long *element)
335 {
336 	unsigned long *page;
337 	unsigned long val;
338 	unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
339 
340 	page = (unsigned long *)ptr;
341 	val = page[0];
342 
343 	if (val != page[last_pos])
344 		return false;
345 
346 	for (pos = 1; pos < last_pos; pos++) {
347 		if (val != page[pos])
348 			return false;
349 	}
350 
351 	*element = val;
352 
353 	return true;
354 }
355 
356 static ssize_t initstate_show(struct device *dev, struct device_attribute *attr,
357 			      char *buf)
358 {
359 	u32 val;
360 	struct zram *zram = dev_to_zram(dev);
361 
362 	guard(rwsem_read)(&zram->dev_lock);
363 	val = init_done(zram);
364 
365 	return sysfs_emit(buf, "%u\n", val);
366 }
367 
368 static ssize_t disksize_show(struct device *dev,
369 		struct device_attribute *attr, char *buf)
370 {
371 	struct zram *zram = dev_to_zram(dev);
372 
373 	return sysfs_emit(buf, "%llu\n", zram->disksize);
374 }
375 
376 static ssize_t mem_limit_store(struct device *dev,
377 			       struct device_attribute *attr, const char *buf,
378 			       size_t len)
379 {
380 	u64 limit;
381 	char *tmp;
382 	struct zram *zram = dev_to_zram(dev);
383 
384 	limit = memparse(buf, &tmp);
385 	if (buf == tmp) /* no chars parsed, invalid input */
386 		return -EINVAL;
387 
388 	guard(rwsem_write)(&zram->dev_lock);
389 	zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
390 
391 	return len;
392 }
393 
394 static ssize_t mem_used_max_store(struct device *dev,
395 				  struct device_attribute *attr,
396 				  const char *buf, size_t len)
397 {
398 	int err;
399 	unsigned long val;
400 	struct zram *zram = dev_to_zram(dev);
401 
402 	err = kstrtoul(buf, 10, &val);
403 	if (err || val != 0)
404 		return -EINVAL;
405 
406 	guard(rwsem_read)(&zram->dev_lock);
407 	if (init_done(zram)) {
408 		atomic_long_set(&zram->stats.max_used_pages,
409 				zs_get_total_pages(zram->mem_pool));
410 	}
411 
412 	return len;
413 }
414 
415 /*
416  * Mark all pages which are older than or equal to cutoff as IDLE.
417  * Callers should hold the zram init lock in read mode
418  */
419 static void mark_idle(struct zram *zram, time64_t cutoff)
420 {
421 	int is_idle = 1;
422 	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
423 	unsigned long index;
424 
425 	for (index = 0; index < nr_pages; index++) {
426 		/*
427 		 * Do not mark ZRAM_SAME slots as ZRAM_IDLE, because no
428 		 * post-processing (recompress, writeback) happens to the
429 		 * ZRAM_SAME slot.
430 		 *
431 		 * And ZRAM_WB slots simply cannot be ZRAM_IDLE.
432 		 */
433 		slot_lock(zram, index);
434 		if (!slot_allocated(zram, index) ||
435 		    test_slot_flag(zram, index, ZRAM_WB) ||
436 		    test_slot_flag(zram, index, ZRAM_SAME)) {
437 			slot_unlock(zram, index);
438 			continue;
439 		}
440 
441 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
442 		is_idle = !cutoff ||
443 			cutoff > zram->table[index].attr.ac_time;
444 #endif
445 		if (is_idle)
446 			set_slot_flag(zram, index, ZRAM_IDLE);
447 		else
448 			clear_slot_flag(zram, index, ZRAM_IDLE);
449 		slot_unlock(zram, index);
450 	}
451 }
452 
453 static ssize_t idle_store(struct device *dev, struct device_attribute *attr,
454 			  const char *buf, size_t len)
455 {
456 	struct zram *zram = dev_to_zram(dev);
457 	time64_t cutoff = 0;
458 
459 	if (!sysfs_streq(buf, "all")) {
460 		/*
461 		 * If it did not parse as 'all' try to treat it as an integer
462 		 * when we have memory tracking enabled.
463 		 */
464 		time64_t uptime;
465 		u32 age_sec;
466 
467 		if (!IS_ENABLED(CONFIG_ZRAM_TRACK_ENTRY_ACTIME) ||
468 		    kstrtouint(buf, 0, &age_sec))
469 			return -EINVAL;
470 
471 		/* No slot can be older than the system uptime */
472 		uptime = ktime_get_boottime_seconds();
473 		if (age_sec >= uptime)
474 			return len;
475 
476 		cutoff = uptime - age_sec;
477 	}
478 
479 	guard(rwsem_read)(&zram->dev_lock);
480 	if (!init_done(zram))
481 		return -EINVAL;
482 
483 	/*
484 	 * A cutoff of 0 marks everything as idle, this is the
485 	 * "all" behavior.
486 	 */
487 	mark_idle(zram, cutoff);
488 	return len;
489 }
490 
491 #ifdef CONFIG_ZRAM_WRITEBACK
492 #define INVALID_BDEV_BLOCK		(~0UL)
493 
494 static int read_from_zspool_raw(struct zram *zram, struct page *page,
495 				unsigned long index);
496 static int read_from_zspool(struct zram *zram, struct page *page,
497 			    unsigned long index);
498 
499 struct zram_wb_ctl {
500 	/* idle list is accessed only by the writeback task, no concurency */
501 	struct list_head idle_reqs;
502 	/* done list is accessed concurrently, protect by done_lock */
503 	struct list_head done_reqs;
504 	wait_queue_head_t done_wait;
505 	spinlock_t done_lock;
506 	atomic_t num_inflight;
507 	struct rcu_head rcu;
508 };
509 
510 struct zram_wb_req {
511 	unsigned long blk_idx;
512 	struct page *page;
513 	struct zram_pp_slot *pps;
514 	struct bio_vec bio_vec;
515 	struct bio bio;
516 
517 	struct list_head entry;
518 };
519 
520 struct zram_rb_req {
521 	struct work_struct work;
522 	struct zram *zram;
523 	struct page *page;
524 	/* The read bio for backing device */
525 	struct bio *bio;
526 	unsigned long blk_idx;
527 	union {
528 		/* The original bio to complete (async read) */
529 		struct bio *parent;
530 		/* error status (sync read) */
531 		int error;
532 	};
533 	unsigned long index;
534 };
535 
536 #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
537 static ssize_t bd_stat_show(struct device *dev, struct device_attribute *attr,
538 			    char *buf)
539 {
540 	struct zram *zram = dev_to_zram(dev);
541 	ssize_t ret;
542 
543 	guard(rwsem_read)(&zram->dev_lock);
544 	ret = sysfs_emit(buf,
545 			 "%8llu %8llu %8llu\n",
546 			 FOUR_K((u64)atomic64_read(&zram->stats.bd_count)),
547 			 FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)),
548 			 FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)));
549 
550 	return ret;
551 }
552 
553 static ssize_t compressed_writeback_store(struct device *dev,
554 					  struct device_attribute *attr,
555 					  const char *buf, size_t len)
556 {
557 	struct zram *zram = dev_to_zram(dev);
558 	bool val;
559 
560 	if (kstrtobool(buf, &val))
561 		return -EINVAL;
562 
563 	guard(rwsem_write)(&zram->dev_lock);
564 	if (init_done(zram)) {
565 		return -EBUSY;
566 	}
567 
568 	zram->compressed_wb = val;
569 
570 	return len;
571 }
572 
573 static ssize_t compressed_writeback_show(struct device *dev,
574 					 struct device_attribute *attr,
575 					 char *buf)
576 {
577 	bool val;
578 	struct zram *zram = dev_to_zram(dev);
579 
580 	guard(rwsem_read)(&zram->dev_lock);
581 	val = zram->compressed_wb;
582 
583 	return sysfs_emit(buf, "%d\n", val);
584 }
585 
586 static ssize_t writeback_limit_enable_store(struct device *dev,
587 					    struct device_attribute *attr,
588 					    const char *buf, size_t len)
589 {
590 	struct zram *zram = dev_to_zram(dev);
591 	u64 val;
592 
593 	if (kstrtoull(buf, 10, &val))
594 		return -EINVAL;
595 
596 	guard(rwsem_write)(&zram->dev_lock);
597 	zram->wb_limit_enable = val;
598 
599 	return len;
600 }
601 
602 static ssize_t writeback_limit_enable_show(struct device *dev,
603 					   struct device_attribute *attr,
604 					   char *buf)
605 {
606 	bool val;
607 	struct zram *zram = dev_to_zram(dev);
608 
609 	guard(rwsem_read)(&zram->dev_lock);
610 	val = zram->wb_limit_enable;
611 
612 	return sysfs_emit(buf, "%d\n", val);
613 }
614 
615 static ssize_t writeback_limit_store(struct device *dev,
616 				     struct device_attribute *attr,
617 				     const char *buf, size_t len)
618 {
619 	struct zram *zram = dev_to_zram(dev);
620 	u64 val;
621 
622 	if (kstrtoull(buf, 10, &val))
623 		return -EINVAL;
624 
625 	/*
626 	 * When the page size is greater than 4KB, if bd_wb_limit is set to
627 	 * a value that is not page - size aligned, it will cause value
628 	 * wrapping. For example, when the page size is set to 16KB and
629 	 * bd_wb_limit is set to 3, a single write - back operation will
630 	 * cause bd_wb_limit to become -1. Even more terrifying is that
631 	 * bd_wb_limit is an unsigned number.
632 	 */
633 	val = rounddown(val, PAGE_SIZE / 4096);
634 
635 	guard(rwsem_write)(&zram->dev_lock);
636 	zram->bd_wb_limit = val;
637 
638 	return len;
639 }
640 
641 static ssize_t writeback_limit_show(struct device *dev,
642 				    struct device_attribute *attr, char *buf)
643 {
644 	u64 val;
645 	struct zram *zram = dev_to_zram(dev);
646 
647 	guard(rwsem_read)(&zram->dev_lock);
648 	val = zram->bd_wb_limit;
649 
650 	return sysfs_emit(buf, "%llu\n", val);
651 }
652 
653 static ssize_t writeback_batch_size_store(struct device *dev,
654 					  struct device_attribute *attr,
655 					  const char *buf, size_t len)
656 {
657 	struct zram *zram = dev_to_zram(dev);
658 	u32 val;
659 
660 	if (kstrtouint(buf, 10, &val))
661 		return -EINVAL;
662 
663 	if (!val)
664 		return -EINVAL;
665 
666 	guard(rwsem_write)(&zram->dev_lock);
667 	zram->wb_batch_size = val;
668 
669 	return len;
670 }
671 
672 static ssize_t writeback_batch_size_show(struct device *dev,
673 					 struct device_attribute *attr,
674 					 char *buf)
675 {
676 	u32 val;
677 	struct zram *zram = dev_to_zram(dev);
678 
679 	guard(rwsem_read)(&zram->dev_lock);
680 	val = zram->wb_batch_size;
681 
682 	return sysfs_emit(buf, "%u\n", val);
683 }
684 
685 static void reset_bdev(struct zram *zram)
686 {
687 	if (!zram->backing_dev)
688 		return;
689 
690 	/* hope filp_close flush all of IO */
691 	filp_close(zram->backing_dev, NULL);
692 	zram->backing_dev = NULL;
693 	zram->bdev = NULL;
694 	zram->disk->fops = &zram_devops;
695 	kvfree(zram->bitmap);
696 	zram->bitmap = NULL;
697 }
698 
699 static ssize_t backing_dev_show(struct device *dev,
700 				struct device_attribute *attr, char *buf)
701 {
702 	struct file *file;
703 	struct zram *zram = dev_to_zram(dev);
704 	char *p;
705 	ssize_t ret;
706 
707 	guard(rwsem_read)(&zram->dev_lock);
708 	file = zram->backing_dev;
709 	if (!file) {
710 		memcpy(buf, "none\n", 5);
711 		return 5;
712 	}
713 
714 	p = file_path(file, buf, PAGE_SIZE - 1);
715 	if (IS_ERR(p))
716 		return PTR_ERR(p);
717 
718 	ret = strlen(p);
719 	memmove(buf, p, ret);
720 	buf[ret++] = '\n';
721 	return ret;
722 }
723 
724 static ssize_t backing_dev_store(struct device *dev,
725 				 struct device_attribute *attr, const char *buf,
726 				 size_t len)
727 {
728 	char *file_name;
729 	size_t sz;
730 	struct file *backing_dev = NULL;
731 	struct inode *inode;
732 	unsigned int bitmap_sz;
733 	unsigned long nr_pages, *bitmap = NULL;
734 	int err;
735 	struct zram *zram = dev_to_zram(dev);
736 
737 	file_name = kmalloc(PATH_MAX, GFP_KERNEL);
738 	if (!file_name)
739 		return -ENOMEM;
740 
741 	guard(rwsem_write)(&zram->dev_lock);
742 	if (init_done(zram)) {
743 		pr_info("Can't setup backing device for initialized device\n");
744 		err = -EBUSY;
745 		goto out;
746 	}
747 
748 	strscpy(file_name, buf, PATH_MAX);
749 	/* ignore trailing newline */
750 	sz = strlen(file_name);
751 	if (sz > 0 && file_name[sz - 1] == '\n')
752 		file_name[sz - 1] = 0x00;
753 
754 	backing_dev = filp_open(file_name, O_RDWR | O_LARGEFILE | O_EXCL, 0);
755 	if (IS_ERR(backing_dev)) {
756 		err = PTR_ERR(backing_dev);
757 		backing_dev = NULL;
758 		goto out;
759 	}
760 
761 	inode = backing_dev->f_mapping->host;
762 
763 	/* Support only block device in this moment */
764 	if (!S_ISBLK(inode->i_mode)) {
765 		err = -ENOTBLK;
766 		goto out;
767 	}
768 
769 	nr_pages = i_size_read(inode) >> PAGE_SHIFT;
770 	/* Refuse to use zero sized device (also prevents self reference) */
771 	if (!nr_pages) {
772 		err = -EINVAL;
773 		goto out;
774 	}
775 
776 	bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
777 	bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
778 	if (!bitmap) {
779 		err = -ENOMEM;
780 		goto out;
781 	}
782 
783 	reset_bdev(zram);
784 
785 	zram->bdev = I_BDEV(inode);
786 	zram->backing_dev = backing_dev;
787 	zram->bitmap = bitmap;
788 	zram->nr_pages = nr_pages;
789 
790 	pr_info("setup backing device %s\n", file_name);
791 	kfree(file_name);
792 
793 	return len;
794 out:
795 	kvfree(bitmap);
796 
797 	if (backing_dev)
798 		filp_close(backing_dev, NULL);
799 
800 	kfree(file_name);
801 
802 	return err;
803 }
804 
805 static unsigned long zram_reserve_bdev_block(struct zram *zram)
806 {
807 	unsigned long blk_idx;
808 
809 	blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, 0);
810 	if (blk_idx == zram->nr_pages)
811 		return INVALID_BDEV_BLOCK;
812 
813 	set_bit(blk_idx, zram->bitmap);
814 	atomic64_inc(&zram->stats.bd_count);
815 	return blk_idx;
816 }
817 
818 static void zram_release_bdev_block(struct zram *zram, unsigned long blk_idx)
819 {
820 	int was_set;
821 
822 	was_set = test_and_clear_bit(blk_idx, zram->bitmap);
823 	WARN_ON_ONCE(!was_set);
824 	atomic64_dec(&zram->stats.bd_count);
825 }
826 
827 static void release_wb_req(struct zram_wb_req *req)
828 {
829 	__free_page(req->page);
830 	kfree(req);
831 }
832 
833 static void release_wb_ctl(struct zram_wb_ctl *wb_ctl)
834 {
835 	if (!wb_ctl)
836 		return;
837 
838 	/* We should never have inflight requests at this point */
839 	WARN_ON(atomic_read(&wb_ctl->num_inflight));
840 	WARN_ON(!list_empty(&wb_ctl->done_reqs));
841 
842 	while (!list_empty(&wb_ctl->idle_reqs)) {
843 		struct zram_wb_req *req;
844 
845 		req = list_first_entry(&wb_ctl->idle_reqs,
846 				       struct zram_wb_req, entry);
847 		list_del(&req->entry);
848 		release_wb_req(req);
849 	}
850 
851 	kfree_rcu(wb_ctl, rcu);
852 }
853 
854 static struct zram_wb_ctl *init_wb_ctl(struct zram *zram)
855 {
856 	struct zram_wb_ctl *wb_ctl;
857 	int i;
858 
859 	wb_ctl = kmalloc_obj(*wb_ctl);
860 	if (!wb_ctl)
861 		return NULL;
862 
863 	INIT_LIST_HEAD(&wb_ctl->idle_reqs);
864 	INIT_LIST_HEAD(&wb_ctl->done_reqs);
865 	atomic_set(&wb_ctl->num_inflight, 0);
866 	init_waitqueue_head(&wb_ctl->done_wait);
867 	spin_lock_init(&wb_ctl->done_lock);
868 
869 	for (i = 0; i < zram->wb_batch_size; i++) {
870 		struct zram_wb_req *req;
871 
872 		/*
873 		 * This is fatal condition only if we couldn't allocate
874 		 * any requests at all.  Otherwise we just work with the
875 		 * requests that we have successfully allocated, so that
876 		 * writeback can still proceed, even if there is only one
877 		 * request on the idle list.
878 		 */
879 		req = kzalloc_obj(*req, GFP_KERNEL | __GFP_NOWARN);
880 		if (!req)
881 			break;
882 
883 		req->page = alloc_page(GFP_KERNEL | __GFP_NOWARN);
884 		if (!req->page) {
885 			kfree(req);
886 			break;
887 		}
888 
889 		list_add(&req->entry, &wb_ctl->idle_reqs);
890 	}
891 
892 	/* We couldn't allocate any requests, so writeabck is not possible */
893 	if (list_empty(&wb_ctl->idle_reqs))
894 		goto release_wb_ctl;
895 
896 	return wb_ctl;
897 
898 release_wb_ctl:
899 	release_wb_ctl(wb_ctl);
900 	return NULL;
901 }
902 
903 static void zram_account_writeback_rollback(struct zram *zram)
904 {
905 	lockdep_assert_held_write(&zram->dev_lock);
906 
907 	if (zram->wb_limit_enable)
908 		zram->bd_wb_limit +=  1UL << (PAGE_SHIFT - 12);
909 }
910 
911 static void zram_account_writeback_submit(struct zram *zram)
912 {
913 	lockdep_assert_held_write(&zram->dev_lock);
914 
915 	if (zram->wb_limit_enable && zram->bd_wb_limit > 0)
916 		zram->bd_wb_limit -=  1UL << (PAGE_SHIFT - 12);
917 }
918 
919 static int zram_writeback_complete(struct zram *zram, struct zram_wb_req *req)
920 {
921 	unsigned long index = req->pps->index;
922 	int err;
923 
924 	err = blk_status_to_errno(req->bio.bi_status);
925 	if (err) {
926 		/*
927 		 * Failed wb requests should not be accounted in wb_limit
928 		 * (if enabled).
929 		 */
930 		zram_account_writeback_rollback(zram);
931 		zram_release_bdev_block(zram, req->blk_idx);
932 		return err;
933 	}
934 
935 	atomic64_inc(&zram->stats.bd_writes);
936 	slot_lock(zram, index);
937 	/*
938 	 * We release slot lock during writeback so slot can change under us:
939 	 * slot_free() or slot_free() and zram_write_page(). In both cases
940 	 * slot loses ZRAM_PP_SLOT flag. No concurrent post-processing can
941 	 * set ZRAM_PP_SLOT on such slots until current post-processing
942 	 * finishes.
943 	 */
944 	if (!test_slot_flag(zram, index, ZRAM_PP_SLOT)) {
945 		zram_release_bdev_block(zram, req->blk_idx);
946 		goto out;
947 	}
948 
949 	clear_slot_flag(zram, index, ZRAM_IDLE);
950 	if (test_slot_flag(zram, index, ZRAM_HUGE))
951 		atomic64_dec(&zram->stats.huge_pages);
952 	atomic64_sub(get_slot_size(zram, index), &zram->stats.compr_data_size);
953 	zs_free(zram->mem_pool, get_slot_handle(zram, index));
954 	set_slot_handle(zram, index, req->blk_idx);
955 	set_slot_flag(zram, index, ZRAM_WB);
956 
957 out:
958 	slot_unlock(zram, index);
959 	return 0;
960 }
961 
962 static void zram_writeback_endio(struct bio *bio)
963 {
964 	struct zram_wb_req *req = container_of(bio, struct zram_wb_req, bio);
965 	struct zram_wb_ctl *wb_ctl = bio->bi_private;
966 	unsigned long flags;
967 
968 	rcu_read_lock();
969 	spin_lock_irqsave(&wb_ctl->done_lock, flags);
970 	list_add(&req->entry, &wb_ctl->done_reqs);
971 	spin_unlock_irqrestore(&wb_ctl->done_lock, flags);
972 
973 	wake_up(&wb_ctl->done_wait);
974 	rcu_read_unlock();
975 }
976 
977 static void zram_submit_wb_request(struct zram *zram,
978 				   struct zram_wb_ctl *wb_ctl,
979 				   struct zram_wb_req *req)
980 {
981 	/*
982 	 * wb_limit (if enabled) should be adjusted before submission,
983 	 * so that we don't over-submit.
984 	 */
985 	zram_account_writeback_submit(zram);
986 	atomic_inc(&wb_ctl->num_inflight);
987 	req->bio.bi_private = wb_ctl;
988 	submit_bio(&req->bio);
989 }
990 
991 static int zram_complete_done_reqs(struct zram *zram,
992 				   struct zram_wb_ctl *wb_ctl)
993 {
994 	struct zram_wb_req *req;
995 	unsigned long flags;
996 	int ret = 0, err;
997 
998 	while (atomic_read(&wb_ctl->num_inflight) > 0) {
999 		spin_lock_irqsave(&wb_ctl->done_lock, flags);
1000 		req = list_first_entry_or_null(&wb_ctl->done_reqs,
1001 					       struct zram_wb_req, entry);
1002 		if (req)
1003 			list_del(&req->entry);
1004 		spin_unlock_irqrestore(&wb_ctl->done_lock, flags);
1005 
1006 		/* ->num_inflight > 0 doesn't mean we have done requests */
1007 		if (!req)
1008 			break;
1009 
1010 		err = zram_writeback_complete(zram, req);
1011 		if (err)
1012 			ret = err;
1013 
1014 		atomic_dec(&wb_ctl->num_inflight);
1015 		release_pp_slot(zram, req->pps);
1016 		req->pps = NULL;
1017 
1018 		list_add(&req->entry, &wb_ctl->idle_reqs);
1019 	}
1020 
1021 	return ret;
1022 }
1023 
1024 static struct zram_wb_req *zram_select_idle_req(struct zram_wb_ctl *wb_ctl)
1025 {
1026 	struct zram_wb_req *req;
1027 
1028 	req = list_first_entry_or_null(&wb_ctl->idle_reqs,
1029 				       struct zram_wb_req, entry);
1030 	if (req)
1031 		list_del(&req->entry);
1032 	return req;
1033 }
1034 
1035 static int zram_writeback_slots(struct zram *zram,
1036 				struct zram_pp_ctl *ctl,
1037 				struct zram_wb_ctl *wb_ctl)
1038 {
1039 	unsigned long blk_idx = INVALID_BDEV_BLOCK;
1040 	struct zram_wb_req *req = NULL;
1041 	struct zram_pp_slot *pps;
1042 	int ret = 0, err = 0;
1043 	unsigned long index = 0;
1044 
1045 	while ((pps = select_pp_slot(ctl))) {
1046 		if (zram->wb_limit_enable && !zram->bd_wb_limit) {
1047 			ret = -EIO;
1048 			break;
1049 		}
1050 
1051 		while (!req) {
1052 			req = zram_select_idle_req(wb_ctl);
1053 			if (req)
1054 				break;
1055 
1056 			wait_event(wb_ctl->done_wait,
1057 				   !list_empty(&wb_ctl->done_reqs));
1058 
1059 			err = zram_complete_done_reqs(zram, wb_ctl);
1060 			/*
1061 			 * BIO errors are not fatal, we continue and simply
1062 			 * attempt to writeback the remaining objects (pages).
1063 			 * At the same time we need to signal user-space that
1064 			 * some writes (at least one, but also could be all of
1065 			 * them) were not successful and we do so by returning
1066 			 * the most recent BIO error.
1067 			 */
1068 			if (err)
1069 				ret = err;
1070 		}
1071 
1072 		if (blk_idx == INVALID_BDEV_BLOCK) {
1073 			blk_idx = zram_reserve_bdev_block(zram);
1074 			if (blk_idx == INVALID_BDEV_BLOCK) {
1075 				ret = -ENOSPC;
1076 				break;
1077 			}
1078 		}
1079 
1080 		index = pps->index;
1081 		slot_lock(zram, index);
1082 		/*
1083 		 * scan_slots() sets ZRAM_PP_SLOT and releases slot lock, so
1084 		 * slots can change in the meantime. If slots are accessed or
1085 		 * freed they lose ZRAM_PP_SLOT flag and hence we don't
1086 		 * post-process them.
1087 		 */
1088 		if (!test_slot_flag(zram, index, ZRAM_PP_SLOT))
1089 			goto next;
1090 		if (zram->compressed_wb)
1091 			err = read_from_zspool_raw(zram, req->page, index);
1092 		else
1093 			err = read_from_zspool(zram, req->page, index);
1094 		if (err)
1095 			goto next;
1096 		slot_unlock(zram, index);
1097 
1098 		/*
1099 		 * From now on pp-slot is owned by the req, remove it from
1100 		 * its pp bucket.
1101 		 */
1102 		list_del_init(&pps->entry);
1103 
1104 		req->blk_idx = blk_idx;
1105 		req->pps = pps;
1106 		bio_init(&req->bio, zram->bdev, &req->bio_vec, 1, REQ_OP_WRITE);
1107 		req->bio.bi_iter.bi_sector = req->blk_idx * (PAGE_SIZE >> 9);
1108 		req->bio.bi_end_io = zram_writeback_endio;
1109 		__bio_add_page(&req->bio, req->page, PAGE_SIZE, 0);
1110 
1111 		zram_submit_wb_request(zram, wb_ctl, req);
1112 		blk_idx = INVALID_BDEV_BLOCK;
1113 		req = NULL;
1114 		cond_resched();
1115 		continue;
1116 
1117 next:
1118 		slot_unlock(zram, index);
1119 		release_pp_slot(zram, pps);
1120 	}
1121 
1122 	/*
1123 	 * Selected idle req, but never submitted it due to some error or
1124 	 * wb limit.
1125 	 */
1126 	if (req)
1127 		release_wb_req(req);
1128 
1129 	if (blk_idx != INVALID_BDEV_BLOCK)
1130 		zram_release_bdev_block(zram, blk_idx);
1131 
1132 	while (atomic_read(&wb_ctl->num_inflight) > 0) {
1133 		wait_event(wb_ctl->done_wait, !list_empty(&wb_ctl->done_reqs));
1134 		err = zram_complete_done_reqs(zram, wb_ctl);
1135 		if (err)
1136 			ret = err;
1137 	}
1138 
1139 	return ret;
1140 }
1141 
1142 #define PAGE_WRITEBACK			0
1143 #define HUGE_WRITEBACK			(1 << 0)
1144 #define IDLE_WRITEBACK			(1 << 1)
1145 #define INCOMPRESSIBLE_WRITEBACK	(1 << 2)
1146 
1147 static int parse_page_index(char *val, unsigned long nr_pages,
1148 			    unsigned long *lo, unsigned long *hi)
1149 {
1150 	int ret;
1151 
1152 	ret = kstrtoul(val, 10, lo);
1153 	if (ret)
1154 		return ret;
1155 	if (*lo >= nr_pages)
1156 		return -ERANGE;
1157 	*hi = *lo + 1;
1158 	return 0;
1159 }
1160 
1161 static int parse_page_indexes(char *val, unsigned long nr_pages,
1162 			      unsigned long *lo, unsigned long *hi)
1163 {
1164 	char *delim;
1165 	int ret;
1166 
1167 	delim = strchr(val, '-');
1168 	if (!delim)
1169 		return -EINVAL;
1170 
1171 	*delim = 0x00;
1172 	ret = kstrtoul(val, 10, lo);
1173 	if (ret)
1174 		return ret;
1175 	if (*lo >= nr_pages)
1176 		return -ERANGE;
1177 
1178 	ret = kstrtoul(delim + 1, 10, hi);
1179 	if (ret)
1180 		return ret;
1181 	if (*hi >= nr_pages || *lo > *hi)
1182 		return -ERANGE;
1183 	*hi += 1;
1184 	return 0;
1185 }
1186 
1187 static int parse_mode(char *val, u32 *mode)
1188 {
1189 	*mode = 0;
1190 
1191 	if (!strcmp(val, "idle"))
1192 		*mode = IDLE_WRITEBACK;
1193 	if (!strcmp(val, "huge"))
1194 		*mode = HUGE_WRITEBACK;
1195 	if (!strcmp(val, "huge_idle"))
1196 		*mode = IDLE_WRITEBACK | HUGE_WRITEBACK;
1197 	if (!strcmp(val, "incompressible"))
1198 		*mode = INCOMPRESSIBLE_WRITEBACK;
1199 
1200 	if (*mode == 0)
1201 		return -EINVAL;
1202 	return 0;
1203 }
1204 
1205 static void scan_slots_for_writeback(struct zram *zram, u32 mode,
1206 				     unsigned long lo, unsigned long hi,
1207 				     struct zram_pp_ctl *ctl)
1208 {
1209 	unsigned long index = lo;
1210 
1211 	while (index < hi) {
1212 		bool ok = true;
1213 
1214 		slot_lock(zram, index);
1215 		if (!slot_allocated(zram, index))
1216 			goto next;
1217 
1218 		if (test_slot_flag(zram, index, ZRAM_WB) ||
1219 		    test_slot_flag(zram, index, ZRAM_SAME))
1220 			goto next;
1221 
1222 		if (mode & IDLE_WRITEBACK &&
1223 		    !test_slot_flag(zram, index, ZRAM_IDLE))
1224 			goto next;
1225 		if (mode & HUGE_WRITEBACK &&
1226 		    !test_slot_flag(zram, index, ZRAM_HUGE))
1227 			goto next;
1228 		if (mode & INCOMPRESSIBLE_WRITEBACK &&
1229 		    !test_slot_flag(zram, index, ZRAM_INCOMPRESSIBLE))
1230 			goto next;
1231 
1232 		ok = place_pp_slot(zram, ctl, index);
1233 next:
1234 		slot_unlock(zram, index);
1235 		if (!ok)
1236 			break;
1237 		index++;
1238 	}
1239 }
1240 
1241 static ssize_t writeback_store(struct device *dev,
1242 			       struct device_attribute *attr,
1243 			       const char *buf, size_t len)
1244 {
1245 	struct zram *zram = dev_to_zram(dev);
1246 	unsigned long nr_pages;
1247 	unsigned long lo = 0, hi;
1248 	struct zram_pp_ctl *pp_ctl = NULL;
1249 	struct zram_wb_ctl *wb_ctl = NULL;
1250 	char *args, *param, *val;
1251 	ssize_t ret = len;
1252 	int err, mode = 0;
1253 
1254 	guard(rwsem_write)(&zram->dev_lock);
1255 	if (!init_done(zram))
1256 		return -EINVAL;
1257 
1258 	if (!zram->backing_dev)
1259 		return -ENODEV;
1260 
1261 	nr_pages = zram->disksize >> PAGE_SHIFT;
1262 	hi = nr_pages;
1263 
1264 	pp_ctl = init_pp_ctl();
1265 	if (!pp_ctl)
1266 		return -ENOMEM;
1267 
1268 	wb_ctl = init_wb_ctl(zram);
1269 	if (!wb_ctl) {
1270 		ret = -ENOMEM;
1271 		goto out;
1272 	}
1273 
1274 	args = skip_spaces(buf);
1275 	while (*args) {
1276 		args = next_arg(args, &param, &val);
1277 
1278 		/*
1279 		 * Workaround to support the old writeback interface.
1280 		 *
1281 		 * The old writeback interface has a minor inconsistency and
1282 		 * requires key=value only for page_index parameter, while the
1283 		 * writeback mode is a valueless parameter.
1284 		 *
1285 		 * This is not the case anymore and now all parameters are
1286 		 * required to have values, however, we need to support the
1287 		 * legacy writeback interface format so we check if we can
1288 		 * recognize a valueless parameter as the (legacy) writeback
1289 		 * mode.
1290 		 */
1291 		if (!val || !*val) {
1292 			err = parse_mode(param, &mode);
1293 			if (err) {
1294 				ret = err;
1295 				goto out;
1296 			}
1297 
1298 			scan_slots_for_writeback(zram, mode, lo, hi, pp_ctl);
1299 			break;
1300 		}
1301 
1302 		if (!strcmp(param, "type")) {
1303 			err = parse_mode(val, &mode);
1304 			if (err) {
1305 				ret = err;
1306 				goto out;
1307 			}
1308 
1309 			scan_slots_for_writeback(zram, mode, lo, hi, pp_ctl);
1310 			break;
1311 		}
1312 
1313 		if (!strcmp(param, "page_index")) {
1314 			err = parse_page_index(val, nr_pages, &lo, &hi);
1315 			if (err) {
1316 				ret = err;
1317 				goto out;
1318 			}
1319 
1320 			scan_slots_for_writeback(zram, mode, lo, hi, pp_ctl);
1321 			continue;
1322 		}
1323 
1324 		if (!strcmp(param, "page_indexes")) {
1325 			err = parse_page_indexes(val, nr_pages, &lo, &hi);
1326 			if (err) {
1327 				ret = err;
1328 				goto out;
1329 			}
1330 
1331 			scan_slots_for_writeback(zram, mode, lo, hi, pp_ctl);
1332 			continue;
1333 		}
1334 	}
1335 
1336 	err = zram_writeback_slots(zram, pp_ctl, wb_ctl);
1337 	if (err)
1338 		ret = err;
1339 
1340 out:
1341 	release_pp_ctl(zram, pp_ctl);
1342 	release_wb_ctl(wb_ctl);
1343 
1344 	return ret;
1345 }
1346 
1347 static int decompress_bdev_page(struct zram *zram, struct page *page,
1348 				unsigned long index)
1349 {
1350 	struct zcomp_strm *zstrm;
1351 	struct scatterlist sg[1];
1352 	unsigned int size;
1353 	int ret, prio;
1354 
1355 	slot_lock(zram, index);
1356 	/* Since slot was unlocked we need to make sure it's still ZRAM_WB */
1357 	if (!test_slot_flag(zram, index, ZRAM_WB)) {
1358 		slot_unlock(zram, index);
1359 		/* We read some stale data, zero it out */
1360 		memset_page(page, 0, 0, PAGE_SIZE);
1361 		return -EIO;
1362 	}
1363 
1364 	if (test_slot_flag(zram, index, ZRAM_HUGE)) {
1365 		slot_unlock(zram, index);
1366 		return 0;
1367 	}
1368 
1369 	size = get_slot_size(zram, index);
1370 	prio = get_slot_comp_priority(zram, index);
1371 
1372 	sg_init_table(sg, 1);
1373 	sg_set_page(sg, page, size, 0);
1374 
1375 	zstrm = zcomp_stream_get(zram->comps[prio]);
1376 	ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size,
1377 			       zstrm->local_copy);
1378 	if (!ret) {
1379 		void *dst = kmap_local_page(page);
1380 
1381 		copy_page(dst, zstrm->local_copy);
1382 		kunmap_local(dst);
1383 	}
1384 	zcomp_stream_put(zstrm);
1385 	slot_unlock(zram, index);
1386 
1387 	return ret;
1388 }
1389 
1390 static void zram_deferred_decompress(struct work_struct *w)
1391 {
1392 	struct zram_rb_req *req = container_of(w, struct zram_rb_req, work);
1393 	struct page *page = bio_first_page_all(req->bio);
1394 	struct zram *zram = req->zram;
1395 	unsigned long index = req->index;
1396 	int ret;
1397 
1398 	ret = decompress_bdev_page(zram, page, index);
1399 	if (ret)
1400 		req->parent->bi_status = BLK_STS_IOERR;
1401 
1402 	/* Decrement parent's ->remaining */
1403 	bio_endio(req->parent);
1404 	bio_put(req->bio);
1405 	kfree(req);
1406 }
1407 
1408 static void zram_async_read_endio(struct bio *bio)
1409 {
1410 	struct zram_rb_req *req = bio->bi_private;
1411 	struct zram *zram = req->zram;
1412 
1413 	if (bio->bi_status) {
1414 		req->parent->bi_status = bio->bi_status;
1415 		bio_endio(req->parent);
1416 		bio_put(bio);
1417 		kfree(req);
1418 		return;
1419 	}
1420 
1421 	/*
1422 	 * NOTE: zram_async_read_endio() is not exactly right place for this.
1423 	 * Ideally, we need to do it after ZRAM_WB check, but this requires
1424 	 * us to use wq path even on systems that don't enable compressed
1425 	 * writeback, because we cannot take slot-lock in the current context.
1426 	 *
1427 	 * Keep the existing behavior for now.
1428 	 */
1429 	if (zram->compressed_wb == false) {
1430 		/* No decompression needed, complete the parent IO */
1431 		bio_endio(req->parent);
1432 		bio_put(bio);
1433 		kfree(req);
1434 		return;
1435 	}
1436 
1437 	/*
1438 	 * zram decompression is sleepable, so we need to deffer it to
1439 	 * a preemptible context.
1440 	 */
1441 	INIT_WORK(&req->work, zram_deferred_decompress);
1442 	queue_work(system_highpri_wq, &req->work);
1443 }
1444 
1445 static int read_from_bdev_async(struct zram *zram, struct page *page,
1446 				unsigned long index, unsigned long blk_idx,
1447 				struct bio *parent)
1448 {
1449 	struct zram_rb_req *req;
1450 	struct bio *bio;
1451 
1452 	req = kmalloc_obj(*req, GFP_NOIO);
1453 	if (!req)
1454 		return -ENOMEM;
1455 
1456 	bio = bio_alloc(zram->bdev, 1, parent->bi_opf, GFP_NOIO);
1457 	if (!bio) {
1458 		kfree(req);
1459 		return -ENOMEM;
1460 	}
1461 
1462 	req->zram = zram;
1463 	req->index = index;
1464 	req->blk_idx = blk_idx;
1465 	req->bio = bio;
1466 	req->parent = parent;
1467 
1468 	bio->bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
1469 	bio->bi_private = req;
1470 	bio->bi_end_io = zram_async_read_endio;
1471 
1472 	__bio_add_page(bio, page, PAGE_SIZE, 0);
1473 	bio_inc_remaining(parent);
1474 	submit_bio(bio);
1475 
1476 	return 0;
1477 }
1478 
1479 static void zram_sync_read(struct work_struct *w)
1480 {
1481 	struct zram_rb_req *req = container_of(w, struct zram_rb_req, work);
1482 	struct bio_vec bv;
1483 	struct bio bio;
1484 
1485 	bio_init(&bio, req->zram->bdev, &bv, 1, REQ_OP_READ);
1486 	bio.bi_iter.bi_sector = req->blk_idx * (PAGE_SIZE >> 9);
1487 	__bio_add_page(&bio, req->page, PAGE_SIZE, 0);
1488 	req->error = submit_bio_wait(&bio);
1489 }
1490 
1491 /*
1492  * Block layer want one ->submit_bio to be active at a time, so if we use
1493  * chained IO with parent IO in same context, it's a deadlock. To avoid that,
1494  * use a worker thread context.
1495  */
1496 static int read_from_bdev_sync(struct zram *zram, struct page *page,
1497 			       unsigned long index, unsigned long blk_idx)
1498 {
1499 	struct zram_rb_req req;
1500 
1501 	req.page = page;
1502 	req.zram = zram;
1503 	req.blk_idx = blk_idx;
1504 
1505 	INIT_WORK_ONSTACK(&req.work, zram_sync_read);
1506 	queue_work(system_dfl_wq, &req.work);
1507 	flush_work(&req.work);
1508 	destroy_work_on_stack(&req.work);
1509 
1510 	if (req.error || zram->compressed_wb == false)
1511 		return req.error;
1512 
1513 	return decompress_bdev_page(zram, page, index);
1514 }
1515 
1516 static int read_from_bdev(struct zram *zram, struct page *page,
1517 			  unsigned long index, unsigned long blk_idx,
1518 			  struct bio *parent)
1519 {
1520 	atomic64_inc(&zram->stats.bd_reads);
1521 	if (!parent) {
1522 		if (WARN_ON_ONCE(!IS_ENABLED(ZRAM_PARTIAL_IO)))
1523 			return -EIO;
1524 		return read_from_bdev_sync(zram, page, index, blk_idx);
1525 	}
1526 	return read_from_bdev_async(zram, page, index, blk_idx, parent);
1527 }
1528 #else
1529 static inline void reset_bdev(struct zram *zram) {};
1530 static int read_from_bdev(struct zram *zram, struct page *page,
1531 			  unsigned long index, unsigned long blk_idx,
1532 			  struct bio *parent)
1533 {
1534 	return -EIO;
1535 }
1536 
1537 static void zram_release_bdev_block(struct zram *zram, unsigned long blk_idx)
1538 {
1539 }
1540 #endif
1541 
1542 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
1543 
1544 static struct dentry *zram_debugfs_root;
1545 
1546 static void zram_debugfs_create(void)
1547 {
1548 	zram_debugfs_root = debugfs_create_dir("zram", NULL);
1549 }
1550 
1551 static void zram_debugfs_destroy(void)
1552 {
1553 	debugfs_remove_recursive(zram_debugfs_root);
1554 }
1555 
1556 static ssize_t read_block_state(struct file *file, char __user *buf,
1557 				size_t count, loff_t *ppos)
1558 {
1559 	char *kbuf;
1560 	unsigned long index;
1561 	ssize_t written = 0;
1562 	struct zram *zram = file->private_data;
1563 	unsigned long nr_pages;
1564 
1565 	kbuf = kvmalloc(count, GFP_KERNEL);
1566 	if (!kbuf)
1567 		return -ENOMEM;
1568 
1569 	guard(rwsem_read)(&zram->dev_lock);
1570 	if (!init_done(zram)) {
1571 		kvfree(kbuf);
1572 		return -EINVAL;
1573 	}
1574 
1575 	nr_pages = zram->disksize >> PAGE_SHIFT;
1576 
1577 	for (index = *ppos; index < nr_pages; index++) {
1578 		int copied;
1579 
1580 		slot_lock(zram, index);
1581 		if (!slot_allocated(zram, index))
1582 			goto next;
1583 
1584 		copied = snprintf(kbuf + written, count,
1585 			"%12lu %12u.%06d %c%c%c%c%c%c\n",
1586 			index, zram->table[index].attr.ac_time, 0,
1587 			test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.',
1588 			test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.',
1589 			test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
1590 			test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
1591 			get_slot_comp_priority(zram, index) ? 'r' : '.',
1592 			test_slot_flag(zram, index,
1593 				       ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
1594 
1595 		if (count <= copied) {
1596 			slot_unlock(zram, index);
1597 			break;
1598 		}
1599 		written += copied;
1600 		count -= copied;
1601 next:
1602 		slot_unlock(zram, index);
1603 		*ppos += 1;
1604 	}
1605 
1606 	if (copy_to_user(buf, kbuf, written))
1607 		written = -EFAULT;
1608 	kvfree(kbuf);
1609 
1610 	return written;
1611 }
1612 
1613 static const struct file_operations proc_zram_block_state_op = {
1614 	.open = simple_open,
1615 	.read = read_block_state,
1616 	.llseek = default_llseek,
1617 };
1618 
1619 static void zram_debugfs_register(struct zram *zram)
1620 {
1621 	if (!zram_debugfs_root)
1622 		return;
1623 
1624 	zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
1625 						zram_debugfs_root);
1626 	debugfs_create_file("block_state", 0400, zram->debugfs_dir,
1627 				zram, &proc_zram_block_state_op);
1628 }
1629 
1630 static void zram_debugfs_unregister(struct zram *zram)
1631 {
1632 	debugfs_remove_recursive(zram->debugfs_dir);
1633 }
1634 #else
1635 static void zram_debugfs_create(void) {};
1636 static void zram_debugfs_destroy(void) {};
1637 static void zram_debugfs_register(struct zram *zram) {};
1638 static void zram_debugfs_unregister(struct zram *zram) {};
1639 #endif
1640 
1641 /* Only algo parameter given, lookup by algo name */
1642 static int lookup_algo_priority(struct zram *zram, const char *algo,
1643 				u32 min_prio)
1644 {
1645 	s32 prio;
1646 
1647 	for (prio = min_prio; prio < ZRAM_MAX_COMPS; prio++) {
1648 		if (!zram->comp_algs[prio])
1649 			continue;
1650 
1651 		if (!strcmp(zram->comp_algs[prio], algo))
1652 			return prio;
1653 	}
1654 
1655 	return -EINVAL;
1656 }
1657 
1658 /* Both algo and priority parameters given, validate them */
1659 static int validate_algo_priority(struct zram *zram, const char *algo, u32 prio)
1660 {
1661 	if (prio >= ZRAM_MAX_COMPS)
1662 		return -EINVAL;
1663 	/* No algo at given priority */
1664 	if (!zram->comp_algs[prio])
1665 		return -EINVAL;
1666 	/* A different algo at given priority */
1667 	if (strcmp(zram->comp_algs[prio], algo))
1668 		return -EINVAL;
1669 	return 0;
1670 }
1671 
1672 static void comp_algorithm_set(struct zram *zram, u32 prio, const char *alg)
1673 {
1674 	zram->comp_algs[prio] = alg;
1675 }
1676 
1677 static void comp_params_reset(struct zram *zram, u32 prio)
1678 {
1679 	struct zcomp_params *params = &zram->params[prio];
1680 
1681 	vfree(params->dict);
1682 	params->level = ZCOMP_PARAM_NOT_SET;
1683 	params->deflate.winbits = ZCOMP_PARAM_NOT_SET;
1684 	params->dict_sz = 0;
1685 	params->dict = NULL;
1686 }
1687 
1688 static int __comp_algorithm_store(struct zram *zram, u32 prio, const char *buf)
1689 {
1690 	const char *alg;
1691 	size_t sz;
1692 
1693 	sz = strlen(buf);
1694 	if (sz >= ZRAM_MAX_ALGO_NAME_SZ)
1695 		return -E2BIG;
1696 
1697 	alg = zcomp_lookup_backend_name(buf);
1698 	if (!alg)
1699 		return -EINVAL;
1700 
1701 	guard(rwsem_write)(&zram->dev_lock);
1702 	if (init_done(zram)) {
1703 		pr_info("Can't change algorithm for initialized device\n");
1704 		return -EBUSY;
1705 	}
1706 
1707 	comp_algorithm_set(zram, prio, alg);
1708 	comp_params_reset(zram, prio);
1709 	return 0;
1710 }
1711 
1712 static int comp_params_store(struct zram *zram, u32 prio, s32 level,
1713 			     const char *dict_path,
1714 			     struct deflate_params *deflate_params)
1715 {
1716 	ssize_t sz = 0;
1717 
1718 	comp_params_reset(zram, prio);
1719 
1720 	if (dict_path) {
1721 		sz = kernel_read_file_from_path(dict_path, 0,
1722 						&zram->params[prio].dict,
1723 						INT_MAX,
1724 						NULL,
1725 						READING_POLICY);
1726 		if (sz < 0) {
1727 			pr_err("failed to load dictionary %s (err=%zd)\n",
1728 			       dict_path, sz);
1729 			return sz;
1730 		}
1731 	}
1732 
1733 	zram->params[prio].dict_sz = sz;
1734 	zram->params[prio].level = level;
1735 	zram->params[prio].deflate.winbits = deflate_params->winbits;
1736 	return 0;
1737 }
1738 
1739 static ssize_t algorithm_params_store(struct device *dev,
1740 				      struct device_attribute *attr,
1741 				      const char *buf,
1742 				      size_t len)
1743 {
1744 	s32 prio = ZRAM_PRIMARY_COMP, level = ZCOMP_PARAM_NOT_SET;
1745 	char *args, *param, *val, *algo = NULL, *dict_path = NULL;
1746 	struct deflate_params deflate_params;
1747 	struct zram *zram = dev_to_zram(dev);
1748 	bool prio_param = false;
1749 	int ret;
1750 
1751 	deflate_params.winbits = ZCOMP_PARAM_NOT_SET;
1752 
1753 	args = skip_spaces(buf);
1754 	while (*args) {
1755 		args = next_arg(args, &param, &val);
1756 
1757 		if (!val || !*val)
1758 			return -EINVAL;
1759 
1760 		if (!strcmp(param, "priority")) {
1761 			prio_param = true;
1762 			ret = kstrtoint(val, 10, &prio);
1763 			if (ret)
1764 				return ret;
1765 			continue;
1766 		}
1767 
1768 		if (!strcmp(param, "level")) {
1769 			ret = kstrtoint(val, 10, &level);
1770 			if (ret)
1771 				return ret;
1772 			continue;
1773 		}
1774 
1775 		if (!strcmp(param, "algo")) {
1776 			algo = val;
1777 			continue;
1778 		}
1779 
1780 		if (!strcmp(param, "dict")) {
1781 			dict_path = val;
1782 			continue;
1783 		}
1784 
1785 		if (!strcmp(param, "deflate.winbits")) {
1786 			ret = kstrtoint(val, 10, &deflate_params.winbits);
1787 			if (ret)
1788 				return ret;
1789 			continue;
1790 		}
1791 	}
1792 
1793 	guard(rwsem_write)(&zram->dev_lock);
1794 	if (init_done(zram))
1795 		return -EBUSY;
1796 
1797 	if (prio_param) {
1798 		if (prio < ZRAM_PRIMARY_COMP || prio >= ZRAM_MAX_COMPS)
1799 			return -EINVAL;
1800 	}
1801 
1802 	if (algo && prio_param) {
1803 		ret = validate_algo_priority(zram, algo, prio);
1804 		if (ret)
1805 			return ret;
1806 	}
1807 
1808 	if (algo && !prio_param) {
1809 		prio = lookup_algo_priority(zram, algo, ZRAM_PRIMARY_COMP);
1810 		if (prio < 0)
1811 			return -EINVAL;
1812 	}
1813 
1814 	ret = comp_params_store(zram, prio, level, dict_path, &deflate_params);
1815 	return ret ? ret : len;
1816 }
1817 
1818 static ssize_t comp_algorithm_show(struct device *dev,
1819 				   struct device_attribute *attr,
1820 				   char *buf)
1821 {
1822 	struct zram *zram = dev_to_zram(dev);
1823 	ssize_t sz;
1824 
1825 	guard(rwsem_read)(&zram->dev_lock);
1826 	sz = zcomp_available_show(zram->comp_algs[ZRAM_PRIMARY_COMP], buf, 0);
1827 	return sz;
1828 }
1829 
1830 static ssize_t comp_algorithm_store(struct device *dev,
1831 				    struct device_attribute *attr,
1832 				    const char *buf,
1833 				    size_t len)
1834 {
1835 	struct zram *zram = dev_to_zram(dev);
1836 	int ret;
1837 
1838 	ret = __comp_algorithm_store(zram, ZRAM_PRIMARY_COMP, buf);
1839 	return ret ? ret : len;
1840 }
1841 
1842 #ifdef CONFIG_ZRAM_MULTI_COMP
1843 static ssize_t recomp_algorithm_show(struct device *dev,
1844 				     struct device_attribute *attr,
1845 				     char *buf)
1846 {
1847 	struct zram *zram = dev_to_zram(dev);
1848 	ssize_t sz = 0;
1849 	u32 prio;
1850 
1851 	guard(rwsem_read)(&zram->dev_lock);
1852 	for (prio = ZRAM_SECONDARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
1853 		if (!zram->comp_algs[prio])
1854 			continue;
1855 
1856 		sz += sysfs_emit_at(buf, sz, "#%d: ", prio);
1857 		sz += zcomp_available_show(zram->comp_algs[prio], buf, sz);
1858 	}
1859 	return sz;
1860 }
1861 
1862 static ssize_t recomp_algorithm_store(struct device *dev,
1863 				      struct device_attribute *attr,
1864 				      const char *buf,
1865 				      size_t len)
1866 {
1867 	struct zram *zram = dev_to_zram(dev);
1868 	int prio = ZRAM_SECONDARY_COMP;
1869 	char *args, *param, *val;
1870 	char *alg = NULL;
1871 	int ret;
1872 
1873 	args = skip_spaces(buf);
1874 	while (*args) {
1875 		args = next_arg(args, &param, &val);
1876 
1877 		if (!val || !*val)
1878 			return -EINVAL;
1879 
1880 		if (!strcmp(param, "algo")) {
1881 			alg = val;
1882 			continue;
1883 		}
1884 
1885 		if (!strcmp(param, "priority")) {
1886 			ret = kstrtoint(val, 10, &prio);
1887 			if (ret)
1888 				return ret;
1889 			continue;
1890 		}
1891 	}
1892 
1893 	if (!alg)
1894 		return -EINVAL;
1895 
1896 	if (prio < ZRAM_SECONDARY_COMP || prio >= ZRAM_MAX_COMPS)
1897 		return -EINVAL;
1898 
1899 	ret = __comp_algorithm_store(zram, prio, alg);
1900 	return ret ? ret : len;
1901 }
1902 #endif
1903 
1904 static ssize_t compact_store(struct device *dev, struct device_attribute *attr,
1905 			     const char *buf, size_t len)
1906 {
1907 	struct zram *zram = dev_to_zram(dev);
1908 
1909 	guard(rwsem_read)(&zram->dev_lock);
1910 	if (!init_done(zram))
1911 		return -EINVAL;
1912 
1913 	zs_compact(zram->mem_pool);
1914 
1915 	return len;
1916 }
1917 
1918 static ssize_t io_stat_show(struct device *dev, struct device_attribute *attr,
1919 			    char *buf)
1920 {
1921 	struct zram *zram = dev_to_zram(dev);
1922 	ssize_t ret;
1923 
1924 	guard(rwsem_read)(&zram->dev_lock);
1925 	ret = sysfs_emit(buf,
1926 			"%8llu %8llu 0 %8llu\n",
1927 			(u64)atomic64_read(&zram->stats.failed_reads),
1928 			(u64)atomic64_read(&zram->stats.failed_writes),
1929 			(u64)atomic64_read(&zram->stats.notify_free));
1930 
1931 	return ret;
1932 }
1933 
1934 static ssize_t mm_stat_show(struct device *dev, struct device_attribute *attr,
1935 			    char *buf)
1936 {
1937 	struct zram *zram = dev_to_zram(dev);
1938 	struct zs_pool_stats pool_stats;
1939 	u64 orig_size, mem_used = 0;
1940 	long max_used;
1941 	ssize_t ret;
1942 
1943 	memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1944 
1945 	guard(rwsem_read)(&zram->dev_lock);
1946 	if (init_done(zram)) {
1947 		mem_used = zs_get_total_pages(zram->mem_pool);
1948 		zs_pool_stats(zram->mem_pool, &pool_stats);
1949 	}
1950 
1951 	orig_size = atomic64_read(&zram->stats.pages_stored);
1952 	max_used = atomic_long_read(&zram->stats.max_used_pages);
1953 
1954 	ret = sysfs_emit(buf,
1955 			"%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu %8llu\n",
1956 			orig_size << PAGE_SHIFT,
1957 			(u64)atomic64_read(&zram->stats.compr_data_size),
1958 			mem_used << PAGE_SHIFT,
1959 			zram->limit_pages << PAGE_SHIFT,
1960 			max_used << PAGE_SHIFT,
1961 			(u64)atomic64_read(&zram->stats.same_pages),
1962 			atomic_long_read(&pool_stats.pages_compacted),
1963 			(u64)atomic64_read(&zram->stats.huge_pages),
1964 			(u64)atomic64_read(&zram->stats.huge_pages_since));
1965 
1966 	return ret;
1967 }
1968 
1969 static ssize_t debug_stat_show(struct device *dev,
1970 			       struct device_attribute *attr, char *buf)
1971 {
1972 	int version = 1;
1973 	struct zram *zram = dev_to_zram(dev);
1974 	ssize_t ret;
1975 
1976 	guard(rwsem_read)(&zram->dev_lock);
1977 	ret = sysfs_emit(buf,
1978 			"version: %d\n0 %8llu\n",
1979 			version,
1980 			(u64)atomic64_read(&zram->stats.miss_free));
1981 
1982 	return ret;
1983 }
1984 
1985 static void zram_meta_free(struct zram *zram, u64 disksize)
1986 {
1987 	unsigned long num_pages = disksize >> PAGE_SHIFT;
1988 	unsigned long index;
1989 
1990 	if (!zram->table)
1991 		return;
1992 
1993 	/* Free all pages that are still in this zram device */
1994 	for (index = 0; index < num_pages; index++)
1995 		slot_free(zram, index);
1996 
1997 	zs_destroy_pool(zram->mem_pool);
1998 	vfree(zram->table);
1999 	zram->table = NULL;
2000 	lockdep_unregister_key(&zram->table_lock_key);
2001 }
2002 
2003 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
2004 {
2005 	unsigned long num_pages;
2006 
2007 	num_pages = disksize >> PAGE_SHIFT;
2008 	zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
2009 	if (!zram->table)
2010 		return false;
2011 
2012 	zram->mem_pool = zs_create_pool(zram->disk->disk_name);
2013 	if (!zram->mem_pool) {
2014 		vfree(zram->table);
2015 		zram->table = NULL;
2016 		return false;
2017 	}
2018 
2019 	if (!huge_class_size)
2020 		huge_class_size = zs_huge_class_size(zram->mem_pool);
2021 
2022 	lockdep_register_key(&zram->table_lock_key);
2023 	lockdep_init_map(&zram->table_lock_map, "zram->table[index].lock", &zram->table_lock_key, 0);
2024 
2025 	return true;
2026 }
2027 
2028 static void slot_free(struct zram *zram, unsigned long index)
2029 {
2030 	unsigned long handle;
2031 
2032 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
2033 	zram->table[index].attr.ac_time = 0;
2034 #endif
2035 
2036 	clear_slot_flag(zram, index, ZRAM_IDLE);
2037 	clear_slot_flag(zram, index, ZRAM_INCOMPRESSIBLE);
2038 	clear_slot_flag(zram, index, ZRAM_PP_SLOT);
2039 	set_slot_comp_priority(zram, index, 0);
2040 
2041 	if (test_slot_flag(zram, index, ZRAM_HUGE)) {
2042 		/*
2043 		 * Writeback completion decrements ->huge_pages but keeps
2044 		 * ZRAM_HUGE flag for deferred decompression path.
2045 		 */
2046 		if (!test_slot_flag(zram, index, ZRAM_WB))
2047 			atomic64_dec(&zram->stats.huge_pages);
2048 		clear_slot_flag(zram, index, ZRAM_HUGE);
2049 	}
2050 
2051 	if (test_slot_flag(zram, index, ZRAM_WB)) {
2052 		clear_slot_flag(zram, index, ZRAM_WB);
2053 		zram_release_bdev_block(zram, get_slot_handle(zram, index));
2054 		goto out;
2055 	}
2056 
2057 	/*
2058 	 * No memory is allocated for same element filled pages.
2059 	 * Simply clear same page flag.
2060 	 */
2061 	if (test_slot_flag(zram, index, ZRAM_SAME)) {
2062 		clear_slot_flag(zram, index, ZRAM_SAME);
2063 		atomic64_dec(&zram->stats.same_pages);
2064 		goto out;
2065 	}
2066 
2067 	handle = get_slot_handle(zram, index);
2068 	if (!handle)
2069 		return;
2070 
2071 	zs_free(zram->mem_pool, handle);
2072 
2073 	atomic64_sub(get_slot_size(zram, index),
2074 		     &zram->stats.compr_data_size);
2075 out:
2076 	atomic64_dec(&zram->stats.pages_stored);
2077 	set_slot_handle(zram, index, 0);
2078 	set_slot_size(zram, index, 0);
2079 }
2080 
2081 static int read_same_filled_page(struct zram *zram, struct page *page,
2082 				 unsigned long index)
2083 {
2084 	void *mem;
2085 
2086 	mem = kmap_local_page(page);
2087 	zram_fill_page(mem, PAGE_SIZE, get_slot_handle(zram, index));
2088 	kunmap_local(mem);
2089 	return 0;
2090 }
2091 
2092 static int read_incompressible_page(struct zram *zram, struct page *page,
2093 				    unsigned long index)
2094 {
2095 	struct scatterlist sg[2];
2096 	unsigned long handle;
2097 	void *src, *dst;
2098 
2099 	handle = get_slot_handle(zram, index);
2100 	zs_obj_read_sg_begin(zram->mem_pool, handle, sg, PAGE_SIZE);
2101 	/* an incompressible object never spans two pages */
2102 	src = kmap_local_page(sg_page(sg));
2103 	dst = kmap_local_page(page);
2104 	copy_page(dst, src);
2105 	kunmap_local(dst);
2106 	kunmap_local(src);
2107 	zs_obj_read_sg_end(zram->mem_pool, handle);
2108 
2109 	return 0;
2110 }
2111 
2112 static int read_compressed_page(struct zram *zram, struct page *page,
2113 				unsigned long index)
2114 {
2115 	struct zcomp_strm *zstrm;
2116 	struct scatterlist sg[2];
2117 	unsigned long handle;
2118 	unsigned int size;
2119 	void *dst;
2120 	int ret, prio;
2121 
2122 	handle = get_slot_handle(zram, index);
2123 	size = get_slot_size(zram, index);
2124 	prio = get_slot_comp_priority(zram, index);
2125 
2126 	zstrm = zcomp_stream_get(zram->comps[prio]);
2127 	zs_obj_read_sg_begin(zram->mem_pool, handle, sg, size);
2128 	dst = kmap_local_page(page);
2129 	ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size, dst);
2130 	kunmap_local(dst);
2131 	zs_obj_read_sg_end(zram->mem_pool, handle);
2132 	zcomp_stream_put(zstrm);
2133 
2134 	return ret;
2135 }
2136 
2137 #if defined CONFIG_ZRAM_WRITEBACK
2138 static int read_from_zspool_raw(struct zram *zram, struct page *page,
2139 				unsigned long index)
2140 {
2141 	struct scatterlist sg[2];
2142 	unsigned long handle;
2143 	unsigned int size;
2144 	void *dst;
2145 
2146 	handle = get_slot_handle(zram, index);
2147 	size = get_slot_size(zram, index);
2148 
2149 	/*
2150 	 * No decompression takes place here, we copy out raw compressed
2151 	 * data directly into the destination page.
2152 	 */
2153 	zs_obj_read_sg_begin(zram->mem_pool, handle, sg, size);
2154 	dst = kmap_local_page(page);
2155 	sg_copy_to_buffer(sg, sg_nents(sg), dst, size);
2156 	kunmap_local(dst);
2157 	zs_obj_read_sg_end(zram->mem_pool, handle);
2158 
2159 	memzero_page(page, size, PAGE_SIZE - size);
2160 
2161 	return 0;
2162 }
2163 #endif
2164 
2165 /*
2166  * Reads (decompresses if needed) a page from zspool (zsmalloc).
2167  * Corresponding ZRAM slot should be locked.
2168  */
2169 static int read_from_zspool(struct zram *zram, struct page *page,
2170 			    unsigned long index)
2171 {
2172 	if (test_slot_flag(zram, index, ZRAM_SAME) ||
2173 	    !get_slot_handle(zram, index))
2174 		return read_same_filled_page(zram, page, index);
2175 
2176 	if (!test_slot_flag(zram, index, ZRAM_HUGE))
2177 		return read_compressed_page(zram, page, index);
2178 	else
2179 		return read_incompressible_page(zram, page, index);
2180 }
2181 
2182 static int zram_read_page(struct zram *zram, struct page *page,
2183 			  unsigned long index, struct bio *parent)
2184 {
2185 	int ret;
2186 
2187 	slot_lock(zram, index);
2188 	if (!test_slot_flag(zram, index, ZRAM_WB)) {
2189 		/* Slot should be locked through out the function call */
2190 		ret = read_from_zspool(zram, page, index);
2191 		slot_unlock(zram, index);
2192 	} else {
2193 		unsigned long blk_idx = get_slot_handle(zram, index);
2194 
2195 		/*
2196 		 * The slot should be unlocked before reading from the backing
2197 		 * device.
2198 		 */
2199 		slot_unlock(zram, index);
2200 		ret = read_from_bdev(zram, page, index, blk_idx, parent);
2201 	}
2202 
2203 	/* Should NEVER happen. Return bio error if it does. */
2204 	if (WARN_ON(ret < 0))
2205 		pr_err("Decompression failed! err=%d, page=%lu\n", ret, index);
2206 
2207 	return ret;
2208 }
2209 
2210 /*
2211  * Use a temporary buffer to decompress the page, as the decompressor
2212  * always expects a full page for the output.
2213  */
2214 static int zram_bvec_read_partial(struct zram *zram, struct bio_vec *bvec,
2215 				  unsigned long index, int offset)
2216 {
2217 	struct page *page = alloc_page(GFP_NOIO);
2218 	int ret;
2219 
2220 	if (!page)
2221 		return -ENOMEM;
2222 	ret = zram_read_page(zram, page, index, NULL);
2223 	if (likely(!ret))
2224 		memcpy_to_bvec(bvec, page_address(page) + offset);
2225 	__free_page(page);
2226 	return ret;
2227 }
2228 
2229 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
2230 			  unsigned long index, int offset, struct bio *bio)
2231 {
2232 	if (is_partial_io(bvec))
2233 		return zram_bvec_read_partial(zram, bvec, index, offset);
2234 	return zram_read_page(zram, bvec->bv_page, index, bio);
2235 }
2236 
2237 static int write_same_filled_page(struct zram *zram, unsigned long fill,
2238 				  unsigned long index)
2239 {
2240 	slot_lock(zram, index);
2241 	slot_free(zram, index);
2242 	set_slot_flag(zram, index, ZRAM_SAME);
2243 	set_slot_handle(zram, index, fill);
2244 	slot_unlock(zram, index);
2245 
2246 	atomic64_inc(&zram->stats.same_pages);
2247 	atomic64_inc(&zram->stats.pages_stored);
2248 
2249 	return 0;
2250 }
2251 
2252 static int write_incompressible_page(struct zram *zram, struct page *page,
2253 				     unsigned long index)
2254 {
2255 	unsigned long handle;
2256 	void *src;
2257 
2258 	/*
2259 	 * This function is called from preemptible context so we don't need
2260 	 * to do optimistic and fallback to pessimistic handle allocation,
2261 	 * like we do for compressible pages.
2262 	 */
2263 	handle = zs_malloc(zram->mem_pool, PAGE_SIZE,
2264 			   GFP_NOIO | __GFP_NOWARN |
2265 			   __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page));
2266 	if (IS_ERR_VALUE(handle))
2267 		return PTR_ERR((void *)handle);
2268 
2269 	if (!zram_can_store_page(zram)) {
2270 		zs_free(zram->mem_pool, handle);
2271 		return -ENOMEM;
2272 	}
2273 
2274 	src = kmap_local_page(page);
2275 	zs_obj_write(zram->mem_pool, handle, src, PAGE_SIZE);
2276 	kunmap_local(src);
2277 
2278 	slot_lock(zram, index);
2279 	slot_free(zram, index);
2280 	set_slot_flag(zram, index, ZRAM_HUGE);
2281 	set_slot_handle(zram, index, handle);
2282 	set_slot_size(zram, index, PAGE_SIZE);
2283 	slot_unlock(zram, index);
2284 
2285 	atomic64_add(PAGE_SIZE, &zram->stats.compr_data_size);
2286 	atomic64_inc(&zram->stats.huge_pages);
2287 	atomic64_inc(&zram->stats.huge_pages_since);
2288 	atomic64_inc(&zram->stats.pages_stored);
2289 
2290 	return 0;
2291 }
2292 
2293 static int zram_write_page(struct zram *zram, struct page *page,
2294 			   unsigned long index)
2295 {
2296 	int ret = 0;
2297 	unsigned long handle;
2298 	unsigned int comp_len;
2299 	void *mem;
2300 	struct zcomp_strm *zstrm;
2301 	unsigned long element;
2302 	bool same_filled;
2303 
2304 	mem = kmap_local_page(page);
2305 	same_filled = page_same_filled(mem, &element);
2306 	kunmap_local(mem);
2307 	if (same_filled)
2308 		return write_same_filled_page(zram, element, index);
2309 
2310 	zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
2311 	mem = kmap_local_page(page);
2312 	ret = zcomp_compress(zram->comps[ZRAM_PRIMARY_COMP], zstrm,
2313 			     mem, &comp_len);
2314 	kunmap_local(mem);
2315 
2316 	if (unlikely(ret)) {
2317 		zcomp_stream_put(zstrm);
2318 		pr_err("Compression failed! err=%d\n", ret);
2319 		return ret;
2320 	}
2321 
2322 	if (comp_len >= huge_class_size) {
2323 		zcomp_stream_put(zstrm);
2324 		return write_incompressible_page(zram, page, index);
2325 	}
2326 
2327 	handle = zs_malloc(zram->mem_pool, comp_len,
2328 			   GFP_NOIO | __GFP_NOWARN |
2329 			   __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page));
2330 	if (IS_ERR_VALUE(handle)) {
2331 		zcomp_stream_put(zstrm);
2332 		return PTR_ERR((void *)handle);
2333 	}
2334 
2335 	if (!zram_can_store_page(zram)) {
2336 		zcomp_stream_put(zstrm);
2337 		zs_free(zram->mem_pool, handle);
2338 		return -ENOMEM;
2339 	}
2340 
2341 	zs_obj_write(zram->mem_pool, handle, zstrm->buffer, comp_len);
2342 	zcomp_stream_put(zstrm);
2343 
2344 	slot_lock(zram, index);
2345 	slot_free(zram, index);
2346 	set_slot_handle(zram, index, handle);
2347 	set_slot_size(zram, index, comp_len);
2348 	slot_unlock(zram, index);
2349 
2350 	/* Update stats */
2351 	atomic64_inc(&zram->stats.pages_stored);
2352 	atomic64_add(comp_len, &zram->stats.compr_data_size);
2353 
2354 	return ret;
2355 }
2356 
2357 /*
2358  * This is a partial IO. Read the full page before writing the changes.
2359  */
2360 static int zram_bvec_write_partial(struct zram *zram, struct bio_vec *bvec,
2361 				   unsigned long index, int offset)
2362 {
2363 	struct page *page = alloc_page(GFP_NOIO);
2364 	int ret;
2365 
2366 	if (!page)
2367 		return -ENOMEM;
2368 
2369 	ret = zram_read_page(zram, page, index, NULL);
2370 	if (!ret) {
2371 		memcpy_from_bvec(page_address(page) + offset, bvec);
2372 		ret = zram_write_page(zram, page, index);
2373 	}
2374 	__free_page(page);
2375 	return ret;
2376 }
2377 
2378 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
2379 			   unsigned long index, int offset)
2380 {
2381 	if (is_partial_io(bvec))
2382 		return zram_bvec_write_partial(zram, bvec, index, offset);
2383 	return zram_write_page(zram, bvec->bv_page, index);
2384 }
2385 
2386 #ifdef CONFIG_ZRAM_MULTI_COMP
2387 #define RECOMPRESS_IDLE		(1 << 0)
2388 #define RECOMPRESS_HUGE		(1 << 1)
2389 
2390 static bool highest_priority_algorithm(struct zram *zram, u32 prio)
2391 {
2392 	u32 p;
2393 
2394 	for (p = prio + 1; p < ZRAM_MAX_COMPS; p++) {
2395 		if (zram->comp_algs[p])
2396 			return false;
2397 	}
2398 
2399 	return true;
2400 }
2401 
2402 static void scan_slots_for_recompress(struct zram *zram, u32 mode, u32 prio,
2403 				      struct zram_pp_ctl *ctl)
2404 {
2405 	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
2406 	unsigned long index;
2407 
2408 	for (index = 0; index < nr_pages; index++) {
2409 		bool ok = true;
2410 
2411 		slot_lock(zram, index);
2412 		if (!slot_allocated(zram, index))
2413 			goto next;
2414 
2415 		if (mode & RECOMPRESS_IDLE &&
2416 		    !test_slot_flag(zram, index, ZRAM_IDLE))
2417 			goto next;
2418 
2419 		if (mode & RECOMPRESS_HUGE &&
2420 		    !test_slot_flag(zram, index, ZRAM_HUGE))
2421 			goto next;
2422 
2423 		if (test_slot_flag(zram, index, ZRAM_WB) ||
2424 		    test_slot_flag(zram, index, ZRAM_SAME) ||
2425 		    test_slot_flag(zram, index, ZRAM_INCOMPRESSIBLE))
2426 			goto next;
2427 
2428 		/* Already compressed with same or higher priority */
2429 		if (get_slot_comp_priority(zram, index) >= prio)
2430 			goto next;
2431 
2432 		ok = place_pp_slot(zram, ctl, index);
2433 next:
2434 		slot_unlock(zram, index);
2435 		if (!ok)
2436 			break;
2437 	}
2438 }
2439 
2440 /*
2441  * This function will decompress (unless it's ZRAM_HUGE) the page and then
2442  * attempt to compress it using provided compression algorithm priority
2443  * (which is potentially more effective).
2444  *
2445  * Corresponding ZRAM slot should be locked.
2446  */
2447 static int recompress_slot(struct zram *zram, unsigned long index,
2448 			   struct page *page, u64 *num_recomp_pages,
2449 			   u32 threshold, u32 prio)
2450 {
2451 	struct zcomp_strm *zstrm = NULL;
2452 	unsigned long handle_old;
2453 	unsigned long handle_new;
2454 	unsigned int comp_len_old;
2455 	unsigned int comp_len_new;
2456 	unsigned int class_index_old;
2457 	unsigned int class_index_new;
2458 	void *src;
2459 	int ret = 0;
2460 
2461 	handle_old = get_slot_handle(zram, index);
2462 	if (!handle_old)
2463 		return -EINVAL;
2464 
2465 	comp_len_old = get_slot_size(zram, index);
2466 	/*
2467 	 * Do not recompress objects that are already "small enough".
2468 	 */
2469 	if (comp_len_old < threshold)
2470 		return 0;
2471 
2472 	ret = read_from_zspool(zram, page, index);
2473 	if (ret)
2474 		return ret;
2475 
2476 	/*
2477 	 * We touched this entry so mark it as non-IDLE. This makes sure that
2478 	 * we don't preserve IDLE flag and don't incorrectly pick this entry
2479 	 * for different post-processing type (e.g. writeback).
2480 	 */
2481 	clear_slot_flag(zram, index, ZRAM_IDLE);
2482 
2483 	zstrm = zcomp_stream_get(zram->comps[prio]);
2484 	src = kmap_local_page(page);
2485 	ret = zcomp_compress(zram->comps[prio], zstrm, src, &comp_len_new);
2486 	kunmap_local(src);
2487 
2488 	/*
2489 	 * Decrement the limit (if set) on pages we can recompress, even
2490 	 * when current recompression was unsuccessful or did not compress
2491 	 * the page below the threshold, because we still spent resources
2492 	 * on it.
2493 	 */
2494 	if (*num_recomp_pages)
2495 		*num_recomp_pages -= 1;
2496 
2497 	if (ret) {
2498 		zcomp_stream_put(zstrm);
2499 		return ret;
2500 	}
2501 
2502 	class_index_old = zs_lookup_class_index(zram->mem_pool, comp_len_old);
2503 	class_index_new = zs_lookup_class_index(zram->mem_pool, comp_len_new);
2504 
2505 	if (class_index_new >= class_index_old ||
2506 	    (threshold && comp_len_new >= threshold)) {
2507 		zcomp_stream_put(zstrm);
2508 
2509 		/*
2510 		 * Secondary algorithms failed to re-compress the page
2511 		 * in a way that would save memory.
2512 		 *
2513 		 * Mark the object incompressible if the max-priority (the
2514 		 * last configured one) algorithm couldn't re-compress it.
2515 		 */
2516 		if (highest_priority_algorithm(zram, prio))
2517 			set_slot_flag(zram, index, ZRAM_INCOMPRESSIBLE);
2518 		return 0;
2519 	}
2520 
2521 	/*
2522 	 * We are holding per-CPU stream mutex and entry lock so better
2523 	 * avoid direct reclaim.  Allocation error is not fatal since
2524 	 * we still have the old object in the mem_pool.
2525 	 *
2526 	 * XXX: technically, the node we really want here is the node that
2527 	 * holds the original compressed data. But that would require us to
2528 	 * modify zsmalloc API to return this information. For now, we will
2529 	 * make do with the node of the page allocated for recompression.
2530 	 */
2531 	handle_new = zs_malloc(zram->mem_pool, comp_len_new,
2532 			       GFP_NOIO | __GFP_NOWARN |
2533 			       __GFP_HIGHMEM | __GFP_MOVABLE,
2534 			       page_to_nid(page));
2535 	if (IS_ERR_VALUE(handle_new)) {
2536 		zcomp_stream_put(zstrm);
2537 		return PTR_ERR((void *)handle_new);
2538 	}
2539 
2540 	zs_obj_write(zram->mem_pool, handle_new, zstrm->buffer, comp_len_new);
2541 	zcomp_stream_put(zstrm);
2542 
2543 	slot_free(zram, index);
2544 	set_slot_handle(zram, index, handle_new);
2545 	set_slot_size(zram, index, comp_len_new);
2546 	set_slot_comp_priority(zram, index, prio);
2547 
2548 	atomic64_add(comp_len_new, &zram->stats.compr_data_size);
2549 	atomic64_inc(&zram->stats.pages_stored);
2550 
2551 	return 0;
2552 }
2553 
2554 static ssize_t recompress_store(struct device *dev,
2555 				struct device_attribute *attr,
2556 				const char *buf, size_t len)
2557 {
2558 	struct zram *zram = dev_to_zram(dev);
2559 	char *args, *param, *val, *algo = NULL;
2560 	u64 num_recomp_pages = ULLONG_MAX;
2561 	struct zram_pp_ctl *ctl = NULL;
2562 	s32 prio = ZRAM_SECONDARY_COMP;
2563 	u32 mode = 0, threshold = 0;
2564 	struct zram_pp_slot *pps;
2565 	struct page *page = NULL;
2566 	bool prio_param = false;
2567 	ssize_t ret;
2568 
2569 	args = skip_spaces(buf);
2570 	while (*args) {
2571 		args = next_arg(args, &param, &val);
2572 
2573 		if (!val || !*val)
2574 			return -EINVAL;
2575 
2576 		if (!strcmp(param, "type")) {
2577 			if (!strcmp(val, "idle"))
2578 				mode = RECOMPRESS_IDLE;
2579 			if (!strcmp(val, "huge"))
2580 				mode = RECOMPRESS_HUGE;
2581 			if (!strcmp(val, "huge_idle"))
2582 				mode = RECOMPRESS_IDLE | RECOMPRESS_HUGE;
2583 			if (!mode)
2584 				return -EINVAL;
2585 			continue;
2586 		}
2587 
2588 		if (!strcmp(param, "max_pages")) {
2589 			/*
2590 			 * Limit the number of entries (pages) we attempt to
2591 			 * recompress.
2592 			 */
2593 			ret = kstrtoull(val, 10, &num_recomp_pages);
2594 			if (ret)
2595 				return ret;
2596 			continue;
2597 		}
2598 
2599 		if (!strcmp(param, "threshold")) {
2600 			/*
2601 			 * We will re-compress only idle objects equal or
2602 			 * greater in size than watermark.
2603 			 */
2604 			ret = kstrtouint(val, 10, &threshold);
2605 			if (ret)
2606 				return ret;
2607 			continue;
2608 		}
2609 
2610 		if (!strcmp(param, "algo")) {
2611 			algo = val;
2612 			continue;
2613 		}
2614 
2615 		if (!strcmp(param, "priority")) {
2616 			prio_param = true;
2617 			ret = kstrtoint(val, 10, &prio);
2618 			if (ret)
2619 				return ret;
2620 			continue;
2621 		}
2622 	}
2623 
2624 	if (threshold >= huge_class_size)
2625 		return -EINVAL;
2626 
2627 	guard(rwsem_write)(&zram->dev_lock);
2628 	if (!init_done(zram))
2629 		return -EINVAL;
2630 
2631 	if (prio_param) {
2632 		if (prio < ZRAM_SECONDARY_COMP || prio >= ZRAM_MAX_COMPS)
2633 			return -EINVAL;
2634 	}
2635 
2636 	if (algo && prio_param) {
2637 		ret = validate_algo_priority(zram, algo, prio);
2638 		if (ret)
2639 			return ret;
2640 	}
2641 
2642 	if (algo && !prio_param) {
2643 		prio = lookup_algo_priority(zram, algo, ZRAM_SECONDARY_COMP);
2644 		if (prio < 0)
2645 			return -EINVAL;
2646 	}
2647 
2648 	if (!zram->comps[prio])
2649 		return -EINVAL;
2650 
2651 	page = alloc_page(GFP_KERNEL);
2652 	if (!page) {
2653 		ret = -ENOMEM;
2654 		goto out;
2655 	}
2656 
2657 	ctl = init_pp_ctl();
2658 	if (!ctl) {
2659 		ret = -ENOMEM;
2660 		goto out;
2661 	}
2662 
2663 	scan_slots_for_recompress(zram, mode, prio, ctl);
2664 
2665 	ret = len;
2666 	while ((pps = select_pp_slot(ctl))) {
2667 		int err = 0;
2668 
2669 		if (!num_recomp_pages)
2670 			break;
2671 
2672 		slot_lock(zram, pps->index);
2673 		if (!test_slot_flag(zram, pps->index, ZRAM_PP_SLOT))
2674 			goto next;
2675 
2676 		err = recompress_slot(zram, pps->index, page,
2677 				      &num_recomp_pages, threshold, prio);
2678 next:
2679 		slot_unlock(zram, pps->index);
2680 		release_pp_slot(zram, pps);
2681 
2682 		if (err) {
2683 			ret = err;
2684 			break;
2685 		}
2686 
2687 		cond_resched();
2688 	}
2689 
2690 out:
2691 	if (page)
2692 		__free_page(page);
2693 	release_pp_ctl(zram, ctl);
2694 	return ret;
2695 }
2696 #endif
2697 
2698 static void zram_bio_discard(struct zram *zram, struct bio *bio)
2699 {
2700 	size_t n = bio->bi_iter.bi_size;
2701 	unsigned long index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
2702 	u32 offset = (bio->bi_iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
2703 			SECTOR_SHIFT;
2704 
2705 	/*
2706 	 * zram manages data in physical block size units. Because logical block
2707 	 * size isn't identical with physical block size on some arch, we
2708 	 * could get a discard request pointing to a specific offset within a
2709 	 * certain physical block.  Although we can handle this request by
2710 	 * reading that physiclal block and decompressing and partially zeroing
2711 	 * and re-compressing and then re-storing it, this isn't reasonable
2712 	 * because our intent with a discard request is to save memory.  So
2713 	 * skipping this logical block is appropriate here.
2714 	 */
2715 	if (offset) {
2716 		if (n <= (PAGE_SIZE - offset))
2717 			goto end_bio;
2718 
2719 		n -= (PAGE_SIZE - offset);
2720 		index++;
2721 	}
2722 
2723 	while (n >= PAGE_SIZE) {
2724 		slot_lock(zram, index);
2725 		slot_free(zram, index);
2726 		slot_unlock(zram, index);
2727 		atomic64_inc(&zram->stats.notify_free);
2728 		index++;
2729 		n -= PAGE_SIZE;
2730 	}
2731 
2732 end_bio:
2733 	bio_endio(bio);
2734 }
2735 
2736 static void zram_bio_read(struct zram *zram, struct bio *bio)
2737 {
2738 	unsigned long start_time = bio_start_io_acct(bio);
2739 	struct bvec_iter iter = bio->bi_iter;
2740 
2741 	do {
2742 		unsigned long index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
2743 		u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
2744 				SECTOR_SHIFT;
2745 		struct bio_vec bv = bio_iter_iovec(bio, iter);
2746 
2747 		bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
2748 
2749 		if (zram_bvec_read(zram, &bv, index, offset, bio) < 0) {
2750 			atomic64_inc(&zram->stats.failed_reads);
2751 			bio->bi_status = BLK_STS_IOERR;
2752 			break;
2753 		}
2754 		flush_dcache_page(bv.bv_page);
2755 
2756 		slot_lock(zram, index);
2757 		mark_slot_accessed(zram, index);
2758 		slot_unlock(zram, index);
2759 
2760 		bio_advance_iter_single(bio, &iter, bv.bv_len);
2761 	} while (iter.bi_size);
2762 
2763 	bio_end_io_acct(bio, start_time);
2764 	bio_endio(bio);
2765 }
2766 
2767 static void zram_bio_write(struct zram *zram, struct bio *bio)
2768 {
2769 	unsigned long start_time = bio_start_io_acct(bio);
2770 	struct bvec_iter iter = bio->bi_iter;
2771 
2772 	do {
2773 		unsigned long index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
2774 		u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
2775 				SECTOR_SHIFT;
2776 		struct bio_vec bv = bio_iter_iovec(bio, iter);
2777 
2778 		bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
2779 
2780 		if (zram_bvec_write(zram, &bv, index, offset) < 0) {
2781 			atomic64_inc(&zram->stats.failed_writes);
2782 			bio->bi_status = BLK_STS_IOERR;
2783 			break;
2784 		}
2785 
2786 		slot_lock(zram, index);
2787 		mark_slot_accessed(zram, index);
2788 		slot_unlock(zram, index);
2789 
2790 		bio_advance_iter_single(bio, &iter, bv.bv_len);
2791 	} while (iter.bi_size);
2792 
2793 	bio_end_io_acct(bio, start_time);
2794 	bio_endio(bio);
2795 }
2796 
2797 /*
2798  * Handler function for all zram I/O requests.
2799  */
2800 static void zram_submit_bio(struct bio *bio)
2801 {
2802 	struct zram *zram = bio->bi_bdev->bd_disk->private_data;
2803 
2804 	switch (bio_op(bio)) {
2805 	case REQ_OP_READ:
2806 		zram_bio_read(zram, bio);
2807 		break;
2808 	case REQ_OP_WRITE:
2809 		zram_bio_write(zram, bio);
2810 		break;
2811 	case REQ_OP_DISCARD:
2812 	case REQ_OP_WRITE_ZEROES:
2813 		zram_bio_discard(zram, bio);
2814 		break;
2815 	default:
2816 		WARN_ON_ONCE(1);
2817 		bio_endio(bio);
2818 	}
2819 }
2820 
2821 static void zram_slot_free_notify(struct block_device *bdev,
2822 				unsigned long index)
2823 {
2824 	struct zram *zram;
2825 
2826 	zram = bdev->bd_disk->private_data;
2827 
2828 	atomic64_inc(&zram->stats.notify_free);
2829 	if (!slot_trylock(zram, index)) {
2830 		atomic64_inc(&zram->stats.miss_free);
2831 		return;
2832 	}
2833 
2834 	slot_free(zram, index);
2835 	slot_unlock(zram, index);
2836 }
2837 
2838 static void zram_comp_params_reset(struct zram *zram)
2839 {
2840 	u32 prio;
2841 
2842 	for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
2843 		comp_params_reset(zram, prio);
2844 	}
2845 }
2846 
2847 static void zram_destroy_comps(struct zram *zram)
2848 {
2849 	u32 prio;
2850 
2851 	for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
2852 		struct zcomp *comp = zram->comps[prio];
2853 
2854 		zram->comps[prio] = NULL;
2855 		if (!comp)
2856 			continue;
2857 		zcomp_destroy(comp);
2858 	}
2859 
2860 	for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++)
2861 		zram->comp_algs[prio] = NULL;
2862 
2863 	zram_comp_params_reset(zram);
2864 	comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
2865 }
2866 
2867 static void zram_reset_device(struct zram *zram)
2868 {
2869 	guard(rwsem_write)(&zram->dev_lock);
2870 
2871 	zram->limit_pages = 0;
2872 
2873 	set_capacity_and_notify(zram->disk, 0);
2874 	part_stat_set_all(zram->disk->part0, 0);
2875 
2876 	/* I/O operation under all of CPU are done so let's free */
2877 	zram_meta_free(zram, zram->disksize);
2878 	zram->disksize = 0;
2879 	zram_destroy_comps(zram);
2880 	memset(&zram->stats, 0, sizeof(zram->stats));
2881 	reset_bdev(zram);
2882 }
2883 
2884 static ssize_t disksize_store(struct device *dev, struct device_attribute *attr,
2885 			      const char *buf, size_t len)
2886 {
2887 	unsigned long num_pages;
2888 	u64 disksize;
2889 	struct zcomp *comp;
2890 	struct zram *zram = dev_to_zram(dev);
2891 	int err;
2892 	u32 prio;
2893 
2894 	disksize = memparse(buf, NULL);
2895 	if (!disksize)
2896 		return -EINVAL;
2897 
2898 	guard(rwsem_write)(&zram->dev_lock);
2899 	if (init_done(zram)) {
2900 		pr_info("Cannot change disksize for initialized device\n");
2901 		return -EBUSY;
2902 	}
2903 
2904 	disksize = PAGE_ALIGN(disksize);
2905 	num_pages = disksize >> PAGE_SHIFT;
2906 	/* Slots are addressed by an unsigned long index */
2907 	if (!num_pages || ((u64)num_pages << PAGE_SHIFT) != disksize)
2908 		return -EINVAL;
2909 
2910 	if (!zram_meta_alloc(zram, disksize))
2911 		return -ENOMEM;
2912 
2913 	for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
2914 		if (!zram->comp_algs[prio])
2915 			continue;
2916 
2917 		comp = zcomp_create(zram->comp_algs[prio],
2918 				    &zram->params[prio]);
2919 		if (IS_ERR(comp)) {
2920 			pr_err("Cannot initialise %s compressing backend\n",
2921 			       zram->comp_algs[prio]);
2922 			err = PTR_ERR(comp);
2923 			goto out_free_comps;
2924 		}
2925 
2926 		zram->comps[prio] = comp;
2927 	}
2928 	zram->disksize = disksize;
2929 	set_capacity_and_notify(zram->disk, zram->disksize >> SECTOR_SHIFT);
2930 
2931 	return len;
2932 
2933 out_free_comps:
2934 	zram_destroy_comps(zram);
2935 	zram_meta_free(zram, disksize);
2936 	return err;
2937 }
2938 
2939 static ssize_t reset_store(struct device *dev,
2940 		struct device_attribute *attr, const char *buf, size_t len)
2941 {
2942 	int ret;
2943 	unsigned short do_reset;
2944 	struct zram *zram;
2945 	struct gendisk *disk;
2946 
2947 	ret = kstrtou16(buf, 10, &do_reset);
2948 	if (ret)
2949 		return ret;
2950 
2951 	if (!do_reset)
2952 		return -EINVAL;
2953 
2954 	zram = dev_to_zram(dev);
2955 	disk = zram->disk;
2956 
2957 	mutex_lock(&disk->open_mutex);
2958 	/* Do not reset an active device or claimed device */
2959 	if (disk_openers(disk) || zram->claim) {
2960 		mutex_unlock(&disk->open_mutex);
2961 		return -EBUSY;
2962 	}
2963 
2964 	/* From now on, anyone can't open /dev/zram[0-9] */
2965 	zram->claim = true;
2966 	mutex_unlock(&disk->open_mutex);
2967 
2968 	/* Make sure all the pending I/O are finished */
2969 	sync_blockdev(disk->part0);
2970 	zram_reset_device(zram);
2971 
2972 	mutex_lock(&disk->open_mutex);
2973 	zram->claim = false;
2974 	mutex_unlock(&disk->open_mutex);
2975 
2976 	return len;
2977 }
2978 
2979 static int zram_open(struct gendisk *disk, blk_mode_t mode)
2980 {
2981 	struct zram *zram = disk->private_data;
2982 
2983 	WARN_ON(!mutex_is_locked(&disk->open_mutex));
2984 
2985 	/* zram was claimed to reset so open request fails */
2986 	if (zram->claim)
2987 		return -EBUSY;
2988 	return 0;
2989 }
2990 
2991 static const struct block_device_operations zram_devops = {
2992 	.open = zram_open,
2993 	.submit_bio = zram_submit_bio,
2994 	.swap_slot_free_notify = zram_slot_free_notify,
2995 	.owner = THIS_MODULE
2996 };
2997 
2998 static DEVICE_ATTR_RO(io_stat);
2999 static DEVICE_ATTR_RO(mm_stat);
3000 static DEVICE_ATTR_RO(debug_stat);
3001 static DEVICE_ATTR_WO(compact);
3002 static DEVICE_ATTR_RW(disksize);
3003 static DEVICE_ATTR_RO(initstate);
3004 static DEVICE_ATTR_WO(reset);
3005 static DEVICE_ATTR_WO(mem_limit);
3006 static DEVICE_ATTR_WO(mem_used_max);
3007 static DEVICE_ATTR_WO(idle);
3008 static DEVICE_ATTR_RW(comp_algorithm);
3009 #ifdef CONFIG_ZRAM_WRITEBACK
3010 static DEVICE_ATTR_RO(bd_stat);
3011 static DEVICE_ATTR_RW(backing_dev);
3012 static DEVICE_ATTR_WO(writeback);
3013 static DEVICE_ATTR_RW(writeback_limit);
3014 static DEVICE_ATTR_RW(writeback_limit_enable);
3015 static DEVICE_ATTR_RW(writeback_batch_size);
3016 static DEVICE_ATTR_RW(compressed_writeback);
3017 #endif
3018 #ifdef CONFIG_ZRAM_MULTI_COMP
3019 static DEVICE_ATTR_RW(recomp_algorithm);
3020 static DEVICE_ATTR_WO(recompress);
3021 #endif
3022 static DEVICE_ATTR_WO(algorithm_params);
3023 
3024 static struct attribute *zram_disk_attrs[] = {
3025 	&dev_attr_disksize.attr,
3026 	&dev_attr_initstate.attr,
3027 	&dev_attr_reset.attr,
3028 	&dev_attr_compact.attr,
3029 	&dev_attr_mem_limit.attr,
3030 	&dev_attr_mem_used_max.attr,
3031 	&dev_attr_idle.attr,
3032 	&dev_attr_comp_algorithm.attr,
3033 #ifdef CONFIG_ZRAM_WRITEBACK
3034 	&dev_attr_bd_stat.attr,
3035 	&dev_attr_backing_dev.attr,
3036 	&dev_attr_writeback.attr,
3037 	&dev_attr_writeback_limit.attr,
3038 	&dev_attr_writeback_limit_enable.attr,
3039 	&dev_attr_writeback_batch_size.attr,
3040 	&dev_attr_compressed_writeback.attr,
3041 #endif
3042 	&dev_attr_io_stat.attr,
3043 	&dev_attr_mm_stat.attr,
3044 	&dev_attr_debug_stat.attr,
3045 #ifdef CONFIG_ZRAM_MULTI_COMP
3046 	&dev_attr_recomp_algorithm.attr,
3047 	&dev_attr_recompress.attr,
3048 #endif
3049 	&dev_attr_algorithm_params.attr,
3050 	NULL,
3051 };
3052 
3053 ATTRIBUTE_GROUPS(zram_disk);
3054 
3055 /*
3056  * Allocate and initialize new zram device. the function returns
3057  * '>= 0' device_id upon success, and negative value otherwise.
3058  */
3059 static int zram_add(void)
3060 {
3061 	struct queue_limits lim = {
3062 		.logical_block_size		= ZRAM_LOGICAL_BLOCK_SIZE,
3063 		/*
3064 		 * To ensure that we always get PAGE_SIZE aligned and
3065 		 * n*PAGE_SIZED sized I/O requests.
3066 		 */
3067 		.physical_block_size		= PAGE_SIZE,
3068 		.io_min				= PAGE_SIZE,
3069 		.io_opt				= PAGE_SIZE,
3070 		.max_hw_discard_sectors		= UINT_MAX,
3071 		/*
3072 		 * zram_bio_discard() will clear all logical blocks if logical
3073 		 * block size is identical with physical block size(PAGE_SIZE).
3074 		 * But if it is different, we will skip discarding some parts of
3075 		 * logical blocks in the part of the request range which isn't
3076 		 * aligned to physical block size.  So we can't ensure that all
3077 		 * discarded logical blocks are zeroed.
3078 		 */
3079 #if ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE
3080 		.max_write_zeroes_sectors	= UINT_MAX,
3081 #endif
3082 		.features			= BLK_FEAT_STABLE_WRITES |
3083 						  BLK_FEAT_SYNCHRONOUS,
3084 	};
3085 	struct zram *zram;
3086 	int ret, device_id;
3087 
3088 	zram = kzalloc_obj(struct zram);
3089 	if (!zram)
3090 		return -ENOMEM;
3091 
3092 	ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
3093 	if (ret < 0)
3094 		goto out_free_dev;
3095 	device_id = ret;
3096 
3097 	init_rwsem(&zram->dev_lock);
3098 #ifdef CONFIG_ZRAM_WRITEBACK
3099 	zram->wb_batch_size = 32;
3100 	zram->compressed_wb = false;
3101 #endif
3102 
3103 	/* gendisk structure */
3104 	zram->disk = blk_alloc_disk(&lim, NUMA_NO_NODE);
3105 	if (IS_ERR(zram->disk)) {
3106 		pr_err("Error allocating disk structure for device %d\n",
3107 			device_id);
3108 		ret = PTR_ERR(zram->disk);
3109 		goto out_free_idr;
3110 	}
3111 
3112 	zram->disk->major = zram_major;
3113 	zram->disk->first_minor = device_id;
3114 	zram->disk->minors = 1;
3115 	zram->disk->flags |= GENHD_FL_NO_PART;
3116 	zram->disk->fops = &zram_devops;
3117 	zram->disk->private_data = zram;
3118 	snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
3119 	zram_comp_params_reset(zram);
3120 	comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
3121 
3122 	/* Actual capacity set using sysfs (/sys/block/zram<id>/disksize */
3123 	set_capacity(zram->disk, 0);
3124 	ret = device_add_disk(NULL, zram->disk, zram_disk_groups);
3125 	if (ret)
3126 		goto out_cleanup_disk;
3127 
3128 	zram_debugfs_register(zram);
3129 	pr_info("Added device: %s\n", zram->disk->disk_name);
3130 	return device_id;
3131 
3132 out_cleanup_disk:
3133 	put_disk(zram->disk);
3134 out_free_idr:
3135 	idr_remove(&zram_index_idr, device_id);
3136 out_free_dev:
3137 	kfree(zram);
3138 	return ret;
3139 }
3140 
3141 static int zram_remove(struct zram *zram)
3142 {
3143 	bool claimed;
3144 
3145 	mutex_lock(&zram->disk->open_mutex);
3146 	if (disk_openers(zram->disk)) {
3147 		mutex_unlock(&zram->disk->open_mutex);
3148 		return -EBUSY;
3149 	}
3150 
3151 	claimed = zram->claim;
3152 	if (!claimed)
3153 		zram->claim = true;
3154 	mutex_unlock(&zram->disk->open_mutex);
3155 
3156 	zram_debugfs_unregister(zram);
3157 
3158 	if (claimed) {
3159 		/*
3160 		 * If we were claimed by reset_store(), del_gendisk() will
3161 		 * wait until reset_store() is done, so nothing need to do.
3162 		 */
3163 		;
3164 	} else {
3165 		/* Make sure all the pending I/O are finished */
3166 		sync_blockdev(zram->disk->part0);
3167 		zram_reset_device(zram);
3168 	}
3169 
3170 	pr_info("Removed device: %s\n", zram->disk->disk_name);
3171 
3172 	del_gendisk(zram->disk);
3173 
3174 	/* del_gendisk drains pending reset_store */
3175 	WARN_ON_ONCE(claimed && zram->claim);
3176 
3177 	/*
3178 	 * disksize_store() may be called in between zram_reset_device()
3179 	 * and del_gendisk(), so run the last reset to avoid leaking
3180 	 * anything allocated with disksize_store()
3181 	 */
3182 	zram_reset_device(zram);
3183 
3184 	put_disk(zram->disk);
3185 	kfree(zram);
3186 	return 0;
3187 }
3188 
3189 /* zram-control sysfs attributes */
3190 
3191 /*
3192  * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
3193  * sense that reading from this file does alter the state of your system -- it
3194  * creates a new un-initialized zram device and returns back this device's
3195  * device_id (or an error code if it fails to create a new device).
3196  */
3197 static ssize_t hot_add_show(const struct class *class,
3198 			const struct class_attribute *attr,
3199 			char *buf)
3200 {
3201 	int ret;
3202 
3203 	mutex_lock(&zram_index_mutex);
3204 	ret = zram_add();
3205 	mutex_unlock(&zram_index_mutex);
3206 
3207 	if (ret < 0)
3208 		return ret;
3209 	return sysfs_emit(buf, "%d\n", ret);
3210 }
3211 /* This attribute must be set to 0400, so CLASS_ATTR_RO() can not be used */
3212 static struct class_attribute class_attr_hot_add =
3213 	__ATTR(hot_add, 0400, hot_add_show, NULL);
3214 
3215 static ssize_t hot_remove_store(const struct class *class,
3216 			const struct class_attribute *attr,
3217 			const char *buf,
3218 			size_t count)
3219 {
3220 	struct zram *zram;
3221 	int ret, dev_id;
3222 
3223 	/* dev_id is gendisk->first_minor, which is `int' */
3224 	ret = kstrtoint(buf, 10, &dev_id);
3225 	if (ret)
3226 		return ret;
3227 	if (dev_id < 0)
3228 		return -EINVAL;
3229 
3230 	mutex_lock(&zram_index_mutex);
3231 
3232 	zram = idr_find(&zram_index_idr, dev_id);
3233 	if (zram) {
3234 		ret = zram_remove(zram);
3235 		if (!ret)
3236 			idr_remove(&zram_index_idr, dev_id);
3237 	} else {
3238 		ret = -ENODEV;
3239 	}
3240 
3241 	mutex_unlock(&zram_index_mutex);
3242 	return ret ? ret : count;
3243 }
3244 static CLASS_ATTR_WO(hot_remove);
3245 
3246 static struct attribute *zram_control_class_attrs[] = {
3247 	&class_attr_hot_add.attr,
3248 	&class_attr_hot_remove.attr,
3249 	NULL,
3250 };
3251 ATTRIBUTE_GROUPS(zram_control_class);
3252 
3253 static struct class zram_control_class = {
3254 	.name		= "zram-control",
3255 	.class_groups	= zram_control_class_groups,
3256 };
3257 
3258 static int zram_remove_cb(int id, void *ptr, void *data)
3259 {
3260 	WARN_ON_ONCE(zram_remove(ptr));
3261 	return 0;
3262 }
3263 
3264 static void destroy_devices(void)
3265 {
3266 	class_unregister(&zram_control_class);
3267 	idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
3268 	zram_debugfs_destroy();
3269 	idr_destroy(&zram_index_idr);
3270 	unregister_blkdev(zram_major, "zram");
3271 	cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
3272 }
3273 
3274 static int __init zram_init(void)
3275 {
3276 	struct zram_table_entry zram_te;
3277 	int ret;
3278 
3279 	BUILD_BUG_ON(__NR_ZRAM_PAGEFLAGS > sizeof(zram_te.attr.flags) * 8);
3280 
3281 	ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
3282 				      zcomp_cpu_up_prepare, zcomp_cpu_dead);
3283 	if (ret < 0)
3284 		return ret;
3285 
3286 	ret = class_register(&zram_control_class);
3287 	if (ret) {
3288 		pr_err("Unable to register zram-control class\n");
3289 		cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
3290 		return ret;
3291 	}
3292 
3293 	zram_debugfs_create();
3294 	zram_major = register_blkdev(0, "zram");
3295 	if (zram_major <= 0) {
3296 		pr_err("Unable to get major number\n");
3297 		class_unregister(&zram_control_class);
3298 		cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
3299 		return -EBUSY;
3300 	}
3301 
3302 	while (num_devices != 0) {
3303 		mutex_lock(&zram_index_mutex);
3304 		ret = zram_add();
3305 		mutex_unlock(&zram_index_mutex);
3306 		if (ret < 0)
3307 			goto out_error;
3308 		num_devices--;
3309 	}
3310 
3311 	return 0;
3312 
3313 out_error:
3314 	destroy_devices();
3315 	return ret;
3316 }
3317 
3318 static void __exit zram_exit(void)
3319 {
3320 	destroy_devices();
3321 }
3322 
3323 module_init(zram_init);
3324 module_exit(zram_exit);
3325 
3326 module_param(num_devices, uint, 0);
3327 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
3328 
3329 MODULE_LICENSE("Dual BSD/GPL");
3330 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
3331 MODULE_DESCRIPTION("Compressed RAM Block Device");
3332