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