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