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