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