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