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(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 HUGE_WRITEBACK 1
624 #define IDLE_WRITEBACK 2
625
writeback_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)626 static ssize_t writeback_store(struct device *dev,
627 struct device_attribute *attr, const char *buf, size_t len)
628 {
629 struct zram *zram = dev_to_zram(dev);
630 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
631 unsigned long index;
632 struct bio bio;
633 struct bio_vec bio_vec;
634 struct page *page;
635 ssize_t ret = len;
636 int mode;
637 unsigned long blk_idx = 0;
638
639 if (sysfs_streq(buf, "idle"))
640 mode = IDLE_WRITEBACK;
641 else if (sysfs_streq(buf, "huge"))
642 mode = HUGE_WRITEBACK;
643 else
644 return -EINVAL;
645
646 down_read(&zram->init_lock);
647 if (!init_done(zram)) {
648 ret = -EINVAL;
649 goto release_init_lock;
650 }
651
652 if (!zram->backing_dev) {
653 ret = -ENODEV;
654 goto release_init_lock;
655 }
656
657 page = alloc_page(GFP_KERNEL);
658 if (!page) {
659 ret = -ENOMEM;
660 goto release_init_lock;
661 }
662
663 for (index = 0; index < nr_pages; index++) {
664 struct bio_vec bvec;
665
666 bvec.bv_page = page;
667 bvec.bv_len = PAGE_SIZE;
668 bvec.bv_offset = 0;
669
670 spin_lock(&zram->wb_limit_lock);
671 if (zram->wb_limit_enable && !zram->bd_wb_limit) {
672 spin_unlock(&zram->wb_limit_lock);
673 ret = -EIO;
674 break;
675 }
676 spin_unlock(&zram->wb_limit_lock);
677
678 if (!blk_idx) {
679 blk_idx = alloc_block_bdev(zram);
680 if (!blk_idx) {
681 ret = -ENOSPC;
682 break;
683 }
684 }
685
686 zram_slot_lock(zram, index);
687 if (!zram_allocated(zram, index))
688 goto next;
689
690 if (zram_test_flag(zram, index, ZRAM_WB) ||
691 zram_test_flag(zram, index, ZRAM_SAME) ||
692 zram_test_flag(zram, index, ZRAM_UNDER_WB))
693 goto next;
694
695 if (mode == IDLE_WRITEBACK &&
696 !zram_test_flag(zram, index, ZRAM_IDLE))
697 goto next;
698 if (mode == HUGE_WRITEBACK &&
699 !zram_test_flag(zram, index, ZRAM_HUGE))
700 goto next;
701 /*
702 * Clearing ZRAM_UNDER_WB is duty of caller.
703 * IOW, zram_free_page never clear it.
704 */
705 zram_set_flag(zram, index, ZRAM_UNDER_WB);
706 /* Need for hugepage writeback racing */
707 zram_set_flag(zram, index, ZRAM_IDLE);
708 zram_slot_unlock(zram, index);
709 if (zram_bvec_read(zram, &bvec, index, 0, NULL)) {
710 zram_slot_lock(zram, index);
711 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
712 zram_clear_flag(zram, index, ZRAM_IDLE);
713 zram_slot_unlock(zram, index);
714 continue;
715 }
716
717 bio_init(&bio, &bio_vec, 1);
718 bio_set_dev(&bio, zram->bdev);
719 bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
720 bio.bi_opf = REQ_OP_WRITE | REQ_SYNC;
721
722 bio_add_page(&bio, bvec.bv_page, bvec.bv_len,
723 bvec.bv_offset);
724 /*
725 * XXX: A single page IO would be inefficient for write
726 * but it would be not bad as starter.
727 */
728 ret = submit_bio_wait(&bio);
729 if (ret) {
730 zram_slot_lock(zram, index);
731 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
732 zram_clear_flag(zram, index, ZRAM_IDLE);
733 zram_slot_unlock(zram, index);
734 continue;
735 }
736
737 atomic64_inc(&zram->stats.bd_writes);
738 /*
739 * We released zram_slot_lock so need to check if the slot was
740 * changed. If there is freeing for the slot, we can catch it
741 * easily by zram_allocated.
742 * A subtle case is the slot is freed/reallocated/marked as
743 * ZRAM_IDLE again. To close the race, idle_store doesn't
744 * mark ZRAM_IDLE once it found the slot was ZRAM_UNDER_WB.
745 * Thus, we could close the race by checking ZRAM_IDLE bit.
746 */
747 zram_slot_lock(zram, index);
748 if (!zram_allocated(zram, index) ||
749 !zram_test_flag(zram, index, ZRAM_IDLE)) {
750 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
751 zram_clear_flag(zram, index, ZRAM_IDLE);
752 goto next;
753 }
754
755 zram_free_page(zram, index);
756 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
757 zram_set_flag(zram, index, ZRAM_WB);
758 zram_set_element(zram, index, blk_idx);
759 blk_idx = 0;
760 atomic64_inc(&zram->stats.pages_stored);
761 spin_lock(&zram->wb_limit_lock);
762 if (zram->wb_limit_enable && zram->bd_wb_limit > 0)
763 zram->bd_wb_limit -= 1UL << (PAGE_SHIFT - 12);
764 spin_unlock(&zram->wb_limit_lock);
765 next:
766 zram_slot_unlock(zram, index);
767 }
768
769 if (blk_idx)
770 free_block_bdev(zram, blk_idx);
771 __free_page(page);
772 release_init_lock:
773 up_read(&zram->init_lock);
774
775 return ret;
776 }
777
778 struct zram_work {
779 struct work_struct work;
780 struct zram *zram;
781 unsigned long entry;
782 struct bio *bio;
783 struct bio_vec bvec;
784 };
785
786 #if PAGE_SIZE != 4096
zram_sync_read(struct work_struct * work)787 static void zram_sync_read(struct work_struct *work)
788 {
789 struct zram_work *zw = container_of(work, struct zram_work, work);
790 struct zram *zram = zw->zram;
791 unsigned long entry = zw->entry;
792 struct bio *bio = zw->bio;
793
794 read_from_bdev_async(zram, &zw->bvec, entry, bio);
795 }
796
797 /*
798 * Block layer want one ->submit_bio to be active at a time, so if we use
799 * chained IO with parent IO in same context, it's a deadlock. To avoid that,
800 * use a worker thread context.
801 */
read_from_bdev_sync(struct zram * zram,struct bio_vec * bvec,unsigned long entry,struct bio * bio)802 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
803 unsigned long entry, struct bio *bio)
804 {
805 struct zram_work work;
806
807 work.bvec = *bvec;
808 work.zram = zram;
809 work.entry = entry;
810 work.bio = bio;
811
812 INIT_WORK_ONSTACK(&work.work, zram_sync_read);
813 queue_work(system_unbound_wq, &work.work);
814 flush_work(&work.work);
815 destroy_work_on_stack(&work.work);
816
817 return 1;
818 }
819 #else
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 WARN_ON(1);
824 return -EIO;
825 }
826 #endif
827
read_from_bdev(struct zram * zram,struct bio_vec * bvec,unsigned long entry,struct bio * parent,bool sync)828 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
829 unsigned long entry, struct bio *parent, bool sync)
830 {
831 atomic64_inc(&zram->stats.bd_reads);
832 if (sync)
833 return read_from_bdev_sync(zram, bvec, entry, parent);
834 else
835 return read_from_bdev_async(zram, bvec, entry, parent);
836 }
837 #else
reset_bdev(struct zram * zram)838 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)839 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
840 unsigned long entry, struct bio *parent, bool sync)
841 {
842 return -EIO;
843 }
844
free_block_bdev(struct zram * zram,unsigned long blk_idx)845 static void free_block_bdev(struct zram *zram, unsigned long blk_idx) {};
846 #endif
847
848 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
849
850 static struct dentry *zram_debugfs_root;
851
zram_debugfs_create(void)852 static void zram_debugfs_create(void)
853 {
854 zram_debugfs_root = debugfs_create_dir("zram", NULL);
855 }
856
zram_debugfs_destroy(void)857 static void zram_debugfs_destroy(void)
858 {
859 debugfs_remove_recursive(zram_debugfs_root);
860 }
861
zram_accessed(struct zram * zram,u32 index)862 static void zram_accessed(struct zram *zram, u32 index)
863 {
864 zram_clear_flag(zram, index, ZRAM_IDLE);
865 zram->table[index].ac_time = ktime_get_boottime();
866 }
867
read_block_state(struct file * file,char __user * buf,size_t count,loff_t * ppos)868 static ssize_t read_block_state(struct file *file, char __user *buf,
869 size_t count, loff_t *ppos)
870 {
871 char *kbuf;
872 ssize_t index, written = 0;
873 struct zram *zram = file->private_data;
874 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
875 struct timespec64 ts;
876
877 kbuf = kvmalloc(count, GFP_KERNEL);
878 if (!kbuf)
879 return -ENOMEM;
880
881 down_read(&zram->init_lock);
882 if (!init_done(zram)) {
883 up_read(&zram->init_lock);
884 kvfree(kbuf);
885 return -EINVAL;
886 }
887
888 for (index = *ppos; index < nr_pages; index++) {
889 int copied;
890
891 zram_slot_lock(zram, index);
892 if (!zram_allocated(zram, index))
893 goto next;
894
895 ts = ktime_to_timespec64(zram->table[index].ac_time);
896 copied = snprintf(kbuf + written, count,
897 "%12zd %12lld.%06lu %c%c%c%c\n",
898 index, (s64)ts.tv_sec,
899 ts.tv_nsec / NSEC_PER_USEC,
900 zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
901 zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
902 zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
903 zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.');
904
905 if (count < copied) {
906 zram_slot_unlock(zram, index);
907 break;
908 }
909 written += copied;
910 count -= copied;
911 next:
912 zram_slot_unlock(zram, index);
913 *ppos += 1;
914 }
915
916 up_read(&zram->init_lock);
917 if (copy_to_user(buf, kbuf, written))
918 written = -EFAULT;
919 kvfree(kbuf);
920
921 return written;
922 }
923
924 static const struct file_operations proc_zram_block_state_op = {
925 .open = simple_open,
926 .read = read_block_state,
927 .llseek = default_llseek,
928 };
929
zram_debugfs_register(struct zram * zram)930 static void zram_debugfs_register(struct zram *zram)
931 {
932 if (!zram_debugfs_root)
933 return;
934
935 zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
936 zram_debugfs_root);
937 debugfs_create_file("block_state", 0400, zram->debugfs_dir,
938 zram, &proc_zram_block_state_op);
939 }
940
zram_debugfs_unregister(struct zram * zram)941 static void zram_debugfs_unregister(struct zram *zram)
942 {
943 debugfs_remove_recursive(zram->debugfs_dir);
944 }
945 #else
zram_debugfs_create(void)946 static void zram_debugfs_create(void) {};
zram_debugfs_destroy(void)947 static void zram_debugfs_destroy(void) {};
zram_accessed(struct zram * zram,u32 index)948 static void zram_accessed(struct zram *zram, u32 index)
949 {
950 zram_clear_flag(zram, index, ZRAM_IDLE);
951 };
zram_debugfs_register(struct zram * zram)952 static void zram_debugfs_register(struct zram *zram) {};
zram_debugfs_unregister(struct zram * zram)953 static void zram_debugfs_unregister(struct zram *zram) {};
954 #endif
955
956 /*
957 * We switched to per-cpu streams and this attr is not needed anymore.
958 * However, we will keep it around for some time, because:
959 * a) we may revert per-cpu streams in the future
960 * b) it's visible to user space and we need to follow our 2 years
961 * retirement rule; but we already have a number of 'soon to be
962 * altered' attrs, so max_comp_streams need to wait for the next
963 * layoff cycle.
964 */
max_comp_streams_show(struct device * dev,struct device_attribute * attr,char * buf)965 static ssize_t max_comp_streams_show(struct device *dev,
966 struct device_attribute *attr, char *buf)
967 {
968 return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
969 }
970
max_comp_streams_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)971 static ssize_t max_comp_streams_store(struct device *dev,
972 struct device_attribute *attr, const char *buf, size_t len)
973 {
974 return len;
975 }
976
comp_algorithm_show(struct device * dev,struct device_attribute * attr,char * buf)977 static ssize_t comp_algorithm_show(struct device *dev,
978 struct device_attribute *attr, char *buf)
979 {
980 size_t sz;
981 struct zram *zram = dev_to_zram(dev);
982
983 down_read(&zram->init_lock);
984 sz = zcomp_available_show(zram->compressor, buf);
985 up_read(&zram->init_lock);
986
987 return sz;
988 }
989
comp_algorithm_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)990 static ssize_t comp_algorithm_store(struct device *dev,
991 struct device_attribute *attr, const char *buf, size_t len)
992 {
993 struct zram *zram = dev_to_zram(dev);
994 char compressor[ARRAY_SIZE(zram->compressor)];
995 size_t sz;
996
997 strlcpy(compressor, buf, sizeof(compressor));
998 /* ignore trailing newline */
999 sz = strlen(compressor);
1000 if (sz > 0 && compressor[sz - 1] == '\n')
1001 compressor[sz - 1] = 0x00;
1002
1003 if (!zcomp_available_algorithm(compressor))
1004 return -EINVAL;
1005
1006 down_write(&zram->init_lock);
1007 if (init_done(zram)) {
1008 up_write(&zram->init_lock);
1009 pr_info("Can't change algorithm for initialized device\n");
1010 return -EBUSY;
1011 }
1012
1013 strcpy(zram->compressor, compressor);
1014 up_write(&zram->init_lock);
1015 return len;
1016 }
1017
compact_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1018 static ssize_t compact_store(struct device *dev,
1019 struct device_attribute *attr, const char *buf, size_t len)
1020 {
1021 struct zram *zram = dev_to_zram(dev);
1022
1023 down_read(&zram->init_lock);
1024 if (!init_done(zram)) {
1025 up_read(&zram->init_lock);
1026 return -EINVAL;
1027 }
1028
1029 zs_compact(zram->mem_pool);
1030 up_read(&zram->init_lock);
1031
1032 return len;
1033 }
1034
io_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1035 static ssize_t io_stat_show(struct device *dev,
1036 struct device_attribute *attr, char *buf)
1037 {
1038 struct zram *zram = dev_to_zram(dev);
1039 ssize_t ret;
1040
1041 down_read(&zram->init_lock);
1042 ret = scnprintf(buf, PAGE_SIZE,
1043 "%8llu %8llu %8llu %8llu\n",
1044 (u64)atomic64_read(&zram->stats.failed_reads),
1045 (u64)atomic64_read(&zram->stats.failed_writes),
1046 (u64)atomic64_read(&zram->stats.invalid_io),
1047 (u64)atomic64_read(&zram->stats.notify_free));
1048 up_read(&zram->init_lock);
1049
1050 return ret;
1051 }
1052
mm_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1053 static ssize_t mm_stat_show(struct device *dev,
1054 struct device_attribute *attr, char *buf)
1055 {
1056 struct zram *zram = dev_to_zram(dev);
1057 struct zs_pool_stats pool_stats;
1058 u64 orig_size, mem_used = 0;
1059 long max_used;
1060 ssize_t ret;
1061
1062 memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1063
1064 down_read(&zram->init_lock);
1065 if (init_done(zram)) {
1066 mem_used = zs_get_total_pages(zram->mem_pool);
1067 zs_pool_stats(zram->mem_pool, &pool_stats);
1068 }
1069
1070 orig_size = atomic64_read(&zram->stats.pages_stored);
1071 max_used = atomic_long_read(&zram->stats.max_used_pages);
1072
1073 ret = scnprintf(buf, PAGE_SIZE,
1074 "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu\n",
1075 orig_size << PAGE_SHIFT,
1076 (u64)atomic64_read(&zram->stats.compr_data_size),
1077 mem_used << PAGE_SHIFT,
1078 zram->limit_pages << PAGE_SHIFT,
1079 max_used << PAGE_SHIFT,
1080 (u64)atomic64_read(&zram->stats.same_pages),
1081 pool_stats.pages_compacted,
1082 (u64)atomic64_read(&zram->stats.huge_pages));
1083 up_read(&zram->init_lock);
1084
1085 return ret;
1086 }
1087
1088 #ifdef CONFIG_ZRAM_WRITEBACK
1089 #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
bd_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1090 static ssize_t bd_stat_show(struct device *dev,
1091 struct device_attribute *attr, char *buf)
1092 {
1093 struct zram *zram = dev_to_zram(dev);
1094 ssize_t ret;
1095
1096 down_read(&zram->init_lock);
1097 ret = scnprintf(buf, PAGE_SIZE,
1098 "%8llu %8llu %8llu\n",
1099 FOUR_K((u64)atomic64_read(&zram->stats.bd_count)),
1100 FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)),
1101 FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)));
1102 up_read(&zram->init_lock);
1103
1104 return ret;
1105 }
1106 #endif
1107
debug_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1108 static ssize_t debug_stat_show(struct device *dev,
1109 struct device_attribute *attr, char *buf)
1110 {
1111 int version = 1;
1112 struct zram *zram = dev_to_zram(dev);
1113 ssize_t ret;
1114
1115 down_read(&zram->init_lock);
1116 ret = scnprintf(buf, PAGE_SIZE,
1117 "version: %d\n%8llu %8llu\n",
1118 version,
1119 (u64)atomic64_read(&zram->stats.writestall),
1120 (u64)atomic64_read(&zram->stats.miss_free));
1121 up_read(&zram->init_lock);
1122
1123 return ret;
1124 }
1125
1126 static DEVICE_ATTR_RO(io_stat);
1127 static DEVICE_ATTR_RO(mm_stat);
1128 #ifdef CONFIG_ZRAM_WRITEBACK
1129 static DEVICE_ATTR_RO(bd_stat);
1130 #endif
1131 static DEVICE_ATTR_RO(debug_stat);
1132
zram_meta_free(struct zram * zram,u64 disksize)1133 static void zram_meta_free(struct zram *zram, u64 disksize)
1134 {
1135 size_t num_pages = disksize >> PAGE_SHIFT;
1136 size_t index;
1137
1138 /* Free all pages that are still in this zram device */
1139 for (index = 0; index < num_pages; index++)
1140 zram_free_page(zram, index);
1141
1142 zs_destroy_pool(zram->mem_pool);
1143 vfree(zram->table);
1144 }
1145
zram_meta_alloc(struct zram * zram,u64 disksize)1146 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
1147 {
1148 size_t num_pages;
1149
1150 num_pages = disksize >> PAGE_SHIFT;
1151 zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
1152 if (!zram->table)
1153 return false;
1154
1155 zram->mem_pool = zs_create_pool(zram->disk->disk_name);
1156 if (!zram->mem_pool) {
1157 vfree(zram->table);
1158 return false;
1159 }
1160
1161 if (!huge_class_size)
1162 huge_class_size = zs_huge_class_size(zram->mem_pool);
1163 return true;
1164 }
1165
1166 /*
1167 * To protect concurrent access to the same index entry,
1168 * caller should hold this table index entry's bit_spinlock to
1169 * indicate this index entry is accessing.
1170 */
zram_free_page(struct zram * zram,size_t index)1171 static void zram_free_page(struct zram *zram, size_t index)
1172 {
1173 unsigned long handle;
1174
1175 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
1176 zram->table[index].ac_time = 0;
1177 #endif
1178 if (zram_test_flag(zram, index, ZRAM_IDLE))
1179 zram_clear_flag(zram, index, ZRAM_IDLE);
1180
1181 if (zram_test_flag(zram, index, ZRAM_HUGE)) {
1182 zram_clear_flag(zram, index, ZRAM_HUGE);
1183 atomic64_dec(&zram->stats.huge_pages);
1184 }
1185
1186 if (zram_test_flag(zram, index, ZRAM_WB)) {
1187 zram_clear_flag(zram, index, ZRAM_WB);
1188 free_block_bdev(zram, zram_get_element(zram, index));
1189 goto out;
1190 }
1191
1192 /*
1193 * No memory is allocated for same element filled pages.
1194 * Simply clear same page flag.
1195 */
1196 if (zram_test_flag(zram, index, ZRAM_SAME)) {
1197 zram_clear_flag(zram, index, ZRAM_SAME);
1198 atomic64_dec(&zram->stats.same_pages);
1199 goto out;
1200 }
1201
1202 handle = zram_get_handle(zram, index);
1203 if (!handle)
1204 return;
1205
1206 zs_free(zram->mem_pool, handle);
1207
1208 atomic64_sub(zram_get_obj_size(zram, index),
1209 &zram->stats.compr_data_size);
1210 out:
1211 atomic64_dec(&zram->stats.pages_stored);
1212 zram_set_handle(zram, index, 0);
1213 zram_set_obj_size(zram, index, 0);
1214 WARN_ON_ONCE(zram->table[index].flags &
1215 ~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB));
1216 }
1217
__zram_bvec_read(struct zram * zram,struct page * page,u32 index,struct bio * bio,bool partial_io)1218 static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index,
1219 struct bio *bio, bool partial_io)
1220 {
1221 struct zcomp_strm *zstrm;
1222 unsigned long handle;
1223 unsigned int size;
1224 void *src, *dst;
1225 int ret;
1226
1227 zram_slot_lock(zram, index);
1228 if (zram_test_flag(zram, index, ZRAM_WB)) {
1229 struct bio_vec bvec;
1230
1231 zram_slot_unlock(zram, index);
1232
1233 bvec.bv_page = page;
1234 bvec.bv_len = PAGE_SIZE;
1235 bvec.bv_offset = 0;
1236 return read_from_bdev(zram, &bvec,
1237 zram_get_element(zram, index),
1238 bio, partial_io);
1239 }
1240
1241 handle = zram_get_handle(zram, index);
1242 if (!handle || zram_test_flag(zram, index, ZRAM_SAME)) {
1243 unsigned long value;
1244 void *mem;
1245
1246 value = handle ? zram_get_element(zram, index) : 0;
1247 mem = kmap_atomic(page);
1248 zram_fill_page(mem, PAGE_SIZE, value);
1249 kunmap_atomic(mem);
1250 zram_slot_unlock(zram, index);
1251 return 0;
1252 }
1253
1254 size = zram_get_obj_size(zram, index);
1255
1256 if (size != PAGE_SIZE)
1257 zstrm = zcomp_stream_get(zram->comp);
1258
1259 src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
1260 if (size == PAGE_SIZE) {
1261 dst = kmap_atomic(page);
1262 memcpy(dst, src, PAGE_SIZE);
1263 kunmap_atomic(dst);
1264 ret = 0;
1265 } else {
1266 dst = kmap_atomic(page);
1267 ret = zcomp_decompress(zstrm, src, size, dst);
1268 kunmap_atomic(dst);
1269 zcomp_stream_put(zram->comp);
1270 }
1271 zs_unmap_object(zram->mem_pool, handle);
1272 zram_slot_unlock(zram, index);
1273
1274 /* Should NEVER happen. Return bio error if it does. */
1275 if (WARN_ON(ret))
1276 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1277
1278 return ret;
1279 }
1280
zram_bvec_read(struct zram * zram,struct bio_vec * bvec,u32 index,int offset,struct bio * bio)1281 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1282 u32 index, int offset, struct bio *bio)
1283 {
1284 int ret;
1285 struct page *page;
1286
1287 page = bvec->bv_page;
1288 if (is_partial_io(bvec)) {
1289 /* Use a temporary buffer to decompress the page */
1290 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1291 if (!page)
1292 return -ENOMEM;
1293 }
1294
1295 ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec));
1296 if (unlikely(ret))
1297 goto out;
1298
1299 if (is_partial_io(bvec)) {
1300 void *dst = kmap_atomic(bvec->bv_page);
1301 void *src = kmap_atomic(page);
1302
1303 memcpy(dst + bvec->bv_offset, src + offset, bvec->bv_len);
1304 kunmap_atomic(src);
1305 kunmap_atomic(dst);
1306 }
1307 out:
1308 if (is_partial_io(bvec))
1309 __free_page(page);
1310
1311 return ret;
1312 }
1313
__zram_bvec_write(struct zram * zram,struct bio_vec * bvec,u32 index,struct bio * bio)1314 static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1315 u32 index, struct bio *bio)
1316 {
1317 int ret = 0;
1318 unsigned long alloced_pages;
1319 unsigned long handle = 0;
1320 unsigned int comp_len = 0;
1321 void *src, *dst, *mem;
1322 struct zcomp_strm *zstrm;
1323 struct page *page = bvec->bv_page;
1324 unsigned long element = 0;
1325 enum zram_pageflags flags = 0;
1326
1327 mem = kmap_atomic(page);
1328 if (page_same_filled(mem, &element)) {
1329 kunmap_atomic(mem);
1330 /* Free memory associated with this sector now. */
1331 flags = ZRAM_SAME;
1332 atomic64_inc(&zram->stats.same_pages);
1333 goto out;
1334 }
1335 kunmap_atomic(mem);
1336
1337 compress_again:
1338 zstrm = zcomp_stream_get(zram->comp);
1339 src = kmap_atomic(page);
1340 ret = zcomp_compress(zstrm, src, &comp_len);
1341 kunmap_atomic(src);
1342
1343 if (unlikely(ret)) {
1344 zcomp_stream_put(zram->comp);
1345 pr_err("Compression failed! err=%d\n", ret);
1346 zs_free(zram->mem_pool, handle);
1347 return ret;
1348 }
1349
1350 if (comp_len >= huge_class_size)
1351 comp_len = PAGE_SIZE;
1352 /*
1353 * handle allocation has 2 paths:
1354 * a) fast path is executed with preemption disabled (for
1355 * per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
1356 * since we can't sleep;
1357 * b) slow path enables preemption and attempts to allocate
1358 * the page with __GFP_DIRECT_RECLAIM bit set. we have to
1359 * put per-cpu compression stream and, thus, to re-do
1360 * the compression once handle is allocated.
1361 *
1362 * if we have a 'non-null' handle here then we are coming
1363 * from the slow path and handle has already been allocated.
1364 */
1365 if (!handle)
1366 handle = zs_malloc(zram->mem_pool, comp_len,
1367 __GFP_KSWAPD_RECLAIM |
1368 __GFP_NOWARN |
1369 __GFP_HIGHMEM |
1370 __GFP_MOVABLE);
1371 if (!handle) {
1372 zcomp_stream_put(zram->comp);
1373 atomic64_inc(&zram->stats.writestall);
1374 handle = zs_malloc(zram->mem_pool, comp_len,
1375 GFP_NOIO | __GFP_HIGHMEM |
1376 __GFP_MOVABLE);
1377 if (handle)
1378 goto compress_again;
1379 return -ENOMEM;
1380 }
1381
1382 alloced_pages = zs_get_total_pages(zram->mem_pool);
1383 update_used_max(zram, alloced_pages);
1384
1385 if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1386 zcomp_stream_put(zram->comp);
1387 zs_free(zram->mem_pool, handle);
1388 return -ENOMEM;
1389 }
1390
1391 dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1392
1393 src = zstrm->buffer;
1394 if (comp_len == PAGE_SIZE)
1395 src = kmap_atomic(page);
1396 memcpy(dst, src, comp_len);
1397 if (comp_len == PAGE_SIZE)
1398 kunmap_atomic(src);
1399
1400 zcomp_stream_put(zram->comp);
1401 zs_unmap_object(zram->mem_pool, handle);
1402 atomic64_add(comp_len, &zram->stats.compr_data_size);
1403 out:
1404 /*
1405 * Free memory associated with this sector
1406 * before overwriting unused sectors.
1407 */
1408 zram_slot_lock(zram, index);
1409 zram_free_page(zram, index);
1410
1411 if (comp_len == PAGE_SIZE) {
1412 zram_set_flag(zram, index, ZRAM_HUGE);
1413 atomic64_inc(&zram->stats.huge_pages);
1414 }
1415
1416 if (flags) {
1417 zram_set_flag(zram, index, flags);
1418 zram_set_element(zram, index, element);
1419 } else {
1420 zram_set_handle(zram, index, handle);
1421 zram_set_obj_size(zram, index, comp_len);
1422 }
1423 zram_slot_unlock(zram, index);
1424
1425 /* Update stats */
1426 atomic64_inc(&zram->stats.pages_stored);
1427 return ret;
1428 }
1429
zram_bvec_write(struct zram * zram,struct bio_vec * bvec,u32 index,int offset,struct bio * bio)1430 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1431 u32 index, int offset, struct bio *bio)
1432 {
1433 int ret;
1434 struct page *page = NULL;
1435 void *src;
1436 struct bio_vec vec;
1437
1438 vec = *bvec;
1439 if (is_partial_io(bvec)) {
1440 void *dst;
1441 /*
1442 * This is a partial IO. We need to read the full page
1443 * before to write the changes.
1444 */
1445 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1446 if (!page)
1447 return -ENOMEM;
1448
1449 ret = __zram_bvec_read(zram, page, index, bio, true);
1450 if (ret)
1451 goto out;
1452
1453 src = kmap_atomic(bvec->bv_page);
1454 dst = kmap_atomic(page);
1455 memcpy(dst + offset, src + bvec->bv_offset, bvec->bv_len);
1456 kunmap_atomic(dst);
1457 kunmap_atomic(src);
1458
1459 vec.bv_page = page;
1460 vec.bv_len = PAGE_SIZE;
1461 vec.bv_offset = 0;
1462 }
1463
1464 ret = __zram_bvec_write(zram, &vec, index, bio);
1465 out:
1466 if (is_partial_io(bvec))
1467 __free_page(page);
1468 return ret;
1469 }
1470
1471 /*
1472 * zram_bio_discard - handler on discard request
1473 * @index: physical block index in PAGE_SIZE units
1474 * @offset: byte offset within physical block
1475 */
zram_bio_discard(struct zram * zram,u32 index,int offset,struct bio * bio)1476 static void zram_bio_discard(struct zram *zram, u32 index,
1477 int offset, struct bio *bio)
1478 {
1479 size_t n = bio->bi_iter.bi_size;
1480
1481 /*
1482 * zram manages data in physical block size units. Because logical block
1483 * size isn't identical with physical block size on some arch, we
1484 * could get a discard request pointing to a specific offset within a
1485 * certain physical block. Although we can handle this request by
1486 * reading that physiclal block and decompressing and partially zeroing
1487 * and re-compressing and then re-storing it, this isn't reasonable
1488 * because our intent with a discard request is to save memory. So
1489 * skipping this logical block is appropriate here.
1490 */
1491 if (offset) {
1492 if (n <= (PAGE_SIZE - offset))
1493 return;
1494
1495 n -= (PAGE_SIZE - offset);
1496 index++;
1497 }
1498
1499 while (n >= PAGE_SIZE) {
1500 zram_slot_lock(zram, index);
1501 zram_free_page(zram, index);
1502 zram_slot_unlock(zram, index);
1503 atomic64_inc(&zram->stats.notify_free);
1504 index++;
1505 n -= PAGE_SIZE;
1506 }
1507 }
1508
1509 /*
1510 * Returns errno if it has some problem. Otherwise return 0 or 1.
1511 * Returns 0 if IO request was done synchronously
1512 * Returns 1 if IO request was successfully submitted.
1513 */
zram_bvec_rw(struct zram * zram,struct bio_vec * bvec,u32 index,int offset,unsigned int op,struct bio * bio)1514 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
1515 int offset, unsigned int op, struct bio *bio)
1516 {
1517 int ret;
1518
1519 if (!op_is_write(op)) {
1520 atomic64_inc(&zram->stats.num_reads);
1521 ret = zram_bvec_read(zram, bvec, index, offset, bio);
1522 flush_dcache_page(bvec->bv_page);
1523 } else {
1524 atomic64_inc(&zram->stats.num_writes);
1525 ret = zram_bvec_write(zram, bvec, index, offset, bio);
1526 }
1527
1528 zram_slot_lock(zram, index);
1529 zram_accessed(zram, index);
1530 zram_slot_unlock(zram, index);
1531
1532 if (unlikely(ret < 0)) {
1533 if (!op_is_write(op))
1534 atomic64_inc(&zram->stats.failed_reads);
1535 else
1536 atomic64_inc(&zram->stats.failed_writes);
1537 }
1538
1539 return ret;
1540 }
1541
__zram_make_request(struct zram * zram,struct bio * bio)1542 static void __zram_make_request(struct zram *zram, struct bio *bio)
1543 {
1544 int offset;
1545 u32 index;
1546 struct bio_vec bvec;
1547 struct bvec_iter iter;
1548 unsigned long start_time;
1549
1550 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1551 offset = (bio->bi_iter.bi_sector &
1552 (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1553
1554 switch (bio_op(bio)) {
1555 case REQ_OP_DISCARD:
1556 case REQ_OP_WRITE_ZEROES:
1557 zram_bio_discard(zram, index, offset, bio);
1558 bio_endio(bio);
1559 return;
1560 default:
1561 break;
1562 }
1563
1564 start_time = bio_start_io_acct(bio);
1565 bio_for_each_segment(bvec, bio, iter) {
1566 struct bio_vec bv = bvec;
1567 unsigned int unwritten = bvec.bv_len;
1568
1569 do {
1570 bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
1571 unwritten);
1572 if (zram_bvec_rw(zram, &bv, index, offset,
1573 bio_op(bio), bio) < 0) {
1574 bio->bi_status = BLK_STS_IOERR;
1575 break;
1576 }
1577
1578 bv.bv_offset += bv.bv_len;
1579 unwritten -= bv.bv_len;
1580
1581 update_position(&index, &offset, &bv);
1582 } while (unwritten);
1583 }
1584 bio_end_io_acct(bio, start_time);
1585 bio_endio(bio);
1586 }
1587
1588 /*
1589 * Handler function for all zram I/O requests.
1590 */
zram_submit_bio(struct bio * bio)1591 static blk_qc_t zram_submit_bio(struct bio *bio)
1592 {
1593 struct zram *zram = bio->bi_disk->private_data;
1594
1595 if (!valid_io_request(zram, bio->bi_iter.bi_sector,
1596 bio->bi_iter.bi_size)) {
1597 atomic64_inc(&zram->stats.invalid_io);
1598 goto error;
1599 }
1600
1601 __zram_make_request(zram, bio);
1602 return BLK_QC_T_NONE;
1603
1604 error:
1605 bio_io_error(bio);
1606 return BLK_QC_T_NONE;
1607 }
1608
zram_slot_free_notify(struct block_device * bdev,unsigned long index)1609 static void zram_slot_free_notify(struct block_device *bdev,
1610 unsigned long index)
1611 {
1612 struct zram *zram;
1613
1614 zram = bdev->bd_disk->private_data;
1615
1616 atomic64_inc(&zram->stats.notify_free);
1617 if (!zram_slot_trylock(zram, index)) {
1618 atomic64_inc(&zram->stats.miss_free);
1619 return;
1620 }
1621
1622 zram_free_page(zram, index);
1623 zram_slot_unlock(zram, index);
1624 }
1625
zram_rw_page(struct block_device * bdev,sector_t sector,struct page * page,unsigned int op)1626 static int zram_rw_page(struct block_device *bdev, sector_t sector,
1627 struct page *page, unsigned int op)
1628 {
1629 int offset, ret;
1630 u32 index;
1631 struct zram *zram;
1632 struct bio_vec bv;
1633 unsigned long start_time;
1634
1635 if (PageTransHuge(page))
1636 return -ENOTSUPP;
1637 zram = bdev->bd_disk->private_data;
1638
1639 if (!valid_io_request(zram, sector, PAGE_SIZE)) {
1640 atomic64_inc(&zram->stats.invalid_io);
1641 ret = -EINVAL;
1642 goto out;
1643 }
1644
1645 index = sector >> SECTORS_PER_PAGE_SHIFT;
1646 offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1647
1648 bv.bv_page = page;
1649 bv.bv_len = PAGE_SIZE;
1650 bv.bv_offset = 0;
1651
1652 start_time = disk_start_io_acct(bdev->bd_disk, SECTORS_PER_PAGE, op);
1653 ret = zram_bvec_rw(zram, &bv, index, offset, op, NULL);
1654 disk_end_io_acct(bdev->bd_disk, op, start_time);
1655 out:
1656 /*
1657 * If I/O fails, just return error(ie, non-zero) without
1658 * calling page_endio.
1659 * It causes resubmit the I/O with bio request by upper functions
1660 * of rw_page(e.g., swap_readpage, __swap_writepage) and
1661 * bio->bi_end_io does things to handle the error
1662 * (e.g., SetPageError, set_page_dirty and extra works).
1663 */
1664 if (unlikely(ret < 0))
1665 return ret;
1666
1667 switch (ret) {
1668 case 0:
1669 page_endio(page, op_is_write(op), 0);
1670 break;
1671 case 1:
1672 ret = 0;
1673 break;
1674 default:
1675 WARN_ON(1);
1676 }
1677 return ret;
1678 }
1679
zram_reset_device(struct zram * zram)1680 static void zram_reset_device(struct zram *zram)
1681 {
1682 struct zcomp *comp;
1683 u64 disksize;
1684
1685 down_write(&zram->init_lock);
1686
1687 zram->limit_pages = 0;
1688
1689 if (!init_done(zram)) {
1690 up_write(&zram->init_lock);
1691 return;
1692 }
1693
1694 comp = zram->comp;
1695 disksize = zram->disksize;
1696 zram->disksize = 0;
1697
1698 set_capacity(zram->disk, 0);
1699 part_stat_set_all(&zram->disk->part0, 0);
1700
1701 up_write(&zram->init_lock);
1702 /* I/O operation under all of CPU are done so let's free */
1703 zram_meta_free(zram, disksize);
1704 memset(&zram->stats, 0, sizeof(zram->stats));
1705 zcomp_destroy(comp);
1706 reset_bdev(zram);
1707 }
1708
disksize_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1709 static ssize_t disksize_store(struct device *dev,
1710 struct device_attribute *attr, const char *buf, size_t len)
1711 {
1712 u64 disksize;
1713 struct zcomp *comp;
1714 struct zram *zram = dev_to_zram(dev);
1715 int err;
1716
1717 disksize = memparse(buf, NULL);
1718 if (!disksize)
1719 return -EINVAL;
1720
1721 down_write(&zram->init_lock);
1722 if (init_done(zram)) {
1723 pr_info("Cannot change disksize for initialized device\n");
1724 err = -EBUSY;
1725 goto out_unlock;
1726 }
1727
1728 disksize = PAGE_ALIGN(disksize);
1729 if (!zram_meta_alloc(zram, disksize)) {
1730 err = -ENOMEM;
1731 goto out_unlock;
1732 }
1733
1734 comp = zcomp_create(zram->compressor);
1735 if (IS_ERR(comp)) {
1736 pr_err("Cannot initialise %s compressing backend\n",
1737 zram->compressor);
1738 err = PTR_ERR(comp);
1739 goto out_free_meta;
1740 }
1741
1742 zram->comp = comp;
1743 zram->disksize = disksize;
1744 set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
1745
1746 revalidate_disk_size(zram->disk, true);
1747 up_write(&zram->init_lock);
1748
1749 return len;
1750
1751 out_free_meta:
1752 zram_meta_free(zram, disksize);
1753 out_unlock:
1754 up_write(&zram->init_lock);
1755 return err;
1756 }
1757
reset_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1758 static ssize_t reset_store(struct device *dev,
1759 struct device_attribute *attr, const char *buf, size_t len)
1760 {
1761 int ret;
1762 unsigned short do_reset;
1763 struct zram *zram;
1764 struct block_device *bdev;
1765
1766 ret = kstrtou16(buf, 10, &do_reset);
1767 if (ret)
1768 return ret;
1769
1770 if (!do_reset)
1771 return -EINVAL;
1772
1773 zram = dev_to_zram(dev);
1774 bdev = bdget_disk(zram->disk, 0);
1775 if (!bdev)
1776 return -ENOMEM;
1777
1778 mutex_lock(&bdev->bd_mutex);
1779 /* Do not reset an active device or claimed device */
1780 if (bdev->bd_openers || zram->claim) {
1781 mutex_unlock(&bdev->bd_mutex);
1782 bdput(bdev);
1783 return -EBUSY;
1784 }
1785
1786 /* From now on, anyone can't open /dev/zram[0-9] */
1787 zram->claim = true;
1788 mutex_unlock(&bdev->bd_mutex);
1789
1790 /* Make sure all the pending I/O are finished */
1791 fsync_bdev(bdev);
1792 zram_reset_device(zram);
1793 revalidate_disk_size(zram->disk, true);
1794 bdput(bdev);
1795
1796 mutex_lock(&bdev->bd_mutex);
1797 zram->claim = false;
1798 mutex_unlock(&bdev->bd_mutex);
1799
1800 return len;
1801 }
1802
zram_open(struct block_device * bdev,fmode_t mode)1803 static int zram_open(struct block_device *bdev, fmode_t mode)
1804 {
1805 int ret = 0;
1806 struct zram *zram;
1807
1808 WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
1809
1810 zram = bdev->bd_disk->private_data;
1811 /* zram was claimed to reset so open request fails */
1812 if (zram->claim)
1813 ret = -EBUSY;
1814
1815 return ret;
1816 }
1817
1818 static const struct block_device_operations zram_devops = {
1819 .open = zram_open,
1820 .submit_bio = zram_submit_bio,
1821 .swap_slot_free_notify = zram_slot_free_notify,
1822 .rw_page = zram_rw_page,
1823 .owner = THIS_MODULE
1824 };
1825
1826 static const struct block_device_operations zram_wb_devops = {
1827 .open = zram_open,
1828 .submit_bio = zram_submit_bio,
1829 .swap_slot_free_notify = zram_slot_free_notify,
1830 .owner = THIS_MODULE
1831 };
1832
1833 static DEVICE_ATTR_WO(compact);
1834 static DEVICE_ATTR_RW(disksize);
1835 static DEVICE_ATTR_RO(initstate);
1836 static DEVICE_ATTR_WO(reset);
1837 static DEVICE_ATTR_WO(mem_limit);
1838 static DEVICE_ATTR_WO(mem_used_max);
1839 static DEVICE_ATTR_WO(idle);
1840 static DEVICE_ATTR_RW(max_comp_streams);
1841 static DEVICE_ATTR_RW(comp_algorithm);
1842 #ifdef CONFIG_ZRAM_WRITEBACK
1843 static DEVICE_ATTR_RW(backing_dev);
1844 static DEVICE_ATTR_WO(writeback);
1845 static DEVICE_ATTR_RW(writeback_limit);
1846 static DEVICE_ATTR_RW(writeback_limit_enable);
1847 #endif
1848
1849 static struct attribute *zram_disk_attrs[] = {
1850 &dev_attr_disksize.attr,
1851 &dev_attr_initstate.attr,
1852 &dev_attr_reset.attr,
1853 &dev_attr_compact.attr,
1854 &dev_attr_mem_limit.attr,
1855 &dev_attr_mem_used_max.attr,
1856 &dev_attr_idle.attr,
1857 &dev_attr_max_comp_streams.attr,
1858 &dev_attr_comp_algorithm.attr,
1859 #ifdef CONFIG_ZRAM_WRITEBACK
1860 &dev_attr_backing_dev.attr,
1861 &dev_attr_writeback.attr,
1862 &dev_attr_writeback_limit.attr,
1863 &dev_attr_writeback_limit_enable.attr,
1864 #endif
1865 &dev_attr_io_stat.attr,
1866 &dev_attr_mm_stat.attr,
1867 #ifdef CONFIG_ZRAM_WRITEBACK
1868 &dev_attr_bd_stat.attr,
1869 #endif
1870 &dev_attr_debug_stat.attr,
1871 NULL,
1872 };
1873
1874 static const struct attribute_group zram_disk_attr_group = {
1875 .attrs = zram_disk_attrs,
1876 };
1877
1878 static const struct attribute_group *zram_disk_attr_groups[] = {
1879 &zram_disk_attr_group,
1880 NULL,
1881 };
1882
1883 /*
1884 * Allocate and initialize new zram device. the function returns
1885 * '>= 0' device_id upon success, and negative value otherwise.
1886 */
zram_add(void)1887 static int zram_add(void)
1888 {
1889 struct zram *zram;
1890 struct request_queue *queue;
1891 int ret, device_id;
1892
1893 zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1894 if (!zram)
1895 return -ENOMEM;
1896
1897 ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1898 if (ret < 0)
1899 goto out_free_dev;
1900 device_id = ret;
1901
1902 init_rwsem(&zram->init_lock);
1903 #ifdef CONFIG_ZRAM_WRITEBACK
1904 spin_lock_init(&zram->wb_limit_lock);
1905 #endif
1906 queue = blk_alloc_queue(NUMA_NO_NODE);
1907 if (!queue) {
1908 pr_err("Error allocating disk queue for device %d\n",
1909 device_id);
1910 ret = -ENOMEM;
1911 goto out_free_idr;
1912 }
1913
1914 /* gendisk structure */
1915 zram->disk = alloc_disk(1);
1916 if (!zram->disk) {
1917 pr_err("Error allocating disk structure for device %d\n",
1918 device_id);
1919 ret = -ENOMEM;
1920 goto out_free_queue;
1921 }
1922
1923 zram->disk->major = zram_major;
1924 zram->disk->first_minor = device_id;
1925 zram->disk->fops = &zram_devops;
1926 zram->disk->queue = queue;
1927 zram->disk->private_data = zram;
1928 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1929
1930 /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1931 set_capacity(zram->disk, 0);
1932 /* zram devices sort of resembles non-rotational disks */
1933 blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
1934 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1935
1936 /*
1937 * To ensure that we always get PAGE_SIZE aligned
1938 * and n*PAGE_SIZED sized I/O requests.
1939 */
1940 blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1941 blk_queue_logical_block_size(zram->disk->queue,
1942 ZRAM_LOGICAL_BLOCK_SIZE);
1943 blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1944 blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1945 zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1946 blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1947 blk_queue_flag_set(QUEUE_FLAG_DISCARD, zram->disk->queue);
1948
1949 /*
1950 * zram_bio_discard() will clear all logical blocks if logical block
1951 * size is identical with physical block size(PAGE_SIZE). But if it is
1952 * different, we will skip discarding some parts of logical blocks in
1953 * the part of the request range which isn't aligned to physical block
1954 * size. So we can't ensure that all discarded logical blocks are
1955 * zeroed.
1956 */
1957 if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1958 blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
1959
1960 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, zram->disk->queue);
1961 device_add_disk(NULL, zram->disk, zram_disk_attr_groups);
1962
1963 strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1964
1965 zram_debugfs_register(zram);
1966 pr_info("Added device: %s\n", zram->disk->disk_name);
1967 return device_id;
1968
1969 out_free_queue:
1970 blk_cleanup_queue(queue);
1971 out_free_idr:
1972 idr_remove(&zram_index_idr, device_id);
1973 out_free_dev:
1974 kfree(zram);
1975 return ret;
1976 }
1977
zram_remove(struct zram * zram)1978 static int zram_remove(struct zram *zram)
1979 {
1980 struct block_device *bdev;
1981
1982 bdev = bdget_disk(zram->disk, 0);
1983 if (!bdev)
1984 return -ENOMEM;
1985
1986 mutex_lock(&bdev->bd_mutex);
1987 if (bdev->bd_openers || zram->claim) {
1988 mutex_unlock(&bdev->bd_mutex);
1989 bdput(bdev);
1990 return -EBUSY;
1991 }
1992
1993 zram->claim = true;
1994 mutex_unlock(&bdev->bd_mutex);
1995
1996 zram_debugfs_unregister(zram);
1997
1998 /* Make sure all the pending I/O are finished */
1999 fsync_bdev(bdev);
2000 zram_reset_device(zram);
2001 bdput(bdev);
2002
2003 pr_info("Removed device: %s\n", zram->disk->disk_name);
2004
2005 del_gendisk(zram->disk);
2006 blk_cleanup_queue(zram->disk->queue);
2007 put_disk(zram->disk);
2008 kfree(zram);
2009 return 0;
2010 }
2011
2012 /* zram-control sysfs attributes */
2013
2014 /*
2015 * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
2016 * sense that reading from this file does alter the state of your system -- it
2017 * creates a new un-initialized zram device and returns back this device's
2018 * device_id (or an error code if it fails to create a new device).
2019 */
hot_add_show(struct class * class,struct class_attribute * attr,char * buf)2020 static ssize_t hot_add_show(struct class *class,
2021 struct class_attribute *attr,
2022 char *buf)
2023 {
2024 int ret;
2025
2026 mutex_lock(&zram_index_mutex);
2027 ret = zram_add();
2028 mutex_unlock(&zram_index_mutex);
2029
2030 if (ret < 0)
2031 return ret;
2032 return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
2033 }
2034 static struct class_attribute class_attr_hot_add =
2035 __ATTR(hot_add, 0400, hot_add_show, NULL);
2036
hot_remove_store(struct class * class,struct class_attribute * attr,const char * buf,size_t count)2037 static ssize_t hot_remove_store(struct class *class,
2038 struct class_attribute *attr,
2039 const char *buf,
2040 size_t count)
2041 {
2042 struct zram *zram;
2043 int ret, dev_id;
2044
2045 /* dev_id is gendisk->first_minor, which is `int' */
2046 ret = kstrtoint(buf, 10, &dev_id);
2047 if (ret)
2048 return ret;
2049 if (dev_id < 0)
2050 return -EINVAL;
2051
2052 mutex_lock(&zram_index_mutex);
2053
2054 zram = idr_find(&zram_index_idr, dev_id);
2055 if (zram) {
2056 ret = zram_remove(zram);
2057 if (!ret)
2058 idr_remove(&zram_index_idr, dev_id);
2059 } else {
2060 ret = -ENODEV;
2061 }
2062
2063 mutex_unlock(&zram_index_mutex);
2064 return ret ? ret : count;
2065 }
2066 static CLASS_ATTR_WO(hot_remove);
2067
2068 static struct attribute *zram_control_class_attrs[] = {
2069 &class_attr_hot_add.attr,
2070 &class_attr_hot_remove.attr,
2071 NULL,
2072 };
2073 ATTRIBUTE_GROUPS(zram_control_class);
2074
2075 static struct class zram_control_class = {
2076 .name = "zram-control",
2077 .owner = THIS_MODULE,
2078 .class_groups = zram_control_class_groups,
2079 };
2080
zram_remove_cb(int id,void * ptr,void * data)2081 static int zram_remove_cb(int id, void *ptr, void *data)
2082 {
2083 zram_remove(ptr);
2084 return 0;
2085 }
2086
destroy_devices(void)2087 static void destroy_devices(void)
2088 {
2089 class_unregister(&zram_control_class);
2090 idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
2091 zram_debugfs_destroy();
2092 idr_destroy(&zram_index_idr);
2093 unregister_blkdev(zram_major, "zram");
2094 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2095 }
2096
zram_init(void)2097 static int __init zram_init(void)
2098 {
2099 int ret;
2100
2101 ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
2102 zcomp_cpu_up_prepare, zcomp_cpu_dead);
2103 if (ret < 0)
2104 return ret;
2105
2106 ret = class_register(&zram_control_class);
2107 if (ret) {
2108 pr_err("Unable to register zram-control class\n");
2109 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2110 return ret;
2111 }
2112
2113 zram_debugfs_create();
2114 zram_major = register_blkdev(0, "zram");
2115 if (zram_major <= 0) {
2116 pr_err("Unable to get major number\n");
2117 class_unregister(&zram_control_class);
2118 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2119 return -EBUSY;
2120 }
2121
2122 while (num_devices != 0) {
2123 mutex_lock(&zram_index_mutex);
2124 ret = zram_add();
2125 mutex_unlock(&zram_index_mutex);
2126 if (ret < 0)
2127 goto out_error;
2128 num_devices--;
2129 }
2130
2131 return 0;
2132
2133 out_error:
2134 destroy_devices();
2135 return ret;
2136 }
2137
zram_exit(void)2138 static void __exit zram_exit(void)
2139 {
2140 destroy_devices();
2141 }
2142
2143 module_init(zram_init);
2144 module_exit(zram_exit);
2145
2146 module_param(num_devices, uint, 0);
2147 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
2148
2149 MODULE_LICENSE("Dual BSD/GPL");
2150 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2151 MODULE_DESCRIPTION("Compressed RAM Block Device");
2152