zram: avoid double free in function zram_bvec_write()
[firefly-linux-kernel-4.4.55.git] / drivers / staging / zram / zram_drv.c
1 /*
2  * Compressed RAM block device
3  *
4  * Copyright (C) 2008, 2009, 2010  Nitin Gupta
5  *
6  * This code is released using a dual license strategy: BSD/GPL
7  * You can choose the licence that better fits your requirements.
8  *
9  * Released under the terms of 3-clause BSD License
10  * Released under the terms of GNU General Public License Version 2.0
11  *
12  * Project home: http://compcache.googlecode.com
13  */
14
15 #define KMSG_COMPONENT "zram"
16 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
17
18 #ifdef CONFIG_ZRAM_DEBUG
19 #define DEBUG
20 #endif
21
22 #include <linux/module.h>
23 #include <linux/kernel.h>
24 #include <linux/bio.h>
25 #include <linux/bitops.h>
26 #include <linux/blkdev.h>
27 #include <linux/buffer_head.h>
28 #include <linux/device.h>
29 #include <linux/genhd.h>
30 #include <linux/highmem.h>
31 #include <linux/slab.h>
32 #include <linux/lzo.h>
33 #include <linux/string.h>
34 #include <linux/vmalloc.h>
35
36 #include "zram_drv.h"
37
38 /* Globals */
39 static int zram_major;
40 struct zram *zram_devices;
41
42 /* Module params (documentation at end) */
43 static unsigned int num_devices = 1;
44
45 static void zram_stat64_add(struct zram *zram, u64 *v, u64 inc)
46 {
47         spin_lock(&zram->stat64_lock);
48         *v = *v + inc;
49         spin_unlock(&zram->stat64_lock);
50 }
51
52 static void zram_stat64_sub(struct zram *zram, u64 *v, u64 dec)
53 {
54         spin_lock(&zram->stat64_lock);
55         *v = *v - dec;
56         spin_unlock(&zram->stat64_lock);
57 }
58
59 static void zram_stat64_inc(struct zram *zram, u64 *v)
60 {
61         zram_stat64_add(zram, v, 1);
62 }
63
64 static int zram_test_flag(struct zram_meta *meta, u32 index,
65                         enum zram_pageflags flag)
66 {
67         return meta->table[index].flags & BIT(flag);
68 }
69
70 static void zram_set_flag(struct zram_meta *meta, u32 index,
71                         enum zram_pageflags flag)
72 {
73         meta->table[index].flags |= BIT(flag);
74 }
75
76 static void zram_clear_flag(struct zram_meta *meta, u32 index,
77                         enum zram_pageflags flag)
78 {
79         meta->table[index].flags &= ~BIT(flag);
80 }
81
82 static int page_zero_filled(void *ptr)
83 {
84         unsigned int pos;
85         unsigned long *page;
86
87         page = (unsigned long *)ptr;
88
89         for (pos = 0; pos != PAGE_SIZE / sizeof(*page); pos++) {
90                 if (page[pos])
91                         return 0;
92         }
93
94         return 1;
95 }
96
97 static void zram_free_page(struct zram *zram, size_t index)
98 {
99         struct zram_meta *meta = zram->meta;
100         unsigned long handle = meta->table[index].handle;
101         u16 size = meta->table[index].size;
102
103         if (unlikely(!handle)) {
104                 /*
105                  * No memory is allocated for zero filled pages.
106                  * Simply clear zero page flag.
107                  */
108                 if (zram_test_flag(meta, index, ZRAM_ZERO)) {
109                         zram_clear_flag(meta, index, ZRAM_ZERO);
110                         zram->stats.pages_zero--;
111                 }
112                 return;
113         }
114
115         if (unlikely(size > max_zpage_size))
116                 zram->stats.bad_compress--;
117
118         zs_free(meta->mem_pool, handle);
119
120         if (size <= PAGE_SIZE / 2)
121                 zram->stats.good_compress--;
122
123         zram_stat64_sub(zram, &zram->stats.compr_size,
124                         meta->table[index].size);
125         zram->stats.pages_stored--;
126
127         meta->table[index].handle = 0;
128         meta->table[index].size = 0;
129 }
130
131 static void handle_zero_page(struct bio_vec *bvec)
132 {
133         struct page *page = bvec->bv_page;
134         void *user_mem;
135
136         user_mem = kmap_atomic(page);
137         memset(user_mem + bvec->bv_offset, 0, bvec->bv_len);
138         kunmap_atomic(user_mem);
139
140         flush_dcache_page(page);
141 }
142
143 static inline int is_partial_io(struct bio_vec *bvec)
144 {
145         return bvec->bv_len != PAGE_SIZE;
146 }
147
148 static int zram_decompress_page(struct zram *zram, char *mem, u32 index)
149 {
150         int ret = LZO_E_OK;
151         size_t clen = PAGE_SIZE;
152         unsigned char *cmem;
153         struct zram_meta *meta = zram->meta;
154         unsigned long handle = meta->table[index].handle;
155
156         if (!handle || zram_test_flag(meta, index, ZRAM_ZERO)) {
157                 memset(mem, 0, PAGE_SIZE);
158                 return 0;
159         }
160
161         cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_RO);
162         if (meta->table[index].size == PAGE_SIZE)
163                 memcpy(mem, cmem, PAGE_SIZE);
164         else
165                 ret = lzo1x_decompress_safe(cmem, meta->table[index].size,
166                                                 mem, &clen);
167         zs_unmap_object(meta->mem_pool, handle);
168
169         /* Should NEVER happen. Return bio error if it does. */
170         if (unlikely(ret != LZO_E_OK)) {
171                 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
172                 zram_stat64_inc(zram, &zram->stats.failed_reads);
173                 return ret;
174         }
175
176         return 0;
177 }
178
179 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
180                           u32 index, int offset, struct bio *bio)
181 {
182         int ret;
183         struct page *page;
184         unsigned char *user_mem, *uncmem = NULL;
185         struct zram_meta *meta = zram->meta;
186         page = bvec->bv_page;
187
188         if (unlikely(!meta->table[index].handle) ||
189                         zram_test_flag(meta, index, ZRAM_ZERO)) {
190                 handle_zero_page(bvec);
191                 return 0;
192         }
193
194         if (is_partial_io(bvec))
195                 /* Use  a temporary buffer to decompress the page */
196                 uncmem = kmalloc(PAGE_SIZE, GFP_NOIO);
197
198         user_mem = kmap_atomic(page);
199         if (!is_partial_io(bvec))
200                 uncmem = user_mem;
201
202         if (!uncmem) {
203                 pr_info("Unable to allocate temp memory\n");
204                 ret = -ENOMEM;
205                 goto out_cleanup;
206         }
207
208         ret = zram_decompress_page(zram, uncmem, index);
209         /* Should NEVER happen. Return bio error if it does. */
210         if (unlikely(ret != LZO_E_OK))
211                 goto out_cleanup;
212
213         if (is_partial_io(bvec))
214                 memcpy(user_mem + bvec->bv_offset, uncmem + offset,
215                                 bvec->bv_len);
216
217         flush_dcache_page(page);
218         ret = 0;
219 out_cleanup:
220         kunmap_atomic(user_mem);
221         if (is_partial_io(bvec))
222                 kfree(uncmem);
223         return ret;
224 }
225
226 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec, u32 index,
227                            int offset)
228 {
229         int ret = 0;
230         size_t clen;
231         unsigned long handle;
232         struct page *page;
233         unsigned char *user_mem, *cmem, *src, *uncmem = NULL;
234         struct zram_meta *meta = zram->meta;
235
236         page = bvec->bv_page;
237         src = meta->compress_buffer;
238
239         if (is_partial_io(bvec)) {
240                 /*
241                  * This is a partial IO. We need to read the full page
242                  * before to write the changes.
243                  */
244                 uncmem = kmalloc(PAGE_SIZE, GFP_NOIO);
245                 if (!uncmem) {
246                         ret = -ENOMEM;
247                         goto out;
248                 }
249                 ret = zram_decompress_page(zram, uncmem, index);
250                 if (ret)
251                         goto out;
252         }
253
254         /*
255          * System overwrites unused sectors. Free memory associated
256          * with this sector now.
257          */
258         if (meta->table[index].handle ||
259             zram_test_flag(meta, index, ZRAM_ZERO))
260                 zram_free_page(zram, index);
261
262         user_mem = kmap_atomic(page);
263
264         if (is_partial_io(bvec)) {
265                 memcpy(uncmem + offset, user_mem + bvec->bv_offset,
266                        bvec->bv_len);
267                 kunmap_atomic(user_mem);
268                 user_mem = NULL;
269         } else {
270                 uncmem = user_mem;
271         }
272
273         if (page_zero_filled(uncmem)) {
274                 kunmap_atomic(user_mem);
275                 zram->stats.pages_zero++;
276                 zram_set_flag(meta, index, ZRAM_ZERO);
277                 ret = 0;
278                 goto out;
279         }
280
281         ret = lzo1x_1_compress(uncmem, PAGE_SIZE, src, &clen,
282                                meta->compress_workmem);
283
284         if (!is_partial_io(bvec)) {
285                 kunmap_atomic(user_mem);
286                 user_mem = NULL;
287                 uncmem = NULL;
288         }
289
290         if (unlikely(ret != LZO_E_OK)) {
291                 pr_err("Compression failed! err=%d\n", ret);
292                 goto out;
293         }
294
295         if (unlikely(clen > max_zpage_size)) {
296                 zram->stats.bad_compress++;
297                 clen = PAGE_SIZE;
298                 src = NULL;
299                 if (is_partial_io(bvec))
300                         src = uncmem;
301         }
302
303         handle = zs_malloc(meta->mem_pool, clen);
304         if (!handle) {
305                 pr_info("Error allocating memory for compressed "
306                         "page: %u, size=%zu\n", index, clen);
307                 ret = -ENOMEM;
308                 goto out;
309         }
310         cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_WO);
311
312         if ((clen == PAGE_SIZE) && !is_partial_io(bvec))
313                 src = kmap_atomic(page);
314         memcpy(cmem, src, clen);
315         if ((clen == PAGE_SIZE) && !is_partial_io(bvec))
316                 kunmap_atomic(src);
317
318         zs_unmap_object(meta->mem_pool, handle);
319
320         meta->table[index].handle = handle;
321         meta->table[index].size = clen;
322
323         /* Update stats */
324         zram_stat64_add(zram, &zram->stats.compr_size, clen);
325         zram->stats.pages_stored++;
326         if (clen <= PAGE_SIZE / 2)
327                 zram->stats.good_compress++;
328
329 out:
330         if (is_partial_io(bvec))
331                 kfree(uncmem);
332
333         if (ret)
334                 zram_stat64_inc(zram, &zram->stats.failed_writes);
335         return ret;
336 }
337
338 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
339                         int offset, struct bio *bio, int rw)
340 {
341         int ret;
342
343         if (rw == READ) {
344                 down_read(&zram->lock);
345                 ret = zram_bvec_read(zram, bvec, index, offset, bio);
346                 up_read(&zram->lock);
347         } else {
348                 down_write(&zram->lock);
349                 ret = zram_bvec_write(zram, bvec, index, offset);
350                 up_write(&zram->lock);
351         }
352
353         return ret;
354 }
355
356 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
357 {
358         if (*offset + bvec->bv_len >= PAGE_SIZE)
359                 (*index)++;
360         *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
361 }
362
363 static void __zram_make_request(struct zram *zram, struct bio *bio, int rw)
364 {
365         int i, offset;
366         u32 index;
367         struct bio_vec *bvec;
368
369         switch (rw) {
370         case READ:
371                 zram_stat64_inc(zram, &zram->stats.num_reads);
372                 break;
373         case WRITE:
374                 zram_stat64_inc(zram, &zram->stats.num_writes);
375                 break;
376         }
377
378         index = bio->bi_sector >> SECTORS_PER_PAGE_SHIFT;
379         offset = (bio->bi_sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
380
381         bio_for_each_segment(bvec, bio, i) {
382                 int max_transfer_size = PAGE_SIZE - offset;
383
384                 if (bvec->bv_len > max_transfer_size) {
385                         /*
386                          * zram_bvec_rw() can only make operation on a single
387                          * zram page. Split the bio vector.
388                          */
389                         struct bio_vec bv;
390
391                         bv.bv_page = bvec->bv_page;
392                         bv.bv_len = max_transfer_size;
393                         bv.bv_offset = bvec->bv_offset;
394
395                         if (zram_bvec_rw(zram, &bv, index, offset, bio, rw) < 0)
396                                 goto out;
397
398                         bv.bv_len = bvec->bv_len - max_transfer_size;
399                         bv.bv_offset += max_transfer_size;
400                         if (zram_bvec_rw(zram, &bv, index+1, 0, bio, rw) < 0)
401                                 goto out;
402                 } else
403                         if (zram_bvec_rw(zram, bvec, index, offset, bio, rw)
404                             < 0)
405                                 goto out;
406
407                 update_position(&index, &offset, bvec);
408         }
409
410         set_bit(BIO_UPTODATE, &bio->bi_flags);
411         bio_endio(bio, 0);
412         return;
413
414 out:
415         bio_io_error(bio);
416 }
417
418 /*
419  * Check if request is within bounds and aligned on zram logical blocks.
420  */
421 static inline int valid_io_request(struct zram *zram, struct bio *bio)
422 {
423         if (unlikely(
424                 (bio->bi_sector >= (zram->disksize >> SECTOR_SHIFT)) ||
425                 (bio->bi_sector & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)) ||
426                 (bio->bi_size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))) {
427
428                 return 0;
429         }
430
431         /* I/O request is valid */
432         return 1;
433 }
434
435 /*
436  * Handler function for all zram I/O requests.
437  */
438 static void zram_make_request(struct request_queue *queue, struct bio *bio)
439 {
440         struct zram *zram = queue->queuedata;
441
442         down_read(&zram->init_lock);
443         if (unlikely(!zram->init_done))
444                 goto error;
445
446         if (!valid_io_request(zram, bio)) {
447                 zram_stat64_inc(zram, &zram->stats.invalid_io);
448                 goto error;
449         }
450
451         __zram_make_request(zram, bio, bio_data_dir(bio));
452         up_read(&zram->init_lock);
453
454         return;
455
456 error:
457         up_read(&zram->init_lock);
458         bio_io_error(bio);
459 }
460
461 static void __zram_reset_device(struct zram *zram)
462 {
463         size_t index;
464         struct zram_meta *meta;
465
466         if (!zram->init_done)
467                 return;
468
469         meta = zram->meta;
470         zram->init_done = 0;
471
472         /* Free all pages that are still in this zram device */
473         for (index = 0; index < zram->disksize >> PAGE_SHIFT; index++) {
474                 unsigned long handle = meta->table[index].handle;
475                 if (!handle)
476                         continue;
477
478                 zs_free(meta->mem_pool, handle);
479         }
480
481         zram_meta_free(zram->meta);
482         zram->meta = NULL;
483         /* Reset stats */
484         memset(&zram->stats, 0, sizeof(zram->stats));
485
486         zram->disksize = 0;
487         set_capacity(zram->disk, 0);
488 }
489
490 void zram_reset_device(struct zram *zram)
491 {
492         down_write(&zram->init_lock);
493         __zram_reset_device(zram);
494         up_write(&zram->init_lock);
495 }
496
497 void zram_meta_free(struct zram_meta *meta)
498 {
499         zs_destroy_pool(meta->mem_pool);
500         kfree(meta->compress_workmem);
501         free_pages((unsigned long)meta->compress_buffer, 1);
502         vfree(meta->table);
503         kfree(meta);
504 }
505
506 struct zram_meta *zram_meta_alloc(u64 disksize)
507 {
508         size_t num_pages;
509         struct zram_meta *meta = kmalloc(sizeof(*meta), GFP_KERNEL);
510         if (!meta)
511                 goto out;
512
513         meta->compress_workmem = kzalloc(LZO1X_MEM_COMPRESS, GFP_KERNEL);
514         if (!meta->compress_workmem)
515                 goto free_meta;
516
517         meta->compress_buffer =
518                 (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, 1);
519         if (!meta->compress_buffer) {
520                 pr_err("Error allocating compressor buffer space\n");
521                 goto free_workmem;
522         }
523
524         num_pages = disksize >> PAGE_SHIFT;
525         meta->table = vzalloc(num_pages * sizeof(*meta->table));
526         if (!meta->table) {
527                 pr_err("Error allocating zram address table\n");
528                 goto free_buffer;
529         }
530
531         meta->mem_pool = zs_create_pool(GFP_NOIO | __GFP_HIGHMEM);
532         if (!meta->mem_pool) {
533                 pr_err("Error creating memory pool\n");
534                 goto free_table;
535         }
536
537         return meta;
538
539 free_table:
540         vfree(meta->table);
541 free_buffer:
542         free_pages((unsigned long)meta->compress_buffer, 1);
543 free_workmem:
544         kfree(meta->compress_workmem);
545 free_meta:
546         kfree(meta);
547         meta = NULL;
548 out:
549         return meta;
550 }
551
552 void zram_init_device(struct zram *zram, struct zram_meta *meta)
553 {
554         if (zram->disksize > 2 * (totalram_pages << PAGE_SHIFT)) {
555                 pr_info(
556                 "There is little point creating a zram of greater than "
557                 "twice the size of memory since we expect a 2:1 compression "
558                 "ratio. Note that zram uses about 0.1%% of the size of "
559                 "the disk when not in use so a huge zram is "
560                 "wasteful.\n"
561                 "\tMemory Size: %lu kB\n"
562                 "\tSize you selected: %llu kB\n"
563                 "Continuing anyway ...\n",
564                 (totalram_pages << PAGE_SHIFT) >> 10, zram->disksize >> 10
565                 );
566         }
567
568         /* zram devices sort of resembles non-rotational disks */
569         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zram->disk->queue);
570
571         zram->meta = meta;
572         zram->init_done = 1;
573
574         pr_debug("Initialization done!\n");
575 }
576
577 static void zram_slot_free_notify(struct block_device *bdev,
578                                 unsigned long index)
579 {
580         struct zram *zram;
581
582         zram = bdev->bd_disk->private_data;
583         down_write(&zram->lock);
584         zram_free_page(zram, index);
585         up_write(&zram->lock);
586         zram_stat64_inc(zram, &zram->stats.notify_free);
587 }
588
589 static const struct block_device_operations zram_devops = {
590         .swap_slot_free_notify = zram_slot_free_notify,
591         .owner = THIS_MODULE
592 };
593
594 static int create_device(struct zram *zram, int device_id)
595 {
596         int ret = -ENOMEM;
597
598         init_rwsem(&zram->lock);
599         init_rwsem(&zram->init_lock);
600         spin_lock_init(&zram->stat64_lock);
601
602         zram->queue = blk_alloc_queue(GFP_KERNEL);
603         if (!zram->queue) {
604                 pr_err("Error allocating disk queue for device %d\n",
605                         device_id);
606                 goto out;
607         }
608
609         blk_queue_make_request(zram->queue, zram_make_request);
610         zram->queue->queuedata = zram;
611
612          /* gendisk structure */
613         zram->disk = alloc_disk(1);
614         if (!zram->disk) {
615                 pr_warn("Error allocating disk structure for device %d\n",
616                         device_id);
617                 goto out_free_queue;
618         }
619
620         zram->disk->major = zram_major;
621         zram->disk->first_minor = device_id;
622         zram->disk->fops = &zram_devops;
623         zram->disk->queue = zram->queue;
624         zram->disk->private_data = zram;
625         snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
626
627         /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
628         set_capacity(zram->disk, 0);
629
630         /*
631          * To ensure that we always get PAGE_SIZE aligned
632          * and n*PAGE_SIZED sized I/O requests.
633          */
634         blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
635         blk_queue_logical_block_size(zram->disk->queue,
636                                         ZRAM_LOGICAL_BLOCK_SIZE);
637         blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
638         blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
639
640         add_disk(zram->disk);
641
642         ret = sysfs_create_group(&disk_to_dev(zram->disk)->kobj,
643                                 &zram_disk_attr_group);
644         if (ret < 0) {
645                 pr_warn("Error creating sysfs group");
646                 goto out_free_disk;
647         }
648
649         zram->init_done = 0;
650         return 0;
651
652 out_free_disk:
653         del_gendisk(zram->disk);
654         put_disk(zram->disk);
655 out_free_queue:
656         blk_cleanup_queue(zram->queue);
657 out:
658         return ret;
659 }
660
661 static void destroy_device(struct zram *zram)
662 {
663         sysfs_remove_group(&disk_to_dev(zram->disk)->kobj,
664                         &zram_disk_attr_group);
665
666         if (zram->disk) {
667                 del_gendisk(zram->disk);
668                 put_disk(zram->disk);
669         }
670
671         if (zram->queue)
672                 blk_cleanup_queue(zram->queue);
673 }
674
675 unsigned int zram_get_num_devices(void)
676 {
677         return num_devices;
678 }
679
680 static int __init zram_init(void)
681 {
682         int ret, dev_id;
683
684         if (num_devices > max_num_devices) {
685                 pr_warn("Invalid value for num_devices: %u\n",
686                                 num_devices);
687                 ret = -EINVAL;
688                 goto out;
689         }
690
691         zram_major = register_blkdev(0, "zram");
692         if (zram_major <= 0) {
693                 pr_warn("Unable to get major number\n");
694                 ret = -EBUSY;
695                 goto out;
696         }
697
698         /* Allocate the device array and initialize each one */
699         zram_devices = kzalloc(num_devices * sizeof(struct zram), GFP_KERNEL);
700         if (!zram_devices) {
701                 ret = -ENOMEM;
702                 goto unregister;
703         }
704
705         for (dev_id = 0; dev_id < num_devices; dev_id++) {
706                 ret = create_device(&zram_devices[dev_id], dev_id);
707                 if (ret)
708                         goto free_devices;
709         }
710
711         pr_info("Created %u device(s) ...\n", num_devices);
712
713         return 0;
714
715 free_devices:
716         while (dev_id)
717                 destroy_device(&zram_devices[--dev_id]);
718         kfree(zram_devices);
719 unregister:
720         unregister_blkdev(zram_major, "zram");
721 out:
722         return ret;
723 }
724
725 static void __exit zram_exit(void)
726 {
727         int i;
728         struct zram *zram;
729
730         for (i = 0; i < num_devices; i++) {
731                 zram = &zram_devices[i];
732
733                 get_disk(zram->disk);
734                 destroy_device(zram);
735                 zram_reset_device(zram);
736                 put_disk(zram->disk);
737         }
738
739         unregister_blkdev(zram_major, "zram");
740
741         kfree(zram_devices);
742         pr_debug("Cleanup done!\n");
743 }
744
745 module_param(num_devices, uint, 0);
746 MODULE_PARM_DESC(num_devices, "Number of zram devices");
747
748 module_init(zram_init);
749 module_exit(zram_exit);
750
751 MODULE_LICENSE("Dual BSD/GPL");
752 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
753 MODULE_DESCRIPTION("Compressed RAM Block Device");