]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/block/zram/zram_drv.c
zram: handle multiple pages attached bio's bvec
[linux.git] / drivers / block / zram / zram_drv.c
1 /*
2  * Compressed RAM block device
3  *
4  * Copyright (C) 2008, 2009, 2010  Nitin Gupta
5  *               2012, 2013 Minchan Kim
6  *
7  * This code is released using a dual license strategy: BSD/GPL
8  * You can choose the licence that better fits your requirements.
9  *
10  * Released under the terms of 3-clause BSD License
11  * Released under the terms of GNU General Public License Version 2.0
12  *
13  */
14
15 #define KMSG_COMPONENT "zram"
16 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
17
18 #include <linux/module.h>
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/bitops.h>
22 #include <linux/blkdev.h>
23 #include <linux/buffer_head.h>
24 #include <linux/device.h>
25 #include <linux/genhd.h>
26 #include <linux/highmem.h>
27 #include <linux/slab.h>
28 #include <linux/backing-dev.h>
29 #include <linux/string.h>
30 #include <linux/vmalloc.h>
31 #include <linux/err.h>
32 #include <linux/idr.h>
33 #include <linux/sysfs.h>
34 #include <linux/cpuhotplug.h>
35
36 #include "zram_drv.h"
37
38 static DEFINE_IDR(zram_index_idr);
39 /* idr index must be protected */
40 static DEFINE_MUTEX(zram_index_mutex);
41
42 static int zram_major;
43 static const char *default_compressor = "lzo";
44
45 /* Module params (documentation at end) */
46 static unsigned int num_devices = 1;
47
48 static inline bool init_done(struct zram *zram)
49 {
50         return zram->disksize;
51 }
52
53 static inline struct zram *dev_to_zram(struct device *dev)
54 {
55         return (struct zram *)dev_to_disk(dev)->private_data;
56 }
57
58 /* flag operations require table entry bit_spin_lock() being held */
59 static int zram_test_flag(struct zram_meta *meta, u32 index,
60                         enum zram_pageflags flag)
61 {
62         return meta->table[index].value & BIT(flag);
63 }
64
65 static void zram_set_flag(struct zram_meta *meta, u32 index,
66                         enum zram_pageflags flag)
67 {
68         meta->table[index].value |= BIT(flag);
69 }
70
71 static void zram_clear_flag(struct zram_meta *meta, u32 index,
72                         enum zram_pageflags flag)
73 {
74         meta->table[index].value &= ~BIT(flag);
75 }
76
77 static inline void zram_set_element(struct zram_meta *meta, u32 index,
78                         unsigned long element)
79 {
80         meta->table[index].element = element;
81 }
82
83 static inline void zram_clear_element(struct zram_meta *meta, u32 index)
84 {
85         meta->table[index].element = 0;
86 }
87
88 static size_t zram_get_obj_size(struct zram_meta *meta, u32 index)
89 {
90         return meta->table[index].value & (BIT(ZRAM_FLAG_SHIFT) - 1);
91 }
92
93 static void zram_set_obj_size(struct zram_meta *meta,
94                                         u32 index, size_t size)
95 {
96         unsigned long flags = meta->table[index].value >> ZRAM_FLAG_SHIFT;
97
98         meta->table[index].value = (flags << ZRAM_FLAG_SHIFT) | size;
99 }
100
101 static inline bool is_partial_io(struct bio_vec *bvec)
102 {
103         return bvec->bv_len != PAGE_SIZE;
104 }
105
106 static void zram_revalidate_disk(struct zram *zram)
107 {
108         revalidate_disk(zram->disk);
109         /* revalidate_disk reset the BDI_CAP_STABLE_WRITES so set again */
110         zram->disk->queue->backing_dev_info->capabilities |=
111                 BDI_CAP_STABLE_WRITES;
112 }
113
114 /*
115  * Check if request is within bounds and aligned on zram logical blocks.
116  */
117 static inline bool valid_io_request(struct zram *zram,
118                 sector_t start, unsigned int size)
119 {
120         u64 end, bound;
121
122         /* unaligned request */
123         if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
124                 return false;
125         if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
126                 return false;
127
128         end = start + (size >> SECTOR_SHIFT);
129         bound = zram->disksize >> SECTOR_SHIFT;
130         /* out of range range */
131         if (unlikely(start >= bound || end > bound || start > end))
132                 return false;
133
134         /* I/O request is valid */
135         return true;
136 }
137
138 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
139 {
140         *index  += (*offset + bvec->bv_len) / PAGE_SIZE;
141         *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
142 }
143
144 static inline void update_used_max(struct zram *zram,
145                                         const unsigned long pages)
146 {
147         unsigned long old_max, cur_max;
148
149         old_max = atomic_long_read(&zram->stats.max_used_pages);
150
151         do {
152                 cur_max = old_max;
153                 if (pages > cur_max)
154                         old_max = atomic_long_cmpxchg(
155                                 &zram->stats.max_used_pages, cur_max, pages);
156         } while (old_max != cur_max);
157 }
158
159 static inline void zram_fill_page(char *ptr, unsigned long len,
160                                         unsigned long value)
161 {
162         int i;
163         unsigned long *page = (unsigned long *)ptr;
164
165         WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
166
167         if (likely(value == 0)) {
168                 memset(ptr, 0, len);
169         } else {
170                 for (i = 0; i < len / sizeof(*page); i++)
171                         page[i] = value;
172         }
173 }
174
175 static bool page_same_filled(void *ptr, unsigned long *element)
176 {
177         unsigned int pos;
178         unsigned long *page;
179
180         page = (unsigned long *)ptr;
181
182         for (pos = 0; pos < PAGE_SIZE / sizeof(*page) - 1; pos++) {
183                 if (page[pos] != page[pos + 1])
184                         return false;
185         }
186
187         *element = page[pos];
188
189         return true;
190 }
191
192 static void handle_same_page(struct bio_vec *bvec, unsigned long element)
193 {
194         struct page *page = bvec->bv_page;
195         void *user_mem;
196
197         user_mem = kmap_atomic(page);
198         zram_fill_page(user_mem + bvec->bv_offset, bvec->bv_len, element);
199         kunmap_atomic(user_mem);
200
201         flush_dcache_page(page);
202 }
203
204 static ssize_t initstate_show(struct device *dev,
205                 struct device_attribute *attr, char *buf)
206 {
207         u32 val;
208         struct zram *zram = dev_to_zram(dev);
209
210         down_read(&zram->init_lock);
211         val = init_done(zram);
212         up_read(&zram->init_lock);
213
214         return scnprintf(buf, PAGE_SIZE, "%u\n", val);
215 }
216
217 static ssize_t disksize_show(struct device *dev,
218                 struct device_attribute *attr, char *buf)
219 {
220         struct zram *zram = dev_to_zram(dev);
221
222         return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
223 }
224
225 static ssize_t mem_limit_store(struct device *dev,
226                 struct device_attribute *attr, const char *buf, size_t len)
227 {
228         u64 limit;
229         char *tmp;
230         struct zram *zram = dev_to_zram(dev);
231
232         limit = memparse(buf, &tmp);
233         if (buf == tmp) /* no chars parsed, invalid input */
234                 return -EINVAL;
235
236         down_write(&zram->init_lock);
237         zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
238         up_write(&zram->init_lock);
239
240         return len;
241 }
242
243 static ssize_t mem_used_max_store(struct device *dev,
244                 struct device_attribute *attr, const char *buf, size_t len)
245 {
246         int err;
247         unsigned long val;
248         struct zram *zram = dev_to_zram(dev);
249
250         err = kstrtoul(buf, 10, &val);
251         if (err || val != 0)
252                 return -EINVAL;
253
254         down_read(&zram->init_lock);
255         if (init_done(zram)) {
256                 struct zram_meta *meta = zram->meta;
257                 atomic_long_set(&zram->stats.max_used_pages,
258                                 zs_get_total_pages(meta->mem_pool));
259         }
260         up_read(&zram->init_lock);
261
262         return len;
263 }
264
265 /*
266  * We switched to per-cpu streams and this attr is not needed anymore.
267  * However, we will keep it around for some time, because:
268  * a) we may revert per-cpu streams in the future
269  * b) it's visible to user space and we need to follow our 2 years
270  *    retirement rule; but we already have a number of 'soon to be
271  *    altered' attrs, so max_comp_streams need to wait for the next
272  *    layoff cycle.
273  */
274 static ssize_t max_comp_streams_show(struct device *dev,
275                 struct device_attribute *attr, char *buf)
276 {
277         return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
278 }
279
280 static ssize_t max_comp_streams_store(struct device *dev,
281                 struct device_attribute *attr, const char *buf, size_t len)
282 {
283         return len;
284 }
285
286 static ssize_t comp_algorithm_show(struct device *dev,
287                 struct device_attribute *attr, char *buf)
288 {
289         size_t sz;
290         struct zram *zram = dev_to_zram(dev);
291
292         down_read(&zram->init_lock);
293         sz = zcomp_available_show(zram->compressor, buf);
294         up_read(&zram->init_lock);
295
296         return sz;
297 }
298
299 static ssize_t comp_algorithm_store(struct device *dev,
300                 struct device_attribute *attr, const char *buf, size_t len)
301 {
302         struct zram *zram = dev_to_zram(dev);
303         char compressor[CRYPTO_MAX_ALG_NAME];
304         size_t sz;
305
306         strlcpy(compressor, buf, sizeof(compressor));
307         /* ignore trailing newline */
308         sz = strlen(compressor);
309         if (sz > 0 && compressor[sz - 1] == '\n')
310                 compressor[sz - 1] = 0x00;
311
312         if (!zcomp_available_algorithm(compressor))
313                 return -EINVAL;
314
315         down_write(&zram->init_lock);
316         if (init_done(zram)) {
317                 up_write(&zram->init_lock);
318                 pr_info("Can't change algorithm for initialized device\n");
319                 return -EBUSY;
320         }
321
322         strlcpy(zram->compressor, compressor, sizeof(compressor));
323         up_write(&zram->init_lock);
324         return len;
325 }
326
327 static ssize_t compact_store(struct device *dev,
328                 struct device_attribute *attr, const char *buf, size_t len)
329 {
330         struct zram *zram = dev_to_zram(dev);
331         struct zram_meta *meta;
332
333         down_read(&zram->init_lock);
334         if (!init_done(zram)) {
335                 up_read(&zram->init_lock);
336                 return -EINVAL;
337         }
338
339         meta = zram->meta;
340         zs_compact(meta->mem_pool);
341         up_read(&zram->init_lock);
342
343         return len;
344 }
345
346 static ssize_t io_stat_show(struct device *dev,
347                 struct device_attribute *attr, char *buf)
348 {
349         struct zram *zram = dev_to_zram(dev);
350         ssize_t ret;
351
352         down_read(&zram->init_lock);
353         ret = scnprintf(buf, PAGE_SIZE,
354                         "%8llu %8llu %8llu %8llu\n",
355                         (u64)atomic64_read(&zram->stats.failed_reads),
356                         (u64)atomic64_read(&zram->stats.failed_writes),
357                         (u64)atomic64_read(&zram->stats.invalid_io),
358                         (u64)atomic64_read(&zram->stats.notify_free));
359         up_read(&zram->init_lock);
360
361         return ret;
362 }
363
364 static ssize_t mm_stat_show(struct device *dev,
365                 struct device_attribute *attr, char *buf)
366 {
367         struct zram *zram = dev_to_zram(dev);
368         struct zs_pool_stats pool_stats;
369         u64 orig_size, mem_used = 0;
370         long max_used;
371         ssize_t ret;
372
373         memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
374
375         down_read(&zram->init_lock);
376         if (init_done(zram)) {
377                 mem_used = zs_get_total_pages(zram->meta->mem_pool);
378                 zs_pool_stats(zram->meta->mem_pool, &pool_stats);
379         }
380
381         orig_size = atomic64_read(&zram->stats.pages_stored);
382         max_used = atomic_long_read(&zram->stats.max_used_pages);
383
384         ret = scnprintf(buf, PAGE_SIZE,
385                         "%8llu %8llu %8llu %8lu %8ld %8llu %8lu\n",
386                         orig_size << PAGE_SHIFT,
387                         (u64)atomic64_read(&zram->stats.compr_data_size),
388                         mem_used << PAGE_SHIFT,
389                         zram->limit_pages << PAGE_SHIFT,
390                         max_used << PAGE_SHIFT,
391                         (u64)atomic64_read(&zram->stats.same_pages),
392                         pool_stats.pages_compacted);
393         up_read(&zram->init_lock);
394
395         return ret;
396 }
397
398 static ssize_t debug_stat_show(struct device *dev,
399                 struct device_attribute *attr, char *buf)
400 {
401         int version = 1;
402         struct zram *zram = dev_to_zram(dev);
403         ssize_t ret;
404
405         down_read(&zram->init_lock);
406         ret = scnprintf(buf, PAGE_SIZE,
407                         "version: %d\n%8llu\n",
408                         version,
409                         (u64)atomic64_read(&zram->stats.writestall));
410         up_read(&zram->init_lock);
411
412         return ret;
413 }
414
415 static DEVICE_ATTR_RO(io_stat);
416 static DEVICE_ATTR_RO(mm_stat);
417 static DEVICE_ATTR_RO(debug_stat);
418
419 static void zram_meta_free(struct zram_meta *meta, u64 disksize)
420 {
421         size_t num_pages = disksize >> PAGE_SHIFT;
422         size_t index;
423
424         /* Free all pages that are still in this zram device */
425         for (index = 0; index < num_pages; index++) {
426                 unsigned long handle = meta->table[index].handle;
427                 /*
428                  * No memory is allocated for same element filled pages.
429                  * Simply clear same page flag.
430                  */
431                 if (!handle || zram_test_flag(meta, index, ZRAM_SAME))
432                         continue;
433
434                 zs_free(meta->mem_pool, handle);
435         }
436
437         zs_destroy_pool(meta->mem_pool);
438         vfree(meta->table);
439         kfree(meta);
440 }
441
442 static struct zram_meta *zram_meta_alloc(char *pool_name, u64 disksize)
443 {
444         size_t num_pages;
445         struct zram_meta *meta = kmalloc(sizeof(*meta), GFP_KERNEL);
446
447         if (!meta)
448                 return NULL;
449
450         num_pages = disksize >> PAGE_SHIFT;
451         meta->table = vzalloc(num_pages * sizeof(*meta->table));
452         if (!meta->table) {
453                 pr_err("Error allocating zram address table\n");
454                 goto out_error;
455         }
456
457         meta->mem_pool = zs_create_pool(pool_name);
458         if (!meta->mem_pool) {
459                 pr_err("Error creating memory pool\n");
460                 goto out_error;
461         }
462
463         return meta;
464
465 out_error:
466         vfree(meta->table);
467         kfree(meta);
468         return NULL;
469 }
470
471 /*
472  * To protect concurrent access to the same index entry,
473  * caller should hold this table index entry's bit_spinlock to
474  * indicate this index entry is accessing.
475  */
476 static void zram_free_page(struct zram *zram, size_t index)
477 {
478         struct zram_meta *meta = zram->meta;
479         unsigned long handle = meta->table[index].handle;
480
481         /*
482          * No memory is allocated for same element filled pages.
483          * Simply clear same page flag.
484          */
485         if (zram_test_flag(meta, index, ZRAM_SAME)) {
486                 zram_clear_flag(meta, index, ZRAM_SAME);
487                 zram_clear_element(meta, index);
488                 atomic64_dec(&zram->stats.same_pages);
489                 return;
490         }
491
492         if (!handle)
493                 return;
494
495         zs_free(meta->mem_pool, handle);
496
497         atomic64_sub(zram_get_obj_size(meta, index),
498                         &zram->stats.compr_data_size);
499         atomic64_dec(&zram->stats.pages_stored);
500
501         meta->table[index].handle = 0;
502         zram_set_obj_size(meta, index, 0);
503 }
504
505 static int zram_decompress_page(struct zram *zram, char *mem, u32 index)
506 {
507         int ret = 0;
508         unsigned char *cmem;
509         struct zram_meta *meta = zram->meta;
510         unsigned long handle;
511         unsigned int size;
512
513         bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
514         handle = meta->table[index].handle;
515         size = zram_get_obj_size(meta, index);
516
517         if (!handle || zram_test_flag(meta, index, ZRAM_SAME)) {
518                 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
519                 zram_fill_page(mem, PAGE_SIZE, meta->table[index].element);
520                 return 0;
521         }
522
523         cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_RO);
524         if (size == PAGE_SIZE) {
525                 memcpy(mem, cmem, PAGE_SIZE);
526         } else {
527                 struct zcomp_strm *zstrm = zcomp_stream_get(zram->comp);
528
529                 ret = zcomp_decompress(zstrm, cmem, size, mem);
530                 zcomp_stream_put(zram->comp);
531         }
532         zs_unmap_object(meta->mem_pool, handle);
533         bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
534
535         /* Should NEVER happen. Return bio error if it does. */
536         if (unlikely(ret)) {
537                 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
538                 return ret;
539         }
540
541         return 0;
542 }
543
544 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
545                           u32 index, int offset)
546 {
547         int ret;
548         struct page *page;
549         unsigned char *user_mem, *uncmem = NULL;
550         struct zram_meta *meta = zram->meta;
551         page = bvec->bv_page;
552
553         bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
554         if (unlikely(!meta->table[index].handle) ||
555                         zram_test_flag(meta, index, ZRAM_SAME)) {
556                 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
557                 handle_same_page(bvec, meta->table[index].element);
558                 return 0;
559         }
560         bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
561
562         if (is_partial_io(bvec))
563                 /* Use  a temporary buffer to decompress the page */
564                 uncmem = kmalloc(PAGE_SIZE, GFP_NOIO);
565
566         user_mem = kmap_atomic(page);
567         if (!is_partial_io(bvec))
568                 uncmem = user_mem;
569
570         if (!uncmem) {
571                 pr_err("Unable to allocate temp memory\n");
572                 ret = -ENOMEM;
573                 goto out_cleanup;
574         }
575
576         ret = zram_decompress_page(zram, uncmem, index);
577         /* Should NEVER happen. Return bio error if it does. */
578         if (unlikely(ret))
579                 goto out_cleanup;
580
581         if (is_partial_io(bvec))
582                 memcpy(user_mem + bvec->bv_offset, uncmem + offset,
583                                 bvec->bv_len);
584
585         flush_dcache_page(page);
586         ret = 0;
587 out_cleanup:
588         kunmap_atomic(user_mem);
589         if (is_partial_io(bvec))
590                 kfree(uncmem);
591         return ret;
592 }
593
594 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec, u32 index,
595                            int offset)
596 {
597         int ret = 0;
598         unsigned int clen;
599         unsigned long handle = 0;
600         struct page *page;
601         unsigned char *user_mem, *cmem, *src, *uncmem = NULL;
602         struct zram_meta *meta = zram->meta;
603         struct zcomp_strm *zstrm = NULL;
604         unsigned long alloced_pages;
605         unsigned long element;
606
607         page = bvec->bv_page;
608         if (is_partial_io(bvec)) {
609                 /*
610                  * This is a partial IO. We need to read the full page
611                  * before to write the changes.
612                  */
613                 uncmem = kmalloc(PAGE_SIZE, GFP_NOIO);
614                 if (!uncmem) {
615                         ret = -ENOMEM;
616                         goto out;
617                 }
618                 ret = zram_decompress_page(zram, uncmem, index);
619                 if (ret)
620                         goto out;
621         }
622
623 compress_again:
624         user_mem = kmap_atomic(page);
625         if (is_partial_io(bvec)) {
626                 memcpy(uncmem + offset, user_mem + bvec->bv_offset,
627                        bvec->bv_len);
628                 kunmap_atomic(user_mem);
629                 user_mem = NULL;
630         } else {
631                 uncmem = user_mem;
632         }
633
634         if (page_same_filled(uncmem, &element)) {
635                 if (user_mem)
636                         kunmap_atomic(user_mem);
637                 /* Free memory associated with this sector now. */
638                 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
639                 zram_free_page(zram, index);
640                 zram_set_flag(meta, index, ZRAM_SAME);
641                 zram_set_element(meta, index, element);
642                 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
643
644                 atomic64_inc(&zram->stats.same_pages);
645                 ret = 0;
646                 goto out;
647         }
648
649         zstrm = zcomp_stream_get(zram->comp);
650         ret = zcomp_compress(zstrm, uncmem, &clen);
651         if (!is_partial_io(bvec)) {
652                 kunmap_atomic(user_mem);
653                 user_mem = NULL;
654                 uncmem = NULL;
655         }
656
657         if (unlikely(ret)) {
658                 pr_err("Compression failed! err=%d\n", ret);
659                 goto out;
660         }
661
662         src = zstrm->buffer;
663         if (unlikely(clen > max_zpage_size)) {
664                 clen = PAGE_SIZE;
665                 if (is_partial_io(bvec))
666                         src = uncmem;
667         }
668
669         /*
670          * handle allocation has 2 paths:
671          * a) fast path is executed with preemption disabled (for
672          *  per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
673          *  since we can't sleep;
674          * b) slow path enables preemption and attempts to allocate
675          *  the page with __GFP_DIRECT_RECLAIM bit set. we have to
676          *  put per-cpu compression stream and, thus, to re-do
677          *  the compression once handle is allocated.
678          *
679          * if we have a 'non-null' handle here then we are coming
680          * from the slow path and handle has already been allocated.
681          */
682         if (!handle)
683                 handle = zs_malloc(meta->mem_pool, clen,
684                                 __GFP_KSWAPD_RECLAIM |
685                                 __GFP_NOWARN |
686                                 __GFP_HIGHMEM |
687                                 __GFP_MOVABLE);
688         if (!handle) {
689                 zcomp_stream_put(zram->comp);
690                 zstrm = NULL;
691
692                 atomic64_inc(&zram->stats.writestall);
693
694                 handle = zs_malloc(meta->mem_pool, clen,
695                                 GFP_NOIO | __GFP_HIGHMEM |
696                                 __GFP_MOVABLE);
697                 if (handle)
698                         goto compress_again;
699
700                 pr_err("Error allocating memory for compressed page: %u, size=%u\n",
701                         index, clen);
702                 ret = -ENOMEM;
703                 goto out;
704         }
705
706         alloced_pages = zs_get_total_pages(meta->mem_pool);
707         update_used_max(zram, alloced_pages);
708
709         if (zram->limit_pages && alloced_pages > zram->limit_pages) {
710                 zs_free(meta->mem_pool, handle);
711                 ret = -ENOMEM;
712                 goto out;
713         }
714
715         cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_WO);
716
717         if ((clen == PAGE_SIZE) && !is_partial_io(bvec)) {
718                 src = kmap_atomic(page);
719                 memcpy(cmem, src, PAGE_SIZE);
720                 kunmap_atomic(src);
721         } else {
722                 memcpy(cmem, src, clen);
723         }
724
725         zcomp_stream_put(zram->comp);
726         zstrm = NULL;
727         zs_unmap_object(meta->mem_pool, handle);
728
729         /*
730          * Free memory associated with this sector
731          * before overwriting unused sectors.
732          */
733         bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
734         zram_free_page(zram, index);
735
736         meta->table[index].handle = handle;
737         zram_set_obj_size(meta, index, clen);
738         bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
739
740         /* Update stats */
741         atomic64_add(clen, &zram->stats.compr_data_size);
742         atomic64_inc(&zram->stats.pages_stored);
743 out:
744         if (zstrm)
745                 zcomp_stream_put(zram->comp);
746         if (is_partial_io(bvec))
747                 kfree(uncmem);
748         return ret;
749 }
750
751 /*
752  * zram_bio_discard - handler on discard request
753  * @index: physical block index in PAGE_SIZE units
754  * @offset: byte offset within physical block
755  */
756 static void zram_bio_discard(struct zram *zram, u32 index,
757                              int offset, struct bio *bio)
758 {
759         size_t n = bio->bi_iter.bi_size;
760         struct zram_meta *meta = zram->meta;
761
762         /*
763          * zram manages data in physical block size units. Because logical block
764          * size isn't identical with physical block size on some arch, we
765          * could get a discard request pointing to a specific offset within a
766          * certain physical block.  Although we can handle this request by
767          * reading that physiclal block and decompressing and partially zeroing
768          * and re-compressing and then re-storing it, this isn't reasonable
769          * because our intent with a discard request is to save memory.  So
770          * skipping this logical block is appropriate here.
771          */
772         if (offset) {
773                 if (n <= (PAGE_SIZE - offset))
774                         return;
775
776                 n -= (PAGE_SIZE - offset);
777                 index++;
778         }
779
780         while (n >= PAGE_SIZE) {
781                 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
782                 zram_free_page(zram, index);
783                 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
784                 atomic64_inc(&zram->stats.notify_free);
785                 index++;
786                 n -= PAGE_SIZE;
787         }
788 }
789
790 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
791                         int offset, bool is_write)
792 {
793         unsigned long start_time = jiffies;
794         int rw_acct = is_write ? REQ_OP_WRITE : REQ_OP_READ;
795         int ret;
796
797         generic_start_io_acct(rw_acct, bvec->bv_len >> SECTOR_SHIFT,
798                         &zram->disk->part0);
799
800         if (!is_write) {
801                 atomic64_inc(&zram->stats.num_reads);
802                 ret = zram_bvec_read(zram, bvec, index, offset);
803         } else {
804                 atomic64_inc(&zram->stats.num_writes);
805                 ret = zram_bvec_write(zram, bvec, index, offset);
806         }
807
808         generic_end_io_acct(rw_acct, &zram->disk->part0, start_time);
809
810         if (unlikely(ret)) {
811                 if (!is_write)
812                         atomic64_inc(&zram->stats.failed_reads);
813                 else
814                         atomic64_inc(&zram->stats.failed_writes);
815         }
816
817         return ret;
818 }
819
820 static void __zram_make_request(struct zram *zram, struct bio *bio)
821 {
822         int offset;
823         u32 index;
824         struct bio_vec bvec;
825         struct bvec_iter iter;
826
827         index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
828         offset = (bio->bi_iter.bi_sector &
829                   (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
830
831         switch (bio_op(bio)) {
832         case REQ_OP_DISCARD:
833         case REQ_OP_WRITE_ZEROES:
834                 zram_bio_discard(zram, index, offset, bio);
835                 bio_endio(bio);
836                 return;
837         default:
838                 break;
839         }
840
841         bio_for_each_segment(bvec, bio, iter) {
842                 struct bio_vec bv = bvec;
843                 unsigned int unwritten = bvec.bv_len;
844
845                 do {
846                         bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
847                                                         unwritten);
848                         if (zram_bvec_rw(zram, &bv, index, offset,
849                                         op_is_write(bio_op(bio))) < 0)
850                                 goto out;
851
852                         bv.bv_offset += bv.bv_len;
853                         unwritten -= bv.bv_len;
854
855                         update_position(&index, &offset, &bv);
856                 } while (unwritten);
857         }
858
859         bio_endio(bio);
860         return;
861
862 out:
863         bio_io_error(bio);
864 }
865
866 /*
867  * Handler function for all zram I/O requests.
868  */
869 static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio)
870 {
871         struct zram *zram = queue->queuedata;
872
873         if (!valid_io_request(zram, bio->bi_iter.bi_sector,
874                                         bio->bi_iter.bi_size)) {
875                 atomic64_inc(&zram->stats.invalid_io);
876                 goto error;
877         }
878
879         __zram_make_request(zram, bio);
880         return BLK_QC_T_NONE;
881
882 error:
883         bio_io_error(bio);
884         return BLK_QC_T_NONE;
885 }
886
887 static void zram_slot_free_notify(struct block_device *bdev,
888                                 unsigned long index)
889 {
890         struct zram *zram;
891         struct zram_meta *meta;
892
893         zram = bdev->bd_disk->private_data;
894         meta = zram->meta;
895
896         bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
897         zram_free_page(zram, index);
898         bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
899         atomic64_inc(&zram->stats.notify_free);
900 }
901
902 static int zram_rw_page(struct block_device *bdev, sector_t sector,
903                        struct page *page, bool is_write)
904 {
905         int offset, err = -EIO;
906         u32 index;
907         struct zram *zram;
908         struct bio_vec bv;
909
910         zram = bdev->bd_disk->private_data;
911
912         if (!valid_io_request(zram, sector, PAGE_SIZE)) {
913                 atomic64_inc(&zram->stats.invalid_io);
914                 err = -EINVAL;
915                 goto out;
916         }
917
918         index = sector >> SECTORS_PER_PAGE_SHIFT;
919         offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
920
921         bv.bv_page = page;
922         bv.bv_len = PAGE_SIZE;
923         bv.bv_offset = 0;
924
925         err = zram_bvec_rw(zram, &bv, index, offset, is_write);
926 out:
927         /*
928          * If I/O fails, just return error(ie, non-zero) without
929          * calling page_endio.
930          * It causes resubmit the I/O with bio request by upper functions
931          * of rw_page(e.g., swap_readpage, __swap_writepage) and
932          * bio->bi_end_io does things to handle the error
933          * (e.g., SetPageError, set_page_dirty and extra works).
934          */
935         if (err == 0)
936                 page_endio(page, is_write, 0);
937         return err;
938 }
939
940 static void zram_reset_device(struct zram *zram)
941 {
942         struct zram_meta *meta;
943         struct zcomp *comp;
944         u64 disksize;
945
946         down_write(&zram->init_lock);
947
948         zram->limit_pages = 0;
949
950         if (!init_done(zram)) {
951                 up_write(&zram->init_lock);
952                 return;
953         }
954
955         meta = zram->meta;
956         comp = zram->comp;
957         disksize = zram->disksize;
958
959         /* Reset stats */
960         memset(&zram->stats, 0, sizeof(zram->stats));
961         zram->disksize = 0;
962
963         set_capacity(zram->disk, 0);
964         part_stat_set_all(&zram->disk->part0, 0);
965
966         up_write(&zram->init_lock);
967         /* I/O operation under all of CPU are done so let's free */
968         zram_meta_free(meta, disksize);
969         zcomp_destroy(comp);
970 }
971
972 static ssize_t disksize_store(struct device *dev,
973                 struct device_attribute *attr, const char *buf, size_t len)
974 {
975         u64 disksize;
976         struct zcomp *comp;
977         struct zram_meta *meta;
978         struct zram *zram = dev_to_zram(dev);
979         int err;
980
981         disksize = memparse(buf, NULL);
982         if (!disksize)
983                 return -EINVAL;
984
985         disksize = PAGE_ALIGN(disksize);
986         meta = zram_meta_alloc(zram->disk->disk_name, disksize);
987         if (!meta)
988                 return -ENOMEM;
989
990         comp = zcomp_create(zram->compressor);
991         if (IS_ERR(comp)) {
992                 pr_err("Cannot initialise %s compressing backend\n",
993                                 zram->compressor);
994                 err = PTR_ERR(comp);
995                 goto out_free_meta;
996         }
997
998         down_write(&zram->init_lock);
999         if (init_done(zram)) {
1000                 pr_info("Cannot change disksize for initialized device\n");
1001                 err = -EBUSY;
1002                 goto out_destroy_comp;
1003         }
1004
1005         zram->meta = meta;
1006         zram->comp = comp;
1007         zram->disksize = disksize;
1008         set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
1009         zram_revalidate_disk(zram);
1010         up_write(&zram->init_lock);
1011
1012         return len;
1013
1014 out_destroy_comp:
1015         up_write(&zram->init_lock);
1016         zcomp_destroy(comp);
1017 out_free_meta:
1018         zram_meta_free(meta, disksize);
1019         return err;
1020 }
1021
1022 static ssize_t reset_store(struct device *dev,
1023                 struct device_attribute *attr, const char *buf, size_t len)
1024 {
1025         int ret;
1026         unsigned short do_reset;
1027         struct zram *zram;
1028         struct block_device *bdev;
1029
1030         ret = kstrtou16(buf, 10, &do_reset);
1031         if (ret)
1032                 return ret;
1033
1034         if (!do_reset)
1035                 return -EINVAL;
1036
1037         zram = dev_to_zram(dev);
1038         bdev = bdget_disk(zram->disk, 0);
1039         if (!bdev)
1040                 return -ENOMEM;
1041
1042         mutex_lock(&bdev->bd_mutex);
1043         /* Do not reset an active device or claimed device */
1044         if (bdev->bd_openers || zram->claim) {
1045                 mutex_unlock(&bdev->bd_mutex);
1046                 bdput(bdev);
1047                 return -EBUSY;
1048         }
1049
1050         /* From now on, anyone can't open /dev/zram[0-9] */
1051         zram->claim = true;
1052         mutex_unlock(&bdev->bd_mutex);
1053
1054         /* Make sure all the pending I/O are finished */
1055         fsync_bdev(bdev);
1056         zram_reset_device(zram);
1057         zram_revalidate_disk(zram);
1058         bdput(bdev);
1059
1060         mutex_lock(&bdev->bd_mutex);
1061         zram->claim = false;
1062         mutex_unlock(&bdev->bd_mutex);
1063
1064         return len;
1065 }
1066
1067 static int zram_open(struct block_device *bdev, fmode_t mode)
1068 {
1069         int ret = 0;
1070         struct zram *zram;
1071
1072         WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
1073
1074         zram = bdev->bd_disk->private_data;
1075         /* zram was claimed to reset so open request fails */
1076         if (zram->claim)
1077                 ret = -EBUSY;
1078
1079         return ret;
1080 }
1081
1082 static const struct block_device_operations zram_devops = {
1083         .open = zram_open,
1084         .swap_slot_free_notify = zram_slot_free_notify,
1085         .rw_page = zram_rw_page,
1086         .owner = THIS_MODULE
1087 };
1088
1089 static DEVICE_ATTR_WO(compact);
1090 static DEVICE_ATTR_RW(disksize);
1091 static DEVICE_ATTR_RO(initstate);
1092 static DEVICE_ATTR_WO(reset);
1093 static DEVICE_ATTR_WO(mem_limit);
1094 static DEVICE_ATTR_WO(mem_used_max);
1095 static DEVICE_ATTR_RW(max_comp_streams);
1096 static DEVICE_ATTR_RW(comp_algorithm);
1097
1098 static struct attribute *zram_disk_attrs[] = {
1099         &dev_attr_disksize.attr,
1100         &dev_attr_initstate.attr,
1101         &dev_attr_reset.attr,
1102         &dev_attr_compact.attr,
1103         &dev_attr_mem_limit.attr,
1104         &dev_attr_mem_used_max.attr,
1105         &dev_attr_max_comp_streams.attr,
1106         &dev_attr_comp_algorithm.attr,
1107         &dev_attr_io_stat.attr,
1108         &dev_attr_mm_stat.attr,
1109         &dev_attr_debug_stat.attr,
1110         NULL,
1111 };
1112
1113 static struct attribute_group zram_disk_attr_group = {
1114         .attrs = zram_disk_attrs,
1115 };
1116
1117 /*
1118  * Allocate and initialize new zram device. the function returns
1119  * '>= 0' device_id upon success, and negative value otherwise.
1120  */
1121 static int zram_add(void)
1122 {
1123         struct zram *zram;
1124         struct request_queue *queue;
1125         int ret, device_id;
1126
1127         zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1128         if (!zram)
1129                 return -ENOMEM;
1130
1131         ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1132         if (ret < 0)
1133                 goto out_free_dev;
1134         device_id = ret;
1135
1136         init_rwsem(&zram->init_lock);
1137
1138         queue = blk_alloc_queue(GFP_KERNEL);
1139         if (!queue) {
1140                 pr_err("Error allocating disk queue for device %d\n",
1141                         device_id);
1142                 ret = -ENOMEM;
1143                 goto out_free_idr;
1144         }
1145
1146         blk_queue_make_request(queue, zram_make_request);
1147
1148         /* gendisk structure */
1149         zram->disk = alloc_disk(1);
1150         if (!zram->disk) {
1151                 pr_err("Error allocating disk structure for device %d\n",
1152                         device_id);
1153                 ret = -ENOMEM;
1154                 goto out_free_queue;
1155         }
1156
1157         zram->disk->major = zram_major;
1158         zram->disk->first_minor = device_id;
1159         zram->disk->fops = &zram_devops;
1160         zram->disk->queue = queue;
1161         zram->disk->queue->queuedata = zram;
1162         zram->disk->private_data = zram;
1163         snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1164
1165         /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1166         set_capacity(zram->disk, 0);
1167         /* zram devices sort of resembles non-rotational disks */
1168         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zram->disk->queue);
1169         queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1170         /*
1171          * To ensure that we always get PAGE_SIZE aligned
1172          * and n*PAGE_SIZED sized I/O requests.
1173          */
1174         blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1175         blk_queue_logical_block_size(zram->disk->queue,
1176                                         ZRAM_LOGICAL_BLOCK_SIZE);
1177         blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1178         blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1179         zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1180         blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1181         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, zram->disk->queue);
1182
1183         /*
1184          * zram_bio_discard() will clear all logical blocks if logical block
1185          * size is identical with physical block size(PAGE_SIZE). But if it is
1186          * different, we will skip discarding some parts of logical blocks in
1187          * the part of the request range which isn't aligned to physical block
1188          * size.  So we can't ensure that all discarded logical blocks are
1189          * zeroed.
1190          */
1191         if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1192                 blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
1193
1194         add_disk(zram->disk);
1195
1196         ret = sysfs_create_group(&disk_to_dev(zram->disk)->kobj,
1197                                 &zram_disk_attr_group);
1198         if (ret < 0) {
1199                 pr_err("Error creating sysfs group for device %d\n",
1200                                 device_id);
1201                 goto out_free_disk;
1202         }
1203         strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1204         zram->meta = NULL;
1205
1206         pr_info("Added device: %s\n", zram->disk->disk_name);
1207         return device_id;
1208
1209 out_free_disk:
1210         del_gendisk(zram->disk);
1211         put_disk(zram->disk);
1212 out_free_queue:
1213         blk_cleanup_queue(queue);
1214 out_free_idr:
1215         idr_remove(&zram_index_idr, device_id);
1216 out_free_dev:
1217         kfree(zram);
1218         return ret;
1219 }
1220
1221 static int zram_remove(struct zram *zram)
1222 {
1223         struct block_device *bdev;
1224
1225         bdev = bdget_disk(zram->disk, 0);
1226         if (!bdev)
1227                 return -ENOMEM;
1228
1229         mutex_lock(&bdev->bd_mutex);
1230         if (bdev->bd_openers || zram->claim) {
1231                 mutex_unlock(&bdev->bd_mutex);
1232                 bdput(bdev);
1233                 return -EBUSY;
1234         }
1235
1236         zram->claim = true;
1237         mutex_unlock(&bdev->bd_mutex);
1238
1239         /*
1240          * Remove sysfs first, so no one will perform a disksize
1241          * store while we destroy the devices. This also helps during
1242          * hot_remove -- zram_reset_device() is the last holder of
1243          * ->init_lock, no later/concurrent disksize_store() or any
1244          * other sysfs handlers are possible.
1245          */
1246         sysfs_remove_group(&disk_to_dev(zram->disk)->kobj,
1247                         &zram_disk_attr_group);
1248
1249         /* Make sure all the pending I/O are finished */
1250         fsync_bdev(bdev);
1251         zram_reset_device(zram);
1252         bdput(bdev);
1253
1254         pr_info("Removed device: %s\n", zram->disk->disk_name);
1255
1256         blk_cleanup_queue(zram->disk->queue);
1257         del_gendisk(zram->disk);
1258         put_disk(zram->disk);
1259         kfree(zram);
1260         return 0;
1261 }
1262
1263 /* zram-control sysfs attributes */
1264 static ssize_t hot_add_show(struct class *class,
1265                         struct class_attribute *attr,
1266                         char *buf)
1267 {
1268         int ret;
1269
1270         mutex_lock(&zram_index_mutex);
1271         ret = zram_add();
1272         mutex_unlock(&zram_index_mutex);
1273
1274         if (ret < 0)
1275                 return ret;
1276         return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
1277 }
1278
1279 static ssize_t hot_remove_store(struct class *class,
1280                         struct class_attribute *attr,
1281                         const char *buf,
1282                         size_t count)
1283 {
1284         struct zram *zram;
1285         int ret, dev_id;
1286
1287         /* dev_id is gendisk->first_minor, which is `int' */
1288         ret = kstrtoint(buf, 10, &dev_id);
1289         if (ret)
1290                 return ret;
1291         if (dev_id < 0)
1292                 return -EINVAL;
1293
1294         mutex_lock(&zram_index_mutex);
1295
1296         zram = idr_find(&zram_index_idr, dev_id);
1297         if (zram) {
1298                 ret = zram_remove(zram);
1299                 if (!ret)
1300                         idr_remove(&zram_index_idr, dev_id);
1301         } else {
1302                 ret = -ENODEV;
1303         }
1304
1305         mutex_unlock(&zram_index_mutex);
1306         return ret ? ret : count;
1307 }
1308
1309 /*
1310  * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
1311  * sense that reading from this file does alter the state of your system -- it
1312  * creates a new un-initialized zram device and returns back this device's
1313  * device_id (or an error code if it fails to create a new device).
1314  */
1315 static struct class_attribute zram_control_class_attrs[] = {
1316         __ATTR(hot_add, 0400, hot_add_show, NULL),
1317         __ATTR_WO(hot_remove),
1318         __ATTR_NULL,
1319 };
1320
1321 static struct class zram_control_class = {
1322         .name           = "zram-control",
1323         .owner          = THIS_MODULE,
1324         .class_attrs    = zram_control_class_attrs,
1325 };
1326
1327 static int zram_remove_cb(int id, void *ptr, void *data)
1328 {
1329         zram_remove(ptr);
1330         return 0;
1331 }
1332
1333 static void destroy_devices(void)
1334 {
1335         class_unregister(&zram_control_class);
1336         idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
1337         idr_destroy(&zram_index_idr);
1338         unregister_blkdev(zram_major, "zram");
1339         cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1340 }
1341
1342 static int __init zram_init(void)
1343 {
1344         int ret;
1345
1346         ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
1347                                       zcomp_cpu_up_prepare, zcomp_cpu_dead);
1348         if (ret < 0)
1349                 return ret;
1350
1351         ret = class_register(&zram_control_class);
1352         if (ret) {
1353                 pr_err("Unable to register zram-control class\n");
1354                 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1355                 return ret;
1356         }
1357
1358         zram_major = register_blkdev(0, "zram");
1359         if (zram_major <= 0) {
1360                 pr_err("Unable to get major number\n");
1361                 class_unregister(&zram_control_class);
1362                 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1363                 return -EBUSY;
1364         }
1365
1366         while (num_devices != 0) {
1367                 mutex_lock(&zram_index_mutex);
1368                 ret = zram_add();
1369                 mutex_unlock(&zram_index_mutex);
1370                 if (ret < 0)
1371                         goto out_error;
1372                 num_devices--;
1373         }
1374
1375         return 0;
1376
1377 out_error:
1378         destroy_devices();
1379         return ret;
1380 }
1381
1382 static void __exit zram_exit(void)
1383 {
1384         destroy_devices();
1385 }
1386
1387 module_init(zram_init);
1388 module_exit(zram_exit);
1389
1390 module_param(num_devices, uint, 0);
1391 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
1392
1393 MODULE_LICENSE("Dual BSD/GPL");
1394 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
1395 MODULE_DESCRIPTION("Compressed RAM Block Device");