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