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