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