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