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