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