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