zram: write incompressible pages to backing device
[linux-block.git] / drivers / block / zram / zram_drv.c
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/cpuhotplug.h>
35
36 #include "zram_drv.h"
37
38 static DEFINE_IDR(zram_index_idr);
39 /* idr index must be protected */
40 static DEFINE_MUTEX(zram_index_mutex);
41
42 static int zram_major;
43 static const char *default_compressor = "lzo";
44
45 /* Module params (documentation at end) */
46 static unsigned int num_devices = 1;
47
48 static void zram_free_page(struct zram *zram, size_t index);
49
50 static inline bool init_done(struct zram *zram)
51 {
52         return zram->disksize;
53 }
54
55 static inline struct zram *dev_to_zram(struct device *dev)
56 {
57         return (struct zram *)dev_to_disk(dev)->private_data;
58 }
59
60 static unsigned long zram_get_handle(struct zram *zram, u32 index)
61 {
62         return zram->table[index].handle;
63 }
64
65 static void zram_set_handle(struct zram *zram, u32 index, unsigned long handle)
66 {
67         zram->table[index].handle = handle;
68 }
69
70 /* flag operations require table entry bit_spin_lock() being held */
71 static int zram_test_flag(struct zram *zram, u32 index,
72                         enum zram_pageflags flag)
73 {
74         return zram->table[index].value & BIT(flag);
75 }
76
77 static void zram_set_flag(struct zram *zram, u32 index,
78                         enum zram_pageflags flag)
79 {
80         zram->table[index].value |= BIT(flag);
81 }
82
83 static void zram_clear_flag(struct zram *zram, u32 index,
84                         enum zram_pageflags flag)
85 {
86         zram->table[index].value &= ~BIT(flag);
87 }
88
89 static inline void zram_set_element(struct zram *zram, u32 index,
90                         unsigned long element)
91 {
92         zram->table[index].element = element;
93 }
94
95 static unsigned long zram_get_element(struct zram *zram, u32 index)
96 {
97         return zram->table[index].element;
98 }
99
100 static size_t zram_get_obj_size(struct zram *zram, u32 index)
101 {
102         return zram->table[index].value & (BIT(ZRAM_FLAG_SHIFT) - 1);
103 }
104
105 static void zram_set_obj_size(struct zram *zram,
106                                         u32 index, size_t size)
107 {
108         unsigned long flags = zram->table[index].value >> ZRAM_FLAG_SHIFT;
109
110         zram->table[index].value = (flags << ZRAM_FLAG_SHIFT) | size;
111 }
112
113 #if PAGE_SIZE != 4096
114 static inline bool is_partial_io(struct bio_vec *bvec)
115 {
116         return bvec->bv_len != PAGE_SIZE;
117 }
118 #else
119 static inline bool is_partial_io(struct bio_vec *bvec)
120 {
121         return false;
122 }
123 #endif
124
125 static void zram_revalidate_disk(struct zram *zram)
126 {
127         revalidate_disk(zram->disk);
128         /* revalidate_disk reset the BDI_CAP_STABLE_WRITES so set again */
129         zram->disk->queue->backing_dev_info->capabilities |=
130                 BDI_CAP_STABLE_WRITES;
131 }
132
133 /*
134  * Check if request is within bounds and aligned on zram logical blocks.
135  */
136 static inline bool valid_io_request(struct zram *zram,
137                 sector_t start, unsigned int size)
138 {
139         u64 end, bound;
140
141         /* unaligned request */
142         if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
143                 return false;
144         if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
145                 return false;
146
147         end = start + (size >> SECTOR_SHIFT);
148         bound = zram->disksize >> SECTOR_SHIFT;
149         /* out of range range */
150         if (unlikely(start >= bound || end > bound || start > end))
151                 return false;
152
153         /* I/O request is valid */
154         return true;
155 }
156
157 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
158 {
159         *index  += (*offset + bvec->bv_len) / PAGE_SIZE;
160         *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
161 }
162
163 static inline void update_used_max(struct zram *zram,
164                                         const unsigned long pages)
165 {
166         unsigned long old_max, cur_max;
167
168         old_max = atomic_long_read(&zram->stats.max_used_pages);
169
170         do {
171                 cur_max = old_max;
172                 if (pages > cur_max)
173                         old_max = atomic_long_cmpxchg(
174                                 &zram->stats.max_used_pages, cur_max, pages);
175         } while (old_max != cur_max);
176 }
177
178 static inline void zram_fill_page(char *ptr, unsigned long len,
179                                         unsigned long value)
180 {
181         int i;
182         unsigned long *page = (unsigned long *)ptr;
183
184         WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
185
186         if (likely(value == 0)) {
187                 memset(ptr, 0, len);
188         } else {
189                 for (i = 0; i < len / sizeof(*page); i++)
190                         page[i] = value;
191         }
192 }
193
194 static bool page_same_filled(void *ptr, unsigned long *element)
195 {
196         unsigned int pos;
197         unsigned long *page;
198         unsigned long val;
199
200         page = (unsigned long *)ptr;
201         val = page[0];
202
203         for (pos = 1; pos < PAGE_SIZE / sizeof(*page); pos++) {
204                 if (val != page[pos])
205                         return false;
206         }
207
208         *element = val;
209
210         return true;
211 }
212
213 static ssize_t initstate_show(struct device *dev,
214                 struct device_attribute *attr, char *buf)
215 {
216         u32 val;
217         struct zram *zram = dev_to_zram(dev);
218
219         down_read(&zram->init_lock);
220         val = init_done(zram);
221         up_read(&zram->init_lock);
222
223         return scnprintf(buf, PAGE_SIZE, "%u\n", val);
224 }
225
226 static ssize_t disksize_show(struct device *dev,
227                 struct device_attribute *attr, char *buf)
228 {
229         struct zram *zram = dev_to_zram(dev);
230
231         return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
232 }
233
234 static ssize_t mem_limit_store(struct device *dev,
235                 struct device_attribute *attr, const char *buf, size_t len)
236 {
237         u64 limit;
238         char *tmp;
239         struct zram *zram = dev_to_zram(dev);
240
241         limit = memparse(buf, &tmp);
242         if (buf == tmp) /* no chars parsed, invalid input */
243                 return -EINVAL;
244
245         down_write(&zram->init_lock);
246         zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
247         up_write(&zram->init_lock);
248
249         return len;
250 }
251
252 static ssize_t mem_used_max_store(struct device *dev,
253                 struct device_attribute *attr, const char *buf, size_t len)
254 {
255         int err;
256         unsigned long val;
257         struct zram *zram = dev_to_zram(dev);
258
259         err = kstrtoul(buf, 10, &val);
260         if (err || val != 0)
261                 return -EINVAL;
262
263         down_read(&zram->init_lock);
264         if (init_done(zram)) {
265                 atomic_long_set(&zram->stats.max_used_pages,
266                                 zs_get_total_pages(zram->mem_pool));
267         }
268         up_read(&zram->init_lock);
269
270         return len;
271 }
272
273 #ifdef CONFIG_ZRAM_WRITEBACK
274 static bool zram_wb_enabled(struct zram *zram)
275 {
276         return zram->backing_dev;
277 }
278
279 static void reset_bdev(struct zram *zram)
280 {
281         struct block_device *bdev;
282
283         if (!zram_wb_enabled(zram))
284                 return;
285
286         bdev = zram->bdev;
287         if (zram->old_block_size)
288                 set_blocksize(bdev, zram->old_block_size);
289         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
290         /* hope filp_close flush all of IO */
291         filp_close(zram->backing_dev, NULL);
292         zram->backing_dev = NULL;
293         zram->old_block_size = 0;
294         zram->bdev = NULL;
295
296         kvfree(zram->bitmap);
297         zram->bitmap = NULL;
298 }
299
300 static ssize_t backing_dev_show(struct device *dev,
301                 struct device_attribute *attr, char *buf)
302 {
303         struct zram *zram = dev_to_zram(dev);
304         struct file *file = zram->backing_dev;
305         char *p;
306         ssize_t ret;
307
308         down_read(&zram->init_lock);
309         if (!zram_wb_enabled(zram)) {
310                 memcpy(buf, "none\n", 5);
311                 up_read(&zram->init_lock);
312                 return 5;
313         }
314
315         p = file_path(file, buf, PAGE_SIZE - 1);
316         if (IS_ERR(p)) {
317                 ret = PTR_ERR(p);
318                 goto out;
319         }
320
321         ret = strlen(p);
322         memmove(buf, p, ret);
323         buf[ret++] = '\n';
324 out:
325         up_read(&zram->init_lock);
326         return ret;
327 }
328
329 static ssize_t backing_dev_store(struct device *dev,
330                 struct device_attribute *attr, const char *buf, size_t len)
331 {
332         char *file_name;
333         struct file *backing_dev = NULL;
334         struct inode *inode;
335         struct address_space *mapping;
336         unsigned int bitmap_sz, old_block_size = 0;
337         unsigned long nr_pages, *bitmap = NULL;
338         struct block_device *bdev = NULL;
339         int err;
340         struct zram *zram = dev_to_zram(dev);
341
342         file_name = kmalloc(PATH_MAX, GFP_KERNEL);
343         if (!file_name)
344                 return -ENOMEM;
345
346         down_write(&zram->init_lock);
347         if (init_done(zram)) {
348                 pr_info("Can't setup backing device for initialized device\n");
349                 err = -EBUSY;
350                 goto out;
351         }
352
353         strlcpy(file_name, buf, len);
354
355         backing_dev = filp_open(file_name, O_RDWR|O_LARGEFILE, 0);
356         if (IS_ERR(backing_dev)) {
357                 err = PTR_ERR(backing_dev);
358                 backing_dev = NULL;
359                 goto out;
360         }
361
362         mapping = backing_dev->f_mapping;
363         inode = mapping->host;
364
365         /* Support only block device in this moment */
366         if (!S_ISBLK(inode->i_mode)) {
367                 err = -ENOTBLK;
368                 goto out;
369         }
370
371         bdev = bdgrab(I_BDEV(inode));
372         err = blkdev_get(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL, zram);
373         if (err < 0)
374                 goto out;
375
376         nr_pages = i_size_read(inode) >> PAGE_SHIFT;
377         bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
378         bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
379         if (!bitmap) {
380                 err = -ENOMEM;
381                 goto out;
382         }
383
384         old_block_size = block_size(bdev);
385         err = set_blocksize(bdev, PAGE_SIZE);
386         if (err)
387                 goto out;
388
389         reset_bdev(zram);
390         spin_lock_init(&zram->bitmap_lock);
391
392         zram->old_block_size = old_block_size;
393         zram->bdev = bdev;
394         zram->backing_dev = backing_dev;
395         zram->bitmap = bitmap;
396         zram->nr_pages = nr_pages;
397         up_write(&zram->init_lock);
398
399         pr_info("setup backing device %s\n", file_name);
400         kfree(file_name);
401
402         return len;
403 out:
404         if (bitmap)
405                 kvfree(bitmap);
406
407         if (bdev)
408                 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
409
410         if (backing_dev)
411                 filp_close(backing_dev, NULL);
412
413         up_write(&zram->init_lock);
414
415         kfree(file_name);
416
417         return err;
418 }
419
420 static unsigned long get_entry_bdev(struct zram *zram)
421 {
422         unsigned long entry;
423
424         spin_lock(&zram->bitmap_lock);
425         /* skip 0 bit to confuse zram.handle = 0 */
426         entry = find_next_zero_bit(zram->bitmap, zram->nr_pages, 1);
427         if (entry == zram->nr_pages) {
428                 spin_unlock(&zram->bitmap_lock);
429                 return 0;
430         }
431
432         set_bit(entry, zram->bitmap);
433         spin_unlock(&zram->bitmap_lock);
434
435         return entry;
436 }
437
438 static void put_entry_bdev(struct zram *zram, unsigned long entry)
439 {
440         int was_set;
441
442         spin_lock(&zram->bitmap_lock);
443         was_set = test_and_clear_bit(entry, zram->bitmap);
444         spin_unlock(&zram->bitmap_lock);
445         WARN_ON_ONCE(!was_set);
446 }
447
448 void zram_page_end_io(struct bio *bio)
449 {
450         struct page *page = bio->bi_io_vec[0].bv_page;
451
452         page_endio(page, op_is_write(bio_op(bio)),
453                         blk_status_to_errno(bio->bi_status));
454         bio_put(bio);
455 }
456
457 static int write_to_bdev(struct zram *zram, struct bio_vec *bvec,
458                                         u32 index, struct bio *parent,
459                                         unsigned long *pentry)
460 {
461         struct bio *bio;
462         unsigned long entry;
463
464         bio = bio_alloc(GFP_ATOMIC, 1);
465         if (!bio)
466                 return -ENOMEM;
467
468         entry = get_entry_bdev(zram);
469         if (!entry) {
470                 bio_put(bio);
471                 return -ENOSPC;
472         }
473
474         bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
475         bio->bi_bdev = zram->bdev;
476         if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len,
477                                         bvec->bv_offset)) {
478                 bio_put(bio);
479                 put_entry_bdev(zram, entry);
480                 return -EIO;
481         }
482
483         if (!parent) {
484                 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC;
485                 bio->bi_end_io = zram_page_end_io;
486         } else {
487                 bio->bi_opf = parent->bi_opf;
488                 bio_chain(bio, parent);
489         }
490
491         submit_bio(bio);
492         *pentry = entry;
493
494         return 0;
495 }
496
497 static void zram_wb_clear(struct zram *zram, u32 index)
498 {
499         unsigned long entry;
500
501         zram_clear_flag(zram, index, ZRAM_WB);
502         entry = zram_get_element(zram, index);
503         zram_set_element(zram, index, 0);
504         put_entry_bdev(zram, entry);
505 }
506
507 #else
508 static bool zram_wb_enabled(struct zram *zram) { return false; }
509 static inline void reset_bdev(struct zram *zram) {};
510 static int write_to_bdev(struct zram *zram, struct bio_vec *bvec,
511                                         u32 index, struct bio *parent,
512                                         unsigned long *pentry)
513
514 {
515         return -EIO;
516 }
517 static void zram_wb_clear(struct zram *zram, u32 index) {}
518 #endif
519
520
521 /*
522  * We switched to per-cpu streams and this attr is not needed anymore.
523  * However, we will keep it around for some time, because:
524  * a) we may revert per-cpu streams in the future
525  * b) it's visible to user space and we need to follow our 2 years
526  *    retirement rule; but we already have a number of 'soon to be
527  *    altered' attrs, so max_comp_streams need to wait for the next
528  *    layoff cycle.
529  */
530 static ssize_t max_comp_streams_show(struct device *dev,
531                 struct device_attribute *attr, char *buf)
532 {
533         return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
534 }
535
536 static ssize_t max_comp_streams_store(struct device *dev,
537                 struct device_attribute *attr, const char *buf, size_t len)
538 {
539         return len;
540 }
541
542 static ssize_t comp_algorithm_show(struct device *dev,
543                 struct device_attribute *attr, char *buf)
544 {
545         size_t sz;
546         struct zram *zram = dev_to_zram(dev);
547
548         down_read(&zram->init_lock);
549         sz = zcomp_available_show(zram->compressor, buf);
550         up_read(&zram->init_lock);
551
552         return sz;
553 }
554
555 static ssize_t comp_algorithm_store(struct device *dev,
556                 struct device_attribute *attr, const char *buf, size_t len)
557 {
558         struct zram *zram = dev_to_zram(dev);
559         char compressor[ARRAY_SIZE(zram->compressor)];
560         size_t sz;
561
562         strlcpy(compressor, buf, sizeof(compressor));
563         /* ignore trailing newline */
564         sz = strlen(compressor);
565         if (sz > 0 && compressor[sz - 1] == '\n')
566                 compressor[sz - 1] = 0x00;
567
568         if (!zcomp_available_algorithm(compressor))
569                 return -EINVAL;
570
571         down_write(&zram->init_lock);
572         if (init_done(zram)) {
573                 up_write(&zram->init_lock);
574                 pr_info("Can't change algorithm for initialized device\n");
575                 return -EBUSY;
576         }
577
578         strcpy(zram->compressor, compressor);
579         up_write(&zram->init_lock);
580         return len;
581 }
582
583 static ssize_t compact_store(struct device *dev,
584                 struct device_attribute *attr, const char *buf, size_t len)
585 {
586         struct zram *zram = dev_to_zram(dev);
587
588         down_read(&zram->init_lock);
589         if (!init_done(zram)) {
590                 up_read(&zram->init_lock);
591                 return -EINVAL;
592         }
593
594         zs_compact(zram->mem_pool);
595         up_read(&zram->init_lock);
596
597         return len;
598 }
599
600 static ssize_t io_stat_show(struct device *dev,
601                 struct device_attribute *attr, char *buf)
602 {
603         struct zram *zram = dev_to_zram(dev);
604         ssize_t ret;
605
606         down_read(&zram->init_lock);
607         ret = scnprintf(buf, PAGE_SIZE,
608                         "%8llu %8llu %8llu %8llu\n",
609                         (u64)atomic64_read(&zram->stats.failed_reads),
610                         (u64)atomic64_read(&zram->stats.failed_writes),
611                         (u64)atomic64_read(&zram->stats.invalid_io),
612                         (u64)atomic64_read(&zram->stats.notify_free));
613         up_read(&zram->init_lock);
614
615         return ret;
616 }
617
618 static ssize_t mm_stat_show(struct device *dev,
619                 struct device_attribute *attr, char *buf)
620 {
621         struct zram *zram = dev_to_zram(dev);
622         struct zs_pool_stats pool_stats;
623         u64 orig_size, mem_used = 0;
624         long max_used;
625         ssize_t ret;
626
627         memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
628
629         down_read(&zram->init_lock);
630         if (init_done(zram)) {
631                 mem_used = zs_get_total_pages(zram->mem_pool);
632                 zs_pool_stats(zram->mem_pool, &pool_stats);
633         }
634
635         orig_size = atomic64_read(&zram->stats.pages_stored);
636         max_used = atomic_long_read(&zram->stats.max_used_pages);
637
638         ret = scnprintf(buf, PAGE_SIZE,
639                         "%8llu %8llu %8llu %8lu %8ld %8llu %8lu\n",
640                         orig_size << PAGE_SHIFT,
641                         (u64)atomic64_read(&zram->stats.compr_data_size),
642                         mem_used << PAGE_SHIFT,
643                         zram->limit_pages << PAGE_SHIFT,
644                         max_used << PAGE_SHIFT,
645                         (u64)atomic64_read(&zram->stats.same_pages),
646                         pool_stats.pages_compacted);
647         up_read(&zram->init_lock);
648
649         return ret;
650 }
651
652 static ssize_t debug_stat_show(struct device *dev,
653                 struct device_attribute *attr, char *buf)
654 {
655         int version = 1;
656         struct zram *zram = dev_to_zram(dev);
657         ssize_t ret;
658
659         down_read(&zram->init_lock);
660         ret = scnprintf(buf, PAGE_SIZE,
661                         "version: %d\n%8llu\n",
662                         version,
663                         (u64)atomic64_read(&zram->stats.writestall));
664         up_read(&zram->init_lock);
665
666         return ret;
667 }
668
669 static DEVICE_ATTR_RO(io_stat);
670 static DEVICE_ATTR_RO(mm_stat);
671 static DEVICE_ATTR_RO(debug_stat);
672
673 static void zram_slot_lock(struct zram *zram, u32 index)
674 {
675         bit_spin_lock(ZRAM_ACCESS, &zram->table[index].value);
676 }
677
678 static void zram_slot_unlock(struct zram *zram, u32 index)
679 {
680         bit_spin_unlock(ZRAM_ACCESS, &zram->table[index].value);
681 }
682
683 static bool zram_same_page_read(struct zram *zram, u32 index,
684                                 struct page *page,
685                                 unsigned int offset, unsigned int len)
686 {
687         zram_slot_lock(zram, index);
688         if (unlikely(!zram_get_handle(zram, index) ||
689                         zram_test_flag(zram, index, ZRAM_SAME))) {
690                 void *mem;
691
692                 zram_slot_unlock(zram, index);
693                 mem = kmap_atomic(page);
694                 zram_fill_page(mem + offset, len,
695                                         zram_get_element(zram, index));
696                 kunmap_atomic(mem);
697                 return true;
698         }
699         zram_slot_unlock(zram, index);
700
701         return false;
702 }
703
704 static void zram_meta_free(struct zram *zram, u64 disksize)
705 {
706         size_t num_pages = disksize >> PAGE_SHIFT;
707         size_t index;
708
709         /* Free all pages that are still in this zram device */
710         for (index = 0; index < num_pages; index++)
711                 zram_free_page(zram, index);
712
713         zs_destroy_pool(zram->mem_pool);
714         vfree(zram->table);
715 }
716
717 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
718 {
719         size_t num_pages;
720
721         num_pages = disksize >> PAGE_SHIFT;
722         zram->table = vzalloc(num_pages * sizeof(*zram->table));
723         if (!zram->table)
724                 return false;
725
726         zram->mem_pool = zs_create_pool(zram->disk->disk_name);
727         if (!zram->mem_pool) {
728                 vfree(zram->table);
729                 return false;
730         }
731
732         return true;
733 }
734
735 /*
736  * To protect concurrent access to the same index entry,
737  * caller should hold this table index entry's bit_spinlock to
738  * indicate this index entry is accessing.
739  */
740 static void zram_free_page(struct zram *zram, size_t index)
741 {
742         unsigned long handle;
743
744         if (zram_wb_enabled(zram) && zram_test_flag(zram, index, ZRAM_WB)) {
745                 zram_wb_clear(zram, index);
746                 atomic64_dec(&zram->stats.pages_stored);
747                 return;
748         }
749
750         /*
751          * No memory is allocated for same element filled pages.
752          * Simply clear same page flag.
753          */
754         if (zram_test_flag(zram, index, ZRAM_SAME)) {
755                 zram_clear_flag(zram, index, ZRAM_SAME);
756                 zram_set_element(zram, index, 0);
757                 atomic64_dec(&zram->stats.same_pages);
758                 atomic64_dec(&zram->stats.pages_stored);
759                 return;
760         }
761
762         handle = zram_get_handle(zram, index);
763         if (!handle)
764                 return;
765
766         zs_free(zram->mem_pool, handle);
767
768         atomic64_sub(zram_get_obj_size(zram, index),
769                         &zram->stats.compr_data_size);
770         atomic64_dec(&zram->stats.pages_stored);
771
772         zram_set_handle(zram, index, 0);
773         zram_set_obj_size(zram, index, 0);
774 }
775
776 static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index)
777 {
778         int ret;
779         unsigned long handle;
780         unsigned int size;
781         void *src, *dst;
782
783         if (zram_same_page_read(zram, index, page, 0, PAGE_SIZE))
784                 return 0;
785
786         zram_slot_lock(zram, index);
787         handle = zram_get_handle(zram, index);
788         size = zram_get_obj_size(zram, index);
789
790         src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
791         if (size == PAGE_SIZE) {
792                 dst = kmap_atomic(page);
793                 memcpy(dst, src, PAGE_SIZE);
794                 kunmap_atomic(dst);
795                 ret = 0;
796         } else {
797                 struct zcomp_strm *zstrm = zcomp_stream_get(zram->comp);
798
799                 dst = kmap_atomic(page);
800                 ret = zcomp_decompress(zstrm, src, size, dst);
801                 kunmap_atomic(dst);
802                 zcomp_stream_put(zram->comp);
803         }
804         zs_unmap_object(zram->mem_pool, handle);
805         zram_slot_unlock(zram, index);
806
807         /* Should NEVER happen. Return bio error if it does. */
808         if (unlikely(ret))
809                 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
810
811         return ret;
812 }
813
814 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
815                                 u32 index, int offset)
816 {
817         int ret;
818         struct page *page;
819
820         page = bvec->bv_page;
821         if (is_partial_io(bvec)) {
822                 /* Use a temporary buffer to decompress the page */
823                 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
824                 if (!page)
825                         return -ENOMEM;
826         }
827
828         ret = __zram_bvec_read(zram, page, index);
829         if (unlikely(ret))
830                 goto out;
831
832         if (is_partial_io(bvec)) {
833                 void *dst = kmap_atomic(bvec->bv_page);
834                 void *src = kmap_atomic(page);
835
836                 memcpy(dst + bvec->bv_offset, src + offset, bvec->bv_len);
837                 kunmap_atomic(src);
838                 kunmap_atomic(dst);
839         }
840 out:
841         if (is_partial_io(bvec))
842                 __free_page(page);
843
844         return ret;
845 }
846
847 static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
848                                 u32 index, struct bio *bio)
849 {
850         int ret = 0;
851         unsigned long alloced_pages;
852         unsigned long handle = 0;
853         unsigned int comp_len = 0;
854         void *src, *dst, *mem;
855         struct zcomp_strm *zstrm;
856         struct page *page = bvec->bv_page;
857         unsigned long element = 0;
858         enum zram_pageflags flags = 0;
859         bool allow_wb = true;
860
861         mem = kmap_atomic(page);
862         if (page_same_filled(mem, &element)) {
863                 kunmap_atomic(mem);
864                 /* Free memory associated with this sector now. */
865                 flags = ZRAM_SAME;
866                 atomic64_inc(&zram->stats.same_pages);
867                 goto out;
868         }
869         kunmap_atomic(mem);
870
871 compress_again:
872         zstrm = zcomp_stream_get(zram->comp);
873         src = kmap_atomic(page);
874         ret = zcomp_compress(zstrm, src, &comp_len);
875         kunmap_atomic(src);
876
877         if (unlikely(ret)) {
878                 zcomp_stream_put(zram->comp);
879                 pr_err("Compression failed! err=%d\n", ret);
880                 zs_free(zram->mem_pool, handle);
881                 return ret;
882         }
883
884         if (unlikely(comp_len > max_zpage_size)) {
885                 if (zram_wb_enabled(zram) && allow_wb) {
886                         zcomp_stream_put(zram->comp);
887                         ret = write_to_bdev(zram, bvec, index, bio, &element);
888                         if (!ret) {
889                                 flags = ZRAM_WB;
890                                 ret = 1;
891                                 goto out;
892                         }
893                         allow_wb = false;
894                         goto compress_again;
895                 }
896                 comp_len = PAGE_SIZE;
897         }
898
899         /*
900          * handle allocation has 2 paths:
901          * a) fast path is executed with preemption disabled (for
902          *  per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
903          *  since we can't sleep;
904          * b) slow path enables preemption and attempts to allocate
905          *  the page with __GFP_DIRECT_RECLAIM bit set. we have to
906          *  put per-cpu compression stream and, thus, to re-do
907          *  the compression once handle is allocated.
908          *
909          * if we have a 'non-null' handle here then we are coming
910          * from the slow path and handle has already been allocated.
911          */
912         if (!handle)
913                 handle = zs_malloc(zram->mem_pool, comp_len,
914                                 __GFP_KSWAPD_RECLAIM |
915                                 __GFP_NOWARN |
916                                 __GFP_HIGHMEM |
917                                 __GFP_MOVABLE);
918         if (!handle) {
919                 zcomp_stream_put(zram->comp);
920                 atomic64_inc(&zram->stats.writestall);
921                 handle = zs_malloc(zram->mem_pool, comp_len,
922                                 GFP_NOIO | __GFP_HIGHMEM |
923                                 __GFP_MOVABLE);
924                 if (handle)
925                         goto compress_again;
926                 return -ENOMEM;
927         }
928
929         alloced_pages = zs_get_total_pages(zram->mem_pool);
930         update_used_max(zram, alloced_pages);
931
932         if (zram->limit_pages && alloced_pages > zram->limit_pages) {
933                 zcomp_stream_put(zram->comp);
934                 zs_free(zram->mem_pool, handle);
935                 return -ENOMEM;
936         }
937
938         dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
939
940         src = zstrm->buffer;
941         if (comp_len == PAGE_SIZE)
942                 src = kmap_atomic(page);
943         memcpy(dst, src, comp_len);
944         if (comp_len == PAGE_SIZE)
945                 kunmap_atomic(src);
946
947         zcomp_stream_put(zram->comp);
948         zs_unmap_object(zram->mem_pool, handle);
949         atomic64_add(comp_len, &zram->stats.compr_data_size);
950 out:
951         /*
952          * Free memory associated with this sector
953          * before overwriting unused sectors.
954          */
955         zram_slot_lock(zram, index);
956         zram_free_page(zram, index);
957
958         if (flags) {
959                 zram_set_flag(zram, index, flags);
960                 zram_set_element(zram, index, element);
961         }  else {
962                 zram_set_handle(zram, index, handle);
963                 zram_set_obj_size(zram, index, comp_len);
964         }
965         zram_slot_unlock(zram, index);
966
967         /* Update stats */
968         atomic64_inc(&zram->stats.pages_stored);
969         return ret;
970 }
971
972 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
973                                 u32 index, int offset, struct bio *bio)
974 {
975         int ret;
976         struct page *page = NULL;
977         void *src;
978         struct bio_vec vec;
979
980         vec = *bvec;
981         if (is_partial_io(bvec)) {
982                 void *dst;
983                 /*
984                  * This is a partial IO. We need to read the full page
985                  * before to write the changes.
986                  */
987                 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
988                 if (!page)
989                         return -ENOMEM;
990
991                 ret = __zram_bvec_read(zram, page, index);
992                 if (ret)
993                         goto out;
994
995                 src = kmap_atomic(bvec->bv_page);
996                 dst = kmap_atomic(page);
997                 memcpy(dst + offset, src + bvec->bv_offset, bvec->bv_len);
998                 kunmap_atomic(dst);
999                 kunmap_atomic(src);
1000
1001                 vec.bv_page = page;
1002                 vec.bv_len = PAGE_SIZE;
1003                 vec.bv_offset = 0;
1004         }
1005
1006         ret = __zram_bvec_write(zram, &vec, index, bio);
1007 out:
1008         if (is_partial_io(bvec))
1009                 __free_page(page);
1010         return ret;
1011 }
1012
1013 /*
1014  * zram_bio_discard - handler on discard request
1015  * @index: physical block index in PAGE_SIZE units
1016  * @offset: byte offset within physical block
1017  */
1018 static void zram_bio_discard(struct zram *zram, u32 index,
1019                              int offset, struct bio *bio)
1020 {
1021         size_t n = bio->bi_iter.bi_size;
1022
1023         /*
1024          * zram manages data in physical block size units. Because logical block
1025          * size isn't identical with physical block size on some arch, we
1026          * could get a discard request pointing to a specific offset within a
1027          * certain physical block.  Although we can handle this request by
1028          * reading that physiclal block and decompressing and partially zeroing
1029          * and re-compressing and then re-storing it, this isn't reasonable
1030          * because our intent with a discard request is to save memory.  So
1031          * skipping this logical block is appropriate here.
1032          */
1033         if (offset) {
1034                 if (n <= (PAGE_SIZE - offset))
1035                         return;
1036
1037                 n -= (PAGE_SIZE - offset);
1038                 index++;
1039         }
1040
1041         while (n >= PAGE_SIZE) {
1042                 zram_slot_lock(zram, index);
1043                 zram_free_page(zram, index);
1044                 zram_slot_unlock(zram, index);
1045                 atomic64_inc(&zram->stats.notify_free);
1046                 index++;
1047                 n -= PAGE_SIZE;
1048         }
1049 }
1050
1051 /*
1052  * Returns errno if it has some problem. Otherwise return 0 or 1.
1053  * Returns 0 if IO request was done synchronously
1054  * Returns 1 if IO request was successfully submitted.
1055  */
1056 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
1057                         int offset, bool is_write, struct bio *bio)
1058 {
1059         unsigned long start_time = jiffies;
1060         int rw_acct = is_write ? REQ_OP_WRITE : REQ_OP_READ;
1061         int ret;
1062
1063         generic_start_io_acct(rw_acct, bvec->bv_len >> SECTOR_SHIFT,
1064                         &zram->disk->part0);
1065
1066         if (!is_write) {
1067                 atomic64_inc(&zram->stats.num_reads);
1068                 ret = zram_bvec_read(zram, bvec, index, offset);
1069                 flush_dcache_page(bvec->bv_page);
1070         } else {
1071                 atomic64_inc(&zram->stats.num_writes);
1072                 ret = zram_bvec_write(zram, bvec, index, offset, bio);
1073         }
1074
1075         generic_end_io_acct(rw_acct, &zram->disk->part0, start_time);
1076
1077         if (unlikely(ret < 0)) {
1078                 if (!is_write)
1079                         atomic64_inc(&zram->stats.failed_reads);
1080                 else
1081                         atomic64_inc(&zram->stats.failed_writes);
1082         }
1083
1084         return ret;
1085 }
1086
1087 static void __zram_make_request(struct zram *zram, struct bio *bio)
1088 {
1089         int offset;
1090         u32 index;
1091         struct bio_vec bvec;
1092         struct bvec_iter iter;
1093
1094         index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1095         offset = (bio->bi_iter.bi_sector &
1096                   (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1097
1098         switch (bio_op(bio)) {
1099         case REQ_OP_DISCARD:
1100         case REQ_OP_WRITE_ZEROES:
1101                 zram_bio_discard(zram, index, offset, bio);
1102                 bio_endio(bio);
1103                 return;
1104         default:
1105                 break;
1106         }
1107
1108         bio_for_each_segment(bvec, bio, iter) {
1109                 struct bio_vec bv = bvec;
1110                 unsigned int unwritten = bvec.bv_len;
1111
1112                 do {
1113                         bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
1114                                                         unwritten);
1115                         if (zram_bvec_rw(zram, &bv, index, offset,
1116                                         op_is_write(bio_op(bio)), bio) < 0)
1117                                 goto out;
1118
1119                         bv.bv_offset += bv.bv_len;
1120                         unwritten -= bv.bv_len;
1121
1122                         update_position(&index, &offset, &bv);
1123                 } while (unwritten);
1124         }
1125
1126         bio_endio(bio);
1127         return;
1128
1129 out:
1130         bio_io_error(bio);
1131 }
1132
1133 /*
1134  * Handler function for all zram I/O requests.
1135  */
1136 static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio)
1137 {
1138         struct zram *zram = queue->queuedata;
1139
1140         if (!valid_io_request(zram, bio->bi_iter.bi_sector,
1141                                         bio->bi_iter.bi_size)) {
1142                 atomic64_inc(&zram->stats.invalid_io);
1143                 goto error;
1144         }
1145
1146         __zram_make_request(zram, bio);
1147         return BLK_QC_T_NONE;
1148
1149 error:
1150         bio_io_error(bio);
1151         return BLK_QC_T_NONE;
1152 }
1153
1154 static void zram_slot_free_notify(struct block_device *bdev,
1155                                 unsigned long index)
1156 {
1157         struct zram *zram;
1158
1159         zram = bdev->bd_disk->private_data;
1160
1161         zram_slot_lock(zram, index);
1162         zram_free_page(zram, index);
1163         zram_slot_unlock(zram, index);
1164         atomic64_inc(&zram->stats.notify_free);
1165 }
1166
1167 static int zram_rw_page(struct block_device *bdev, sector_t sector,
1168                        struct page *page, bool is_write)
1169 {
1170         int offset, ret;
1171         u32 index;
1172         struct zram *zram;
1173         struct bio_vec bv;
1174
1175         zram = bdev->bd_disk->private_data;
1176
1177         if (!valid_io_request(zram, sector, PAGE_SIZE)) {
1178                 atomic64_inc(&zram->stats.invalid_io);
1179                 ret = -EINVAL;
1180                 goto out;
1181         }
1182
1183         index = sector >> SECTORS_PER_PAGE_SHIFT;
1184         offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1185
1186         bv.bv_page = page;
1187         bv.bv_len = PAGE_SIZE;
1188         bv.bv_offset = 0;
1189
1190         ret = zram_bvec_rw(zram, &bv, index, offset, is_write, NULL);
1191 out:
1192         /*
1193          * If I/O fails, just return error(ie, non-zero) without
1194          * calling page_endio.
1195          * It causes resubmit the I/O with bio request by upper functions
1196          * of rw_page(e.g., swap_readpage, __swap_writepage) and
1197          * bio->bi_end_io does things to handle the error
1198          * (e.g., SetPageError, set_page_dirty and extra works).
1199          */
1200         if (unlikely(ret < 0))
1201                 return ret;
1202
1203         switch (ret) {
1204         case 0:
1205                 page_endio(page, is_write, 0);
1206                 break;
1207         case 1:
1208                 ret = 0;
1209                 break;
1210         default:
1211                 WARN_ON(1);
1212         }
1213         return ret;
1214 }
1215
1216 static void zram_reset_device(struct zram *zram)
1217 {
1218         struct zcomp *comp;
1219         u64 disksize;
1220
1221         down_write(&zram->init_lock);
1222
1223         zram->limit_pages = 0;
1224
1225         if (!init_done(zram)) {
1226                 up_write(&zram->init_lock);
1227                 return;
1228         }
1229
1230         comp = zram->comp;
1231         disksize = zram->disksize;
1232         zram->disksize = 0;
1233
1234         set_capacity(zram->disk, 0);
1235         part_stat_set_all(&zram->disk->part0, 0);
1236
1237         up_write(&zram->init_lock);
1238         /* I/O operation under all of CPU are done so let's free */
1239         zram_meta_free(zram, disksize);
1240         memset(&zram->stats, 0, sizeof(zram->stats));
1241         zcomp_destroy(comp);
1242         reset_bdev(zram);
1243 }
1244
1245 static ssize_t disksize_store(struct device *dev,
1246                 struct device_attribute *attr, const char *buf, size_t len)
1247 {
1248         u64 disksize;
1249         struct zcomp *comp;
1250         struct zram *zram = dev_to_zram(dev);
1251         int err;
1252
1253         disksize = memparse(buf, NULL);
1254         if (!disksize)
1255                 return -EINVAL;
1256
1257         down_write(&zram->init_lock);
1258         if (init_done(zram)) {
1259                 pr_info("Cannot change disksize for initialized device\n");
1260                 err = -EBUSY;
1261                 goto out_unlock;
1262         }
1263
1264         disksize = PAGE_ALIGN(disksize);
1265         if (!zram_meta_alloc(zram, disksize)) {
1266                 err = -ENOMEM;
1267                 goto out_unlock;
1268         }
1269
1270         comp = zcomp_create(zram->compressor);
1271         if (IS_ERR(comp)) {
1272                 pr_err("Cannot initialise %s compressing backend\n",
1273                                 zram->compressor);
1274                 err = PTR_ERR(comp);
1275                 goto out_free_meta;
1276         }
1277
1278         zram->comp = comp;
1279         zram->disksize = disksize;
1280         set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
1281         zram_revalidate_disk(zram);
1282         up_write(&zram->init_lock);
1283
1284         return len;
1285
1286 out_free_meta:
1287         zram_meta_free(zram, disksize);
1288 out_unlock:
1289         up_write(&zram->init_lock);
1290         return err;
1291 }
1292
1293 static ssize_t reset_store(struct device *dev,
1294                 struct device_attribute *attr, const char *buf, size_t len)
1295 {
1296         int ret;
1297         unsigned short do_reset;
1298         struct zram *zram;
1299         struct block_device *bdev;
1300
1301         ret = kstrtou16(buf, 10, &do_reset);
1302         if (ret)
1303                 return ret;
1304
1305         if (!do_reset)
1306                 return -EINVAL;
1307
1308         zram = dev_to_zram(dev);
1309         bdev = bdget_disk(zram->disk, 0);
1310         if (!bdev)
1311                 return -ENOMEM;
1312
1313         mutex_lock(&bdev->bd_mutex);
1314         /* Do not reset an active device or claimed device */
1315         if (bdev->bd_openers || zram->claim) {
1316                 mutex_unlock(&bdev->bd_mutex);
1317                 bdput(bdev);
1318                 return -EBUSY;
1319         }
1320
1321         /* From now on, anyone can't open /dev/zram[0-9] */
1322         zram->claim = true;
1323         mutex_unlock(&bdev->bd_mutex);
1324
1325         /* Make sure all the pending I/O are finished */
1326         fsync_bdev(bdev);
1327         zram_reset_device(zram);
1328         zram_revalidate_disk(zram);
1329         bdput(bdev);
1330
1331         mutex_lock(&bdev->bd_mutex);
1332         zram->claim = false;
1333         mutex_unlock(&bdev->bd_mutex);
1334
1335         return len;
1336 }
1337
1338 static int zram_open(struct block_device *bdev, fmode_t mode)
1339 {
1340         int ret = 0;
1341         struct zram *zram;
1342
1343         WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
1344
1345         zram = bdev->bd_disk->private_data;
1346         /* zram was claimed to reset so open request fails */
1347         if (zram->claim)
1348                 ret = -EBUSY;
1349
1350         return ret;
1351 }
1352
1353 static const struct block_device_operations zram_devops = {
1354         .open = zram_open,
1355         .swap_slot_free_notify = zram_slot_free_notify,
1356         .rw_page = zram_rw_page,
1357         .owner = THIS_MODULE
1358 };
1359
1360 static DEVICE_ATTR_WO(compact);
1361 static DEVICE_ATTR_RW(disksize);
1362 static DEVICE_ATTR_RO(initstate);
1363 static DEVICE_ATTR_WO(reset);
1364 static DEVICE_ATTR_WO(mem_limit);
1365 static DEVICE_ATTR_WO(mem_used_max);
1366 static DEVICE_ATTR_RW(max_comp_streams);
1367 static DEVICE_ATTR_RW(comp_algorithm);
1368 #ifdef CONFIG_ZRAM_WRITEBACK
1369 static DEVICE_ATTR_RW(backing_dev);
1370 #endif
1371
1372 static struct attribute *zram_disk_attrs[] = {
1373         &dev_attr_disksize.attr,
1374         &dev_attr_initstate.attr,
1375         &dev_attr_reset.attr,
1376         &dev_attr_compact.attr,
1377         &dev_attr_mem_limit.attr,
1378         &dev_attr_mem_used_max.attr,
1379         &dev_attr_max_comp_streams.attr,
1380         &dev_attr_comp_algorithm.attr,
1381 #ifdef CONFIG_ZRAM_WRITEBACK
1382         &dev_attr_backing_dev.attr,
1383 #endif
1384         &dev_attr_io_stat.attr,
1385         &dev_attr_mm_stat.attr,
1386         &dev_attr_debug_stat.attr,
1387         NULL,
1388 };
1389
1390 static const struct attribute_group zram_disk_attr_group = {
1391         .attrs = zram_disk_attrs,
1392 };
1393
1394 /*
1395  * Allocate and initialize new zram device. the function returns
1396  * '>= 0' device_id upon success, and negative value otherwise.
1397  */
1398 static int zram_add(void)
1399 {
1400         struct zram *zram;
1401         struct request_queue *queue;
1402         int ret, device_id;
1403
1404         zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1405         if (!zram)
1406                 return -ENOMEM;
1407
1408         ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1409         if (ret < 0)
1410                 goto out_free_dev;
1411         device_id = ret;
1412
1413         init_rwsem(&zram->init_lock);
1414
1415         queue = blk_alloc_queue(GFP_KERNEL);
1416         if (!queue) {
1417                 pr_err("Error allocating disk queue for device %d\n",
1418                         device_id);
1419                 ret = -ENOMEM;
1420                 goto out_free_idr;
1421         }
1422
1423         blk_queue_make_request(queue, zram_make_request);
1424
1425         /* gendisk structure */
1426         zram->disk = alloc_disk(1);
1427         if (!zram->disk) {
1428                 pr_err("Error allocating disk structure for device %d\n",
1429                         device_id);
1430                 ret = -ENOMEM;
1431                 goto out_free_queue;
1432         }
1433
1434         zram->disk->major = zram_major;
1435         zram->disk->first_minor = device_id;
1436         zram->disk->fops = &zram_devops;
1437         zram->disk->queue = queue;
1438         zram->disk->queue->queuedata = zram;
1439         zram->disk->private_data = zram;
1440         snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1441
1442         /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1443         set_capacity(zram->disk, 0);
1444         /* zram devices sort of resembles non-rotational disks */
1445         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zram->disk->queue);
1446         queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1447         /*
1448          * To ensure that we always get PAGE_SIZE aligned
1449          * and n*PAGE_SIZED sized I/O requests.
1450          */
1451         blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1452         blk_queue_logical_block_size(zram->disk->queue,
1453                                         ZRAM_LOGICAL_BLOCK_SIZE);
1454         blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1455         blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1456         zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1457         blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1458         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, zram->disk->queue);
1459
1460         /*
1461          * zram_bio_discard() will clear all logical blocks if logical block
1462          * size is identical with physical block size(PAGE_SIZE). But if it is
1463          * different, we will skip discarding some parts of logical blocks in
1464          * the part of the request range which isn't aligned to physical block
1465          * size.  So we can't ensure that all discarded logical blocks are
1466          * zeroed.
1467          */
1468         if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1469                 blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
1470
1471         add_disk(zram->disk);
1472
1473         ret = sysfs_create_group(&disk_to_dev(zram->disk)->kobj,
1474                                 &zram_disk_attr_group);
1475         if (ret < 0) {
1476                 pr_err("Error creating sysfs group for device %d\n",
1477                                 device_id);
1478                 goto out_free_disk;
1479         }
1480         strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1481
1482         pr_info("Added device: %s\n", zram->disk->disk_name);
1483         return device_id;
1484
1485 out_free_disk:
1486         del_gendisk(zram->disk);
1487         put_disk(zram->disk);
1488 out_free_queue:
1489         blk_cleanup_queue(queue);
1490 out_free_idr:
1491         idr_remove(&zram_index_idr, device_id);
1492 out_free_dev:
1493         kfree(zram);
1494         return ret;
1495 }
1496
1497 static int zram_remove(struct zram *zram)
1498 {
1499         struct block_device *bdev;
1500
1501         bdev = bdget_disk(zram->disk, 0);
1502         if (!bdev)
1503                 return -ENOMEM;
1504
1505         mutex_lock(&bdev->bd_mutex);
1506         if (bdev->bd_openers || zram->claim) {
1507                 mutex_unlock(&bdev->bd_mutex);
1508                 bdput(bdev);
1509                 return -EBUSY;
1510         }
1511
1512         zram->claim = true;
1513         mutex_unlock(&bdev->bd_mutex);
1514
1515         /*
1516          * Remove sysfs first, so no one will perform a disksize
1517          * store while we destroy the devices. This also helps during
1518          * hot_remove -- zram_reset_device() is the last holder of
1519          * ->init_lock, no later/concurrent disksize_store() or any
1520          * other sysfs handlers are possible.
1521          */
1522         sysfs_remove_group(&disk_to_dev(zram->disk)->kobj,
1523                         &zram_disk_attr_group);
1524
1525         /* Make sure all the pending I/O are finished */
1526         fsync_bdev(bdev);
1527         zram_reset_device(zram);
1528         bdput(bdev);
1529
1530         pr_info("Removed device: %s\n", zram->disk->disk_name);
1531
1532         blk_cleanup_queue(zram->disk->queue);
1533         del_gendisk(zram->disk);
1534         put_disk(zram->disk);
1535         kfree(zram);
1536         return 0;
1537 }
1538
1539 /* zram-control sysfs attributes */
1540
1541 /*
1542  * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
1543  * sense that reading from this file does alter the state of your system -- it
1544  * creates a new un-initialized zram device and returns back this device's
1545  * device_id (or an error code if it fails to create a new device).
1546  */
1547 static ssize_t hot_add_show(struct class *class,
1548                         struct class_attribute *attr,
1549                         char *buf)
1550 {
1551         int ret;
1552
1553         mutex_lock(&zram_index_mutex);
1554         ret = zram_add();
1555         mutex_unlock(&zram_index_mutex);
1556
1557         if (ret < 0)
1558                 return ret;
1559         return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
1560 }
1561 static CLASS_ATTR_RO(hot_add);
1562
1563 static ssize_t hot_remove_store(struct class *class,
1564                         struct class_attribute *attr,
1565                         const char *buf,
1566                         size_t count)
1567 {
1568         struct zram *zram;
1569         int ret, dev_id;
1570
1571         /* dev_id is gendisk->first_minor, which is `int' */
1572         ret = kstrtoint(buf, 10, &dev_id);
1573         if (ret)
1574                 return ret;
1575         if (dev_id < 0)
1576                 return -EINVAL;
1577
1578         mutex_lock(&zram_index_mutex);
1579
1580         zram = idr_find(&zram_index_idr, dev_id);
1581         if (zram) {
1582                 ret = zram_remove(zram);
1583                 if (!ret)
1584                         idr_remove(&zram_index_idr, dev_id);
1585         } else {
1586                 ret = -ENODEV;
1587         }
1588
1589         mutex_unlock(&zram_index_mutex);
1590         return ret ? ret : count;
1591 }
1592 static CLASS_ATTR_WO(hot_remove);
1593
1594 static struct attribute *zram_control_class_attrs[] = {
1595         &class_attr_hot_add.attr,
1596         &class_attr_hot_remove.attr,
1597         NULL,
1598 };
1599 ATTRIBUTE_GROUPS(zram_control_class);
1600
1601 static struct class zram_control_class = {
1602         .name           = "zram-control",
1603         .owner          = THIS_MODULE,
1604         .class_groups   = zram_control_class_groups,
1605 };
1606
1607 static int zram_remove_cb(int id, void *ptr, void *data)
1608 {
1609         zram_remove(ptr);
1610         return 0;
1611 }
1612
1613 static void destroy_devices(void)
1614 {
1615         class_unregister(&zram_control_class);
1616         idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
1617         idr_destroy(&zram_index_idr);
1618         unregister_blkdev(zram_major, "zram");
1619         cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1620 }
1621
1622 static int __init zram_init(void)
1623 {
1624         int ret;
1625
1626         ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
1627                                       zcomp_cpu_up_prepare, zcomp_cpu_dead);
1628         if (ret < 0)
1629                 return ret;
1630
1631         ret = class_register(&zram_control_class);
1632         if (ret) {
1633                 pr_err("Unable to register zram-control class\n");
1634                 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1635                 return ret;
1636         }
1637
1638         zram_major = register_blkdev(0, "zram");
1639         if (zram_major <= 0) {
1640                 pr_err("Unable to get major number\n");
1641                 class_unregister(&zram_control_class);
1642                 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1643                 return -EBUSY;
1644         }
1645
1646         while (num_devices != 0) {
1647                 mutex_lock(&zram_index_mutex);
1648                 ret = zram_add();
1649                 mutex_unlock(&zram_index_mutex);
1650                 if (ret < 0)
1651                         goto out_error;
1652                 num_devices--;
1653         }
1654
1655         return 0;
1656
1657 out_error:
1658         destroy_devices();
1659         return ret;
1660 }
1661
1662 static void __exit zram_exit(void)
1663 {
1664         destroy_devices();
1665 }
1666
1667 module_init(zram_init);
1668 module_exit(zram_exit);
1669
1670 module_param(num_devices, uint, 0);
1671 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
1672
1673 MODULE_LICENSE("Dual BSD/GPL");
1674 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
1675 MODULE_DESCRIPTION("Compressed RAM Block Device");