2 * Compressed RAM block device
4 * Copyright (C) 2008, 2009, 2010 Nitin Gupta
6 * This code is released using a dual license strategy: BSD/GPL
7 * You can choose the licence that better fits your requirements.
9 * Released under the terms of 3-clause BSD License
10 * Released under the terms of GNU General Public License Version 2.0
12 * Project home: http://compcache.googlecode.com
15 #define KMSG_COMPONENT "zram"
16 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
18 #ifdef CONFIG_ZRAM_DEBUG
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>
39 static int zram_major;
40 struct zram *zram_devices;
42 /* Module params (documentation at end) */
43 static unsigned int num_devices = 1;
45 static void zram_stat64_add(struct zram *zram, u64 *v, u64 inc)
47 spin_lock(&zram->stat64_lock);
49 spin_unlock(&zram->stat64_lock);
52 static void zram_stat64_sub(struct zram *zram, u64 *v, u64 dec)
54 spin_lock(&zram->stat64_lock);
56 spin_unlock(&zram->stat64_lock);
59 static void zram_stat64_inc(struct zram *zram, u64 *v)
61 zram_stat64_add(zram, v, 1);
64 static int zram_test_flag(struct zram *zram, u32 index,
65 enum zram_pageflags flag)
67 return zram->table[index].flags & BIT(flag);
70 static void zram_set_flag(struct zram *zram, u32 index,
71 enum zram_pageflags flag)
73 zram->table[index].flags |= BIT(flag);
76 static void zram_clear_flag(struct zram *zram, u32 index,
77 enum zram_pageflags flag)
79 zram->table[index].flags &= ~BIT(flag);
82 static int page_zero_filled(void *ptr)
87 page = (unsigned long *)ptr;
89 for (pos = 0; pos != PAGE_SIZE / sizeof(*page); pos++) {
97 static void zram_set_disksize(struct zram *zram, size_t totalram_bytes)
99 if (!zram->disksize) {
101 "disk size not provided. You can use disksize_kb module "
102 "param to specify size.\nUsing default: (%u%% of RAM).\n",
103 default_disksize_perc_ram
105 zram->disksize = default_disksize_perc_ram *
106 (totalram_bytes / 100);
109 if (zram->disksize > 2 * (totalram_bytes)) {
111 "There is little point creating a zram of greater than "
112 "twice the size of memory since we expect a 2:1 compression "
113 "ratio. Note that zram uses about 0.1%% of the size of "
114 "the disk when not in use so a huge zram is "
116 "\tMemory Size: %zu kB\n"
117 "\tSize you selected: %llu kB\n"
118 "Continuing anyway ...\n",
119 totalram_bytes >> 10, zram->disksize >> 10);
122 zram->disksize &= PAGE_MASK;
125 static void zram_free_page(struct zram *zram, size_t index)
127 unsigned long handle = zram->table[index].handle;
128 u16 size = zram->table[index].size;
130 if (unlikely(!handle)) {
132 * No memory is allocated for zero filled pages.
133 * Simply clear zero page flag.
135 if (zram_test_flag(zram, index, ZRAM_ZERO)) {
136 zram_clear_flag(zram, index, ZRAM_ZERO);
137 zram->stats.pages_zero--;
142 if (unlikely(size > max_zpage_size))
143 zram->stats.bad_compress--;
145 zs_free(zram->mem_pool, handle);
147 if (size <= PAGE_SIZE / 2)
148 zram->stats.good_compress--;
150 zram_stat64_sub(zram, &zram->stats.compr_size,
151 zram->table[index].size);
152 zram->stats.pages_stored--;
154 zram->table[index].handle = 0;
155 zram->table[index].size = 0;
158 static void handle_zero_page(struct bio_vec *bvec)
160 struct page *page = bvec->bv_page;
163 user_mem = kmap_atomic(page);
164 memset(user_mem + bvec->bv_offset, 0, bvec->bv_len);
165 kunmap_atomic(user_mem);
167 flush_dcache_page(page);
170 static inline int is_partial_io(struct bio_vec *bvec)
172 return bvec->bv_len != PAGE_SIZE;
175 static int zram_decompress_page(struct zram *zram, char *mem, u32 index)
178 size_t clen = PAGE_SIZE;
180 unsigned long handle = zram->table[index].handle;
182 if (!handle || zram_test_flag(zram, index, ZRAM_ZERO)) {
183 memset(mem, 0, PAGE_SIZE);
187 cmem = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
188 if (zram->table[index].size == PAGE_SIZE)
189 memcpy(mem, cmem, PAGE_SIZE);
191 ret = lzo1x_decompress_safe(cmem, zram->table[index].size,
193 zs_unmap_object(zram->mem_pool, handle);
195 /* Should NEVER happen. Return bio error if it does. */
196 if (unlikely(ret != LZO_E_OK)) {
197 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
198 zram_stat64_inc(zram, &zram->stats.failed_reads);
205 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
206 u32 index, int offset, struct bio *bio)
210 unsigned char *user_mem, *uncmem = NULL;
212 page = bvec->bv_page;
214 if (unlikely(!zram->table[index].handle) ||
215 zram_test_flag(zram, index, ZRAM_ZERO)) {
216 handle_zero_page(bvec);
220 user_mem = kmap_atomic(page);
221 if (is_partial_io(bvec))
222 /* Use a temporary buffer to decompress the page */
223 uncmem = kmalloc(PAGE_SIZE, GFP_KERNEL);
228 pr_info("Unable to allocate temp memory\n");
233 ret = zram_decompress_page(zram, uncmem, index);
234 /* Should NEVER happen. Return bio error if it does. */
235 if (unlikely(ret != LZO_E_OK)) {
236 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
237 zram_stat64_inc(zram, &zram->stats.failed_reads);
241 if (is_partial_io(bvec))
242 memcpy(user_mem + bvec->bv_offset, uncmem + offset,
245 flush_dcache_page(page);
248 kunmap_atomic(user_mem);
249 if (is_partial_io(bvec))
254 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec, u32 index,
259 unsigned long handle;
261 unsigned char *user_mem, *cmem, *src, *uncmem = NULL;
263 page = bvec->bv_page;
264 src = zram->compress_buffer;
266 if (is_partial_io(bvec)) {
268 * This is a partial IO. We need to read the full page
269 * before to write the changes.
271 uncmem = kmalloc(PAGE_SIZE, GFP_KERNEL);
273 pr_info("Error allocating temp memory!\n");
277 ret = zram_decompress_page(zram, uncmem, index);
283 * System overwrites unused sectors. Free memory associated
284 * with this sector now.
286 if (zram->table[index].handle ||
287 zram_test_flag(zram, index, ZRAM_ZERO))
288 zram_free_page(zram, index);
290 user_mem = kmap_atomic(page);
292 if (is_partial_io(bvec)) {
293 memcpy(uncmem + offset, user_mem + bvec->bv_offset,
295 kunmap_atomic(user_mem);
301 if (page_zero_filled(uncmem)) {
302 kunmap_atomic(user_mem);
303 if (is_partial_io(bvec))
305 zram->stats.pages_zero++;
306 zram_set_flag(zram, index, ZRAM_ZERO);
311 ret = lzo1x_1_compress(uncmem, PAGE_SIZE, src, &clen,
312 zram->compress_workmem);
314 if (!is_partial_io(bvec)) {
315 kunmap_atomic(user_mem);
320 if (unlikely(ret != LZO_E_OK)) {
321 pr_err("Compression failed! err=%d\n", ret);
325 if (unlikely(clen > max_zpage_size)) {
326 zram->stats.bad_compress++;
329 if (is_partial_io(bvec))
333 handle = zs_malloc(zram->mem_pool, clen);
335 pr_info("Error allocating memory for compressed "
336 "page: %u, size=%zu\n", index, clen);
340 cmem = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
342 if ((clen == PAGE_SIZE) && !is_partial_io(bvec))
343 src = kmap_atomic(page);
344 memcpy(cmem, src, clen);
345 if ((clen == PAGE_SIZE) && !is_partial_io(bvec))
348 zs_unmap_object(zram->mem_pool, handle);
350 zram->table[index].handle = handle;
351 zram->table[index].size = clen;
354 zram_stat64_add(zram, &zram->stats.compr_size, clen);
355 zram->stats.pages_stored++;
356 if (clen <= PAGE_SIZE / 2)
357 zram->stats.good_compress++;
360 if (is_partial_io(bvec))
364 zram_stat64_inc(zram, &zram->stats.failed_writes);
368 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
369 int offset, struct bio *bio, int rw)
374 down_read(&zram->lock);
375 ret = zram_bvec_read(zram, bvec, index, offset, bio);
376 up_read(&zram->lock);
378 down_write(&zram->lock);
379 ret = zram_bvec_write(zram, bvec, index, offset);
380 up_write(&zram->lock);
386 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
388 if (*offset + bvec->bv_len >= PAGE_SIZE)
390 *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
393 static void __zram_make_request(struct zram *zram, struct bio *bio, int rw)
397 struct bio_vec *bvec;
401 zram_stat64_inc(zram, &zram->stats.num_reads);
404 zram_stat64_inc(zram, &zram->stats.num_writes);
408 index = bio->bi_sector >> SECTORS_PER_PAGE_SHIFT;
409 offset = (bio->bi_sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
411 bio_for_each_segment(bvec, bio, i) {
412 int max_transfer_size = PAGE_SIZE - offset;
414 if (bvec->bv_len > max_transfer_size) {
416 * zram_bvec_rw() can only make operation on a single
417 * zram page. Split the bio vector.
421 bv.bv_page = bvec->bv_page;
422 bv.bv_len = max_transfer_size;
423 bv.bv_offset = bvec->bv_offset;
425 if (zram_bvec_rw(zram, &bv, index, offset, bio, rw) < 0)
428 bv.bv_len = bvec->bv_len - max_transfer_size;
429 bv.bv_offset += max_transfer_size;
430 if (zram_bvec_rw(zram, &bv, index+1, 0, bio, rw) < 0)
433 if (zram_bvec_rw(zram, bvec, index, offset, bio, rw)
437 update_position(&index, &offset, bvec);
440 set_bit(BIO_UPTODATE, &bio->bi_flags);
449 * Check if request is within bounds and aligned on zram logical blocks.
451 static inline int valid_io_request(struct zram *zram, struct bio *bio)
454 (bio->bi_sector >= (zram->disksize >> SECTOR_SHIFT)) ||
455 (bio->bi_sector & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)) ||
456 (bio->bi_size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))) {
461 /* I/O request is valid */
466 * Handler function for all zram I/O requests.
468 static void zram_make_request(struct request_queue *queue, struct bio *bio)
470 struct zram *zram = queue->queuedata;
472 if (unlikely(!zram->init_done) && zram_init_device(zram))
475 down_read(&zram->init_lock);
476 if (unlikely(!zram->init_done))
479 if (!valid_io_request(zram, bio)) {
480 zram_stat64_inc(zram, &zram->stats.invalid_io);
484 __zram_make_request(zram, bio, bio_data_dir(bio));
485 up_read(&zram->init_lock);
490 up_read(&zram->init_lock);
495 void __zram_reset_device(struct zram *zram)
501 /* Free various per-device buffers */
502 kfree(zram->compress_workmem);
503 free_pages((unsigned long)zram->compress_buffer, 1);
505 zram->compress_workmem = NULL;
506 zram->compress_buffer = NULL;
508 /* Free all pages that are still in this zram device */
509 for (index = 0; index < zram->disksize >> PAGE_SHIFT; index++) {
510 unsigned long handle = zram->table[index].handle;
514 zs_free(zram->mem_pool, handle);
520 zs_destroy_pool(zram->mem_pool);
521 zram->mem_pool = NULL;
524 memset(&zram->stats, 0, sizeof(zram->stats));
529 void zram_reset_device(struct zram *zram)
531 down_write(&zram->init_lock);
532 __zram_reset_device(zram);
533 up_write(&zram->init_lock);
536 int zram_init_device(struct zram *zram)
541 down_write(&zram->init_lock);
543 if (zram->init_done) {
544 up_write(&zram->init_lock);
548 zram_set_disksize(zram, totalram_pages << PAGE_SHIFT);
550 zram->compress_workmem = kzalloc(LZO1X_MEM_COMPRESS, GFP_KERNEL);
551 if (!zram->compress_workmem) {
552 pr_err("Error allocating compressor working memory!\n");
557 zram->compress_buffer =
558 (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, 1);
559 if (!zram->compress_buffer) {
560 pr_err("Error allocating compressor buffer space\n");
565 num_pages = zram->disksize >> PAGE_SHIFT;
566 zram->table = vzalloc(num_pages * sizeof(*zram->table));
568 pr_err("Error allocating zram address table\n");
573 set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
575 /* zram devices sort of resembles non-rotational disks */
576 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zram->disk->queue);
578 zram->mem_pool = zs_create_pool("zram", GFP_NOIO | __GFP_HIGHMEM);
579 if (!zram->mem_pool) {
580 pr_err("Error creating memory pool\n");
586 up_write(&zram->init_lock);
588 pr_debug("Initialization done!\n");
592 /* To prevent accessing table entries during cleanup */
595 __zram_reset_device(zram);
596 up_write(&zram->init_lock);
597 pr_err("Initialization failed: err=%d\n", ret);
601 static void zram_slot_free_notify(struct block_device *bdev,
606 zram = bdev->bd_disk->private_data;
607 zram_free_page(zram, index);
608 zram_stat64_inc(zram, &zram->stats.notify_free);
611 static const struct block_device_operations zram_devops = {
612 .swap_slot_free_notify = zram_slot_free_notify,
616 static int create_device(struct zram *zram, int device_id)
620 init_rwsem(&zram->lock);
621 init_rwsem(&zram->init_lock);
622 spin_lock_init(&zram->stat64_lock);
624 zram->queue = blk_alloc_queue(GFP_KERNEL);
626 pr_err("Error allocating disk queue for device %d\n",
632 blk_queue_make_request(zram->queue, zram_make_request);
633 zram->queue->queuedata = zram;
635 /* gendisk structure */
636 zram->disk = alloc_disk(1);
638 blk_cleanup_queue(zram->queue);
639 pr_warn("Error allocating disk structure for device %d\n",
645 zram->disk->major = zram_major;
646 zram->disk->first_minor = device_id;
647 zram->disk->fops = &zram_devops;
648 zram->disk->queue = zram->queue;
649 zram->disk->private_data = zram;
650 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
652 /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
653 set_capacity(zram->disk, 0);
656 * To ensure that we always get PAGE_SIZE aligned
657 * and n*PAGE_SIZED sized I/O requests.
659 blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
660 blk_queue_logical_block_size(zram->disk->queue,
661 ZRAM_LOGICAL_BLOCK_SIZE);
662 blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
663 blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
665 add_disk(zram->disk);
667 ret = sysfs_create_group(&disk_to_dev(zram->disk)->kobj,
668 &zram_disk_attr_group);
670 pr_warn("Error creating sysfs group");
680 static void destroy_device(struct zram *zram)
682 sysfs_remove_group(&disk_to_dev(zram->disk)->kobj,
683 &zram_disk_attr_group);
686 del_gendisk(zram->disk);
687 put_disk(zram->disk);
691 blk_cleanup_queue(zram->queue);
694 unsigned int zram_get_num_devices(void)
699 static int __init zram_init(void)
703 if (num_devices > max_num_devices) {
704 pr_warn("Invalid value for num_devices: %u\n",
710 zram_major = register_blkdev(0, "zram");
711 if (zram_major <= 0) {
712 pr_warn("Unable to get major number\n");
717 /* Allocate the device array and initialize each one */
718 zram_devices = kzalloc(num_devices * sizeof(struct zram), GFP_KERNEL);
724 for (dev_id = 0; dev_id < num_devices; dev_id++) {
725 ret = create_device(&zram_devices[dev_id], dev_id);
730 pr_info("Created %u device(s) ...\n", num_devices);
736 destroy_device(&zram_devices[--dev_id]);
739 unregister_blkdev(zram_major, "zram");
744 static void __exit zram_exit(void)
749 for (i = 0; i < num_devices; i++) {
750 zram = &zram_devices[i];
752 destroy_device(zram);
754 zram_reset_device(zram);
757 unregister_blkdev(zram_major, "zram");
760 pr_debug("Cleanup done!\n");
763 module_param(num_devices, uint, 0);
764 MODULE_PARM_DESC(num_devices, "Number of zram devices");
766 module_init(zram_init);
767 module_exit(zram_exit);
769 MODULE_LICENSE("Dual BSD/GPL");
770 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
771 MODULE_DESCRIPTION("Compressed RAM Block Device");