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