2 * Compressed RAM block device
4 * Copyright (C) 2008, 2009, 2010 Nitin Gupta
5 * 2012, 2013 Minchan Kim
7 * This code is released using a dual license strategy: BSD/GPL
8 * You can choose the licence that better fits your requirements.
10 * Released under the terms of 3-clause BSD License
11 * Released under the terms of GNU General Public License Version 2.0
15 #define KMSG_COMPONENT "zram"
16 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
18 #include <linux/module.h>
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/bitops.h>
22 #include <linux/blkdev.h>
23 #include <linux/buffer_head.h>
24 #include <linux/device.h>
25 #include <linux/genhd.h>
26 #include <linux/highmem.h>
27 #include <linux/slab.h>
28 #include <linux/backing-dev.h>
29 #include <linux/string.h>
30 #include <linux/vmalloc.h>
31 #include <linux/err.h>
32 #include <linux/idr.h>
33 #include <linux/sysfs.h>
34 #include <linux/debugfs.h>
35 #include <linux/cpuhotplug.h>
36 #include <linux/part_stat.h>
40 static DEFINE_IDR(zram_index_idr);
41 /* idr index must be protected */
42 static DEFINE_MUTEX(zram_index_mutex);
44 static int zram_major;
45 static const char *default_compressor = "lzo-rle";
47 /* Module params (documentation at end) */
48 static unsigned int num_devices = 1;
50 * Pages that compress to sizes equals or greater than this are stored
51 * uncompressed in memory.
53 static size_t huge_class_size;
55 static void zram_free_page(struct zram *zram, size_t index);
56 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
57 u32 index, int offset, struct bio *bio);
60 static int zram_slot_trylock(struct zram *zram, u32 index)
62 return bit_spin_trylock(ZRAM_LOCK, &zram->table[index].flags);
65 static void zram_slot_lock(struct zram *zram, u32 index)
67 bit_spin_lock(ZRAM_LOCK, &zram->table[index].flags);
70 static void zram_slot_unlock(struct zram *zram, u32 index)
72 bit_spin_unlock(ZRAM_LOCK, &zram->table[index].flags);
75 static inline bool init_done(struct zram *zram)
77 return zram->disksize;
80 static inline struct zram *dev_to_zram(struct device *dev)
82 return (struct zram *)dev_to_disk(dev)->private_data;
85 static unsigned long zram_get_handle(struct zram *zram, u32 index)
87 return zram->table[index].handle;
90 static void zram_set_handle(struct zram *zram, u32 index, unsigned long handle)
92 zram->table[index].handle = handle;
95 /* flag operations require table entry bit_spin_lock() being held */
96 static bool zram_test_flag(struct zram *zram, u32 index,
97 enum zram_pageflags flag)
99 return zram->table[index].flags & BIT(flag);
102 static void zram_set_flag(struct zram *zram, u32 index,
103 enum zram_pageflags flag)
105 zram->table[index].flags |= BIT(flag);
108 static void zram_clear_flag(struct zram *zram, u32 index,
109 enum zram_pageflags flag)
111 zram->table[index].flags &= ~BIT(flag);
114 static inline void zram_set_element(struct zram *zram, u32 index,
115 unsigned long element)
117 zram->table[index].element = element;
120 static unsigned long zram_get_element(struct zram *zram, u32 index)
122 return zram->table[index].element;
125 static size_t zram_get_obj_size(struct zram *zram, u32 index)
127 return zram->table[index].flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
130 static void zram_set_obj_size(struct zram *zram,
131 u32 index, size_t size)
133 unsigned long flags = zram->table[index].flags >> ZRAM_FLAG_SHIFT;
135 zram->table[index].flags = (flags << ZRAM_FLAG_SHIFT) | size;
138 static inline bool zram_allocated(struct zram *zram, u32 index)
140 return zram_get_obj_size(zram, index) ||
141 zram_test_flag(zram, index, ZRAM_SAME) ||
142 zram_test_flag(zram, index, ZRAM_WB);
145 #if PAGE_SIZE != 4096
146 static inline bool is_partial_io(struct bio_vec *bvec)
148 return bvec->bv_len != PAGE_SIZE;
151 static inline bool is_partial_io(struct bio_vec *bvec)
158 * Check if request is within bounds and aligned on zram logical blocks.
160 static inline bool valid_io_request(struct zram *zram,
161 sector_t start, unsigned int size)
165 /* unaligned request */
166 if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
168 if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
171 end = start + (size >> SECTOR_SHIFT);
172 bound = zram->disksize >> SECTOR_SHIFT;
173 /* out of range range */
174 if (unlikely(start >= bound || end > bound || start > end))
177 /* I/O request is valid */
181 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
183 *index += (*offset + bvec->bv_len) / PAGE_SIZE;
184 *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
187 static inline void update_used_max(struct zram *zram,
188 const unsigned long pages)
190 unsigned long old_max, cur_max;
192 old_max = atomic_long_read(&zram->stats.max_used_pages);
197 old_max = atomic_long_cmpxchg(
198 &zram->stats.max_used_pages, cur_max, pages);
199 } while (old_max != cur_max);
202 static inline void zram_fill_page(void *ptr, unsigned long len,
205 WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
206 memset_l(ptr, value, len / sizeof(unsigned long));
209 static bool page_same_filled(void *ptr, unsigned long *element)
213 unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
215 page = (unsigned long *)ptr;
218 if (val != page[last_pos])
221 for (pos = 1; pos < last_pos; pos++) {
222 if (val != page[pos])
231 static ssize_t initstate_show(struct device *dev,
232 struct device_attribute *attr, char *buf)
235 struct zram *zram = dev_to_zram(dev);
237 down_read(&zram->init_lock);
238 val = init_done(zram);
239 up_read(&zram->init_lock);
241 return scnprintf(buf, PAGE_SIZE, "%u\n", val);
244 static ssize_t disksize_show(struct device *dev,
245 struct device_attribute *attr, char *buf)
247 struct zram *zram = dev_to_zram(dev);
249 return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
252 static ssize_t mem_limit_store(struct device *dev,
253 struct device_attribute *attr, const char *buf, size_t len)
257 struct zram *zram = dev_to_zram(dev);
259 limit = memparse(buf, &tmp);
260 if (buf == tmp) /* no chars parsed, invalid input */
263 down_write(&zram->init_lock);
264 zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
265 up_write(&zram->init_lock);
270 static ssize_t mem_used_max_store(struct device *dev,
271 struct device_attribute *attr, const char *buf, size_t len)
275 struct zram *zram = dev_to_zram(dev);
277 err = kstrtoul(buf, 10, &val);
281 down_read(&zram->init_lock);
282 if (init_done(zram)) {
283 atomic_long_set(&zram->stats.max_used_pages,
284 zs_get_total_pages(zram->mem_pool));
286 up_read(&zram->init_lock);
291 static ssize_t idle_store(struct device *dev,
292 struct device_attribute *attr, const char *buf, size_t len)
294 struct zram *zram = dev_to_zram(dev);
295 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
298 if (!sysfs_streq(buf, "all"))
301 down_read(&zram->init_lock);
302 if (!init_done(zram)) {
303 up_read(&zram->init_lock);
307 for (index = 0; index < nr_pages; index++) {
309 * Do not mark ZRAM_UNDER_WB slot as ZRAM_IDLE to close race.
310 * See the comment in writeback_store.
312 zram_slot_lock(zram, index);
313 if (zram_allocated(zram, index) &&
314 !zram_test_flag(zram, index, ZRAM_UNDER_WB))
315 zram_set_flag(zram, index, ZRAM_IDLE);
316 zram_slot_unlock(zram, index);
319 up_read(&zram->init_lock);
324 #ifdef CONFIG_ZRAM_WRITEBACK
325 static ssize_t writeback_limit_enable_store(struct device *dev,
326 struct device_attribute *attr, const char *buf, size_t len)
328 struct zram *zram = dev_to_zram(dev);
330 ssize_t ret = -EINVAL;
332 if (kstrtoull(buf, 10, &val))
335 down_read(&zram->init_lock);
336 spin_lock(&zram->wb_limit_lock);
337 zram->wb_limit_enable = val;
338 spin_unlock(&zram->wb_limit_lock);
339 up_read(&zram->init_lock);
345 static ssize_t writeback_limit_enable_show(struct device *dev,
346 struct device_attribute *attr, char *buf)
349 struct zram *zram = dev_to_zram(dev);
351 down_read(&zram->init_lock);
352 spin_lock(&zram->wb_limit_lock);
353 val = zram->wb_limit_enable;
354 spin_unlock(&zram->wb_limit_lock);
355 up_read(&zram->init_lock);
357 return scnprintf(buf, PAGE_SIZE, "%d\n", val);
360 static ssize_t writeback_limit_store(struct device *dev,
361 struct device_attribute *attr, const char *buf, size_t len)
363 struct zram *zram = dev_to_zram(dev);
365 ssize_t ret = -EINVAL;
367 if (kstrtoull(buf, 10, &val))
370 down_read(&zram->init_lock);
371 spin_lock(&zram->wb_limit_lock);
372 zram->bd_wb_limit = val;
373 spin_unlock(&zram->wb_limit_lock);
374 up_read(&zram->init_lock);
380 static ssize_t writeback_limit_show(struct device *dev,
381 struct device_attribute *attr, char *buf)
384 struct zram *zram = dev_to_zram(dev);
386 down_read(&zram->init_lock);
387 spin_lock(&zram->wb_limit_lock);
388 val = zram->bd_wb_limit;
389 spin_unlock(&zram->wb_limit_lock);
390 up_read(&zram->init_lock);
392 return scnprintf(buf, PAGE_SIZE, "%llu\n", val);
395 static void reset_bdev(struct zram *zram)
397 struct block_device *bdev;
399 if (!zram->backing_dev)
403 if (zram->old_block_size)
404 set_blocksize(bdev, zram->old_block_size);
405 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
406 /* hope filp_close flush all of IO */
407 filp_close(zram->backing_dev, NULL);
408 zram->backing_dev = NULL;
409 zram->old_block_size = 0;
411 zram->disk->queue->backing_dev_info->capabilities |=
412 BDI_CAP_SYNCHRONOUS_IO;
413 kvfree(zram->bitmap);
417 static ssize_t backing_dev_show(struct device *dev,
418 struct device_attribute *attr, char *buf)
421 struct zram *zram = dev_to_zram(dev);
425 down_read(&zram->init_lock);
426 file = zram->backing_dev;
428 memcpy(buf, "none\n", 5);
429 up_read(&zram->init_lock);
433 p = file_path(file, buf, PAGE_SIZE - 1);
440 memmove(buf, p, ret);
443 up_read(&zram->init_lock);
447 static ssize_t backing_dev_store(struct device *dev,
448 struct device_attribute *attr, const char *buf, size_t len)
452 struct file *backing_dev = NULL;
454 struct address_space *mapping;
455 unsigned int bitmap_sz, old_block_size = 0;
456 unsigned long nr_pages, *bitmap = NULL;
457 struct block_device *bdev = NULL;
459 struct zram *zram = dev_to_zram(dev);
461 file_name = kmalloc(PATH_MAX, GFP_KERNEL);
465 down_write(&zram->init_lock);
466 if (init_done(zram)) {
467 pr_info("Can't setup backing device for initialized device\n");
472 strlcpy(file_name, buf, PATH_MAX);
473 /* ignore trailing newline */
474 sz = strlen(file_name);
475 if (sz > 0 && file_name[sz - 1] == '\n')
476 file_name[sz - 1] = 0x00;
478 backing_dev = filp_open(file_name, O_RDWR|O_LARGEFILE, 0);
479 if (IS_ERR(backing_dev)) {
480 err = PTR_ERR(backing_dev);
485 mapping = backing_dev->f_mapping;
486 inode = mapping->host;
488 /* Support only block device in this moment */
489 if (!S_ISBLK(inode->i_mode)) {
494 bdev = bdgrab(I_BDEV(inode));
495 err = blkdev_get(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL, zram);
501 nr_pages = i_size_read(inode) >> PAGE_SHIFT;
502 bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
503 bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
509 old_block_size = block_size(bdev);
510 err = set_blocksize(bdev, PAGE_SIZE);
516 zram->old_block_size = old_block_size;
518 zram->backing_dev = backing_dev;
519 zram->bitmap = bitmap;
520 zram->nr_pages = nr_pages;
522 * With writeback feature, zram does asynchronous IO so it's no longer
523 * synchronous device so let's remove synchronous io flag. Othewise,
524 * upper layer(e.g., swap) could wait IO completion rather than
525 * (submit and return), which will cause system sluggish.
526 * Furthermore, when the IO function returns(e.g., swap_readpage),
527 * upper layer expects IO was done so it could deallocate the page
528 * freely but in fact, IO is going on so finally could cause
529 * use-after-free when the IO is really done.
531 zram->disk->queue->backing_dev_info->capabilities &=
532 ~BDI_CAP_SYNCHRONOUS_IO;
533 up_write(&zram->init_lock);
535 pr_info("setup backing device %s\n", file_name);
544 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
547 filp_close(backing_dev, NULL);
549 up_write(&zram->init_lock);
556 static unsigned long alloc_block_bdev(struct zram *zram)
558 unsigned long blk_idx = 1;
560 /* skip 0 bit to confuse zram.handle = 0 */
561 blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, blk_idx);
562 if (blk_idx == zram->nr_pages)
565 if (test_and_set_bit(blk_idx, zram->bitmap))
568 atomic64_inc(&zram->stats.bd_count);
572 static void free_block_bdev(struct zram *zram, unsigned long blk_idx)
576 was_set = test_and_clear_bit(blk_idx, zram->bitmap);
577 WARN_ON_ONCE(!was_set);
578 atomic64_dec(&zram->stats.bd_count);
581 static void zram_page_end_io(struct bio *bio)
583 struct page *page = bio_first_page_all(bio);
585 page_endio(page, op_is_write(bio_op(bio)),
586 blk_status_to_errno(bio->bi_status));
591 * Returns 1 if the submission is successful.
593 static int read_from_bdev_async(struct zram *zram, struct bio_vec *bvec,
594 unsigned long entry, struct bio *parent)
598 bio = bio_alloc(GFP_ATOMIC, 1);
602 bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
603 bio_set_dev(bio, zram->bdev);
604 if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset)) {
610 bio->bi_opf = REQ_OP_READ;
611 bio->bi_end_io = zram_page_end_io;
613 bio->bi_opf = parent->bi_opf;
614 bio_chain(bio, parent);
621 #define HUGE_WRITEBACK 1
622 #define IDLE_WRITEBACK 2
624 static ssize_t writeback_store(struct device *dev,
625 struct device_attribute *attr, const char *buf, size_t len)
627 struct zram *zram = dev_to_zram(dev);
628 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
631 struct bio_vec bio_vec;
635 unsigned long blk_idx = 0;
637 if (sysfs_streq(buf, "idle"))
638 mode = IDLE_WRITEBACK;
639 else if (sysfs_streq(buf, "huge"))
640 mode = HUGE_WRITEBACK;
644 down_read(&zram->init_lock);
645 if (!init_done(zram)) {
647 goto release_init_lock;
650 if (!zram->backing_dev) {
652 goto release_init_lock;
655 page = alloc_page(GFP_KERNEL);
658 goto release_init_lock;
661 for (index = 0; index < nr_pages; index++) {
665 bvec.bv_len = PAGE_SIZE;
668 spin_lock(&zram->wb_limit_lock);
669 if (zram->wb_limit_enable && !zram->bd_wb_limit) {
670 spin_unlock(&zram->wb_limit_lock);
674 spin_unlock(&zram->wb_limit_lock);
677 blk_idx = alloc_block_bdev(zram);
684 zram_slot_lock(zram, index);
685 if (!zram_allocated(zram, index))
688 if (zram_test_flag(zram, index, ZRAM_WB) ||
689 zram_test_flag(zram, index, ZRAM_SAME) ||
690 zram_test_flag(zram, index, ZRAM_UNDER_WB))
693 if (mode == IDLE_WRITEBACK &&
694 !zram_test_flag(zram, index, ZRAM_IDLE))
696 if (mode == HUGE_WRITEBACK &&
697 !zram_test_flag(zram, index, ZRAM_HUGE))
700 * Clearing ZRAM_UNDER_WB is duty of caller.
701 * IOW, zram_free_page never clear it.
703 zram_set_flag(zram, index, ZRAM_UNDER_WB);
704 /* Need for hugepage writeback racing */
705 zram_set_flag(zram, index, ZRAM_IDLE);
706 zram_slot_unlock(zram, index);
707 if (zram_bvec_read(zram, &bvec, index, 0, NULL)) {
708 zram_slot_lock(zram, index);
709 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
710 zram_clear_flag(zram, index, ZRAM_IDLE);
711 zram_slot_unlock(zram, index);
715 bio_init(&bio, &bio_vec, 1);
716 bio_set_dev(&bio, zram->bdev);
717 bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
718 bio.bi_opf = REQ_OP_WRITE | REQ_SYNC;
720 bio_add_page(&bio, bvec.bv_page, bvec.bv_len,
723 * XXX: A single page IO would be inefficient for write
724 * but it would be not bad as starter.
726 ret = submit_bio_wait(&bio);
728 zram_slot_lock(zram, index);
729 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
730 zram_clear_flag(zram, index, ZRAM_IDLE);
731 zram_slot_unlock(zram, index);
735 atomic64_inc(&zram->stats.bd_writes);
737 * We released zram_slot_lock so need to check if the slot was
738 * changed. If there is freeing for the slot, we can catch it
739 * easily by zram_allocated.
740 * A subtle case is the slot is freed/reallocated/marked as
741 * ZRAM_IDLE again. To close the race, idle_store doesn't
742 * mark ZRAM_IDLE once it found the slot was ZRAM_UNDER_WB.
743 * Thus, we could close the race by checking ZRAM_IDLE bit.
745 zram_slot_lock(zram, index);
746 if (!zram_allocated(zram, index) ||
747 !zram_test_flag(zram, index, ZRAM_IDLE)) {
748 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
749 zram_clear_flag(zram, index, ZRAM_IDLE);
753 zram_free_page(zram, index);
754 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
755 zram_set_flag(zram, index, ZRAM_WB);
756 zram_set_element(zram, index, blk_idx);
758 atomic64_inc(&zram->stats.pages_stored);
759 spin_lock(&zram->wb_limit_lock);
760 if (zram->wb_limit_enable && zram->bd_wb_limit > 0)
761 zram->bd_wb_limit -= 1UL << (PAGE_SHIFT - 12);
762 spin_unlock(&zram->wb_limit_lock);
764 zram_slot_unlock(zram, index);
768 free_block_bdev(zram, blk_idx);
771 up_read(&zram->init_lock);
777 struct work_struct work;
784 #if PAGE_SIZE != 4096
785 static void zram_sync_read(struct work_struct *work)
787 struct zram_work *zw = container_of(work, struct zram_work, work);
788 struct zram *zram = zw->zram;
789 unsigned long entry = zw->entry;
790 struct bio *bio = zw->bio;
792 read_from_bdev_async(zram, &zw->bvec, entry, bio);
796 * Block layer want one ->make_request_fn to be active at a time
797 * so if we use chained IO with parent IO in same context,
798 * it's a deadlock. To avoid, it, it uses worker thread context.
800 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
801 unsigned long entry, struct bio *bio)
803 struct zram_work work;
810 INIT_WORK_ONSTACK(&work.work, zram_sync_read);
811 queue_work(system_unbound_wq, &work.work);
812 flush_work(&work.work);
813 destroy_work_on_stack(&work.work);
818 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
819 unsigned long entry, struct bio *bio)
826 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
827 unsigned long entry, struct bio *parent, bool sync)
829 atomic64_inc(&zram->stats.bd_reads);
831 return read_from_bdev_sync(zram, bvec, entry, parent);
833 return read_from_bdev_async(zram, bvec, entry, parent);
836 static inline void reset_bdev(struct zram *zram) {};
837 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
838 unsigned long entry, struct bio *parent, bool sync)
843 static void free_block_bdev(struct zram *zram, unsigned long blk_idx) {};
846 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
848 static struct dentry *zram_debugfs_root;
850 static void zram_debugfs_create(void)
852 zram_debugfs_root = debugfs_create_dir("zram", NULL);
855 static void zram_debugfs_destroy(void)
857 debugfs_remove_recursive(zram_debugfs_root);
860 static void zram_accessed(struct zram *zram, u32 index)
862 zram_clear_flag(zram, index, ZRAM_IDLE);
863 zram->table[index].ac_time = ktime_get_boottime();
866 static ssize_t read_block_state(struct file *file, char __user *buf,
867 size_t count, loff_t *ppos)
870 ssize_t index, written = 0;
871 struct zram *zram = file->private_data;
872 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
873 struct timespec64 ts;
875 kbuf = kvmalloc(count, GFP_KERNEL);
879 down_read(&zram->init_lock);
880 if (!init_done(zram)) {
881 up_read(&zram->init_lock);
886 for (index = *ppos; index < nr_pages; index++) {
889 zram_slot_lock(zram, index);
890 if (!zram_allocated(zram, index))
893 ts = ktime_to_timespec64(zram->table[index].ac_time);
894 copied = snprintf(kbuf + written, count,
895 "%12zd %12lld.%06lu %c%c%c%c\n",
896 index, (s64)ts.tv_sec,
897 ts.tv_nsec / NSEC_PER_USEC,
898 zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
899 zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
900 zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
901 zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.');
903 if (count < copied) {
904 zram_slot_unlock(zram, index);
910 zram_slot_unlock(zram, index);
914 up_read(&zram->init_lock);
915 if (copy_to_user(buf, kbuf, written))
922 static const struct file_operations proc_zram_block_state_op = {
924 .read = read_block_state,
925 .llseek = default_llseek,
928 static void zram_debugfs_register(struct zram *zram)
930 if (!zram_debugfs_root)
933 zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
935 debugfs_create_file("block_state", 0400, zram->debugfs_dir,
936 zram, &proc_zram_block_state_op);
939 static void zram_debugfs_unregister(struct zram *zram)
941 debugfs_remove_recursive(zram->debugfs_dir);
944 static void zram_debugfs_create(void) {};
945 static void zram_debugfs_destroy(void) {};
946 static void zram_accessed(struct zram *zram, u32 index)
948 zram_clear_flag(zram, index, ZRAM_IDLE);
950 static void zram_debugfs_register(struct zram *zram) {};
951 static void zram_debugfs_unregister(struct zram *zram) {};
955 * We switched to per-cpu streams and this attr is not needed anymore.
956 * However, we will keep it around for some time, because:
957 * a) we may revert per-cpu streams in the future
958 * b) it's visible to user space and we need to follow our 2 years
959 * retirement rule; but we already have a number of 'soon to be
960 * altered' attrs, so max_comp_streams need to wait for the next
963 static ssize_t max_comp_streams_show(struct device *dev,
964 struct device_attribute *attr, char *buf)
966 return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
969 static ssize_t max_comp_streams_store(struct device *dev,
970 struct device_attribute *attr, const char *buf, size_t len)
975 static ssize_t comp_algorithm_show(struct device *dev,
976 struct device_attribute *attr, char *buf)
979 struct zram *zram = dev_to_zram(dev);
981 down_read(&zram->init_lock);
982 sz = zcomp_available_show(zram->compressor, buf);
983 up_read(&zram->init_lock);
988 static ssize_t comp_algorithm_store(struct device *dev,
989 struct device_attribute *attr, const char *buf, size_t len)
991 struct zram *zram = dev_to_zram(dev);
992 char compressor[ARRAY_SIZE(zram->compressor)];
995 strlcpy(compressor, buf, sizeof(compressor));
996 /* ignore trailing newline */
997 sz = strlen(compressor);
998 if (sz > 0 && compressor[sz - 1] == '\n')
999 compressor[sz - 1] = 0x00;
1001 if (!zcomp_available_algorithm(compressor))
1004 down_write(&zram->init_lock);
1005 if (init_done(zram)) {
1006 up_write(&zram->init_lock);
1007 pr_info("Can't change algorithm for initialized device\n");
1011 strcpy(zram->compressor, compressor);
1012 up_write(&zram->init_lock);
1016 static ssize_t compact_store(struct device *dev,
1017 struct device_attribute *attr, const char *buf, size_t len)
1019 struct zram *zram = dev_to_zram(dev);
1021 down_read(&zram->init_lock);
1022 if (!init_done(zram)) {
1023 up_read(&zram->init_lock);
1027 zs_compact(zram->mem_pool);
1028 up_read(&zram->init_lock);
1033 static ssize_t io_stat_show(struct device *dev,
1034 struct device_attribute *attr, char *buf)
1036 struct zram *zram = dev_to_zram(dev);
1039 down_read(&zram->init_lock);
1040 ret = scnprintf(buf, PAGE_SIZE,
1041 "%8llu %8llu %8llu %8llu\n",
1042 (u64)atomic64_read(&zram->stats.failed_reads),
1043 (u64)atomic64_read(&zram->stats.failed_writes),
1044 (u64)atomic64_read(&zram->stats.invalid_io),
1045 (u64)atomic64_read(&zram->stats.notify_free));
1046 up_read(&zram->init_lock);
1051 static ssize_t mm_stat_show(struct device *dev,
1052 struct device_attribute *attr, char *buf)
1054 struct zram *zram = dev_to_zram(dev);
1055 struct zs_pool_stats pool_stats;
1056 u64 orig_size, mem_used = 0;
1060 memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1062 down_read(&zram->init_lock);
1063 if (init_done(zram)) {
1064 mem_used = zs_get_total_pages(zram->mem_pool);
1065 zs_pool_stats(zram->mem_pool, &pool_stats);
1068 orig_size = atomic64_read(&zram->stats.pages_stored);
1069 max_used = atomic_long_read(&zram->stats.max_used_pages);
1071 ret = scnprintf(buf, PAGE_SIZE,
1072 "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu\n",
1073 orig_size << PAGE_SHIFT,
1074 (u64)atomic64_read(&zram->stats.compr_data_size),
1075 mem_used << PAGE_SHIFT,
1076 zram->limit_pages << PAGE_SHIFT,
1077 max_used << PAGE_SHIFT,
1078 (u64)atomic64_read(&zram->stats.same_pages),
1079 pool_stats.pages_compacted,
1080 (u64)atomic64_read(&zram->stats.huge_pages));
1081 up_read(&zram->init_lock);
1086 #ifdef CONFIG_ZRAM_WRITEBACK
1087 #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
1088 static ssize_t bd_stat_show(struct device *dev,
1089 struct device_attribute *attr, char *buf)
1091 struct zram *zram = dev_to_zram(dev);
1094 down_read(&zram->init_lock);
1095 ret = scnprintf(buf, PAGE_SIZE,
1096 "%8llu %8llu %8llu\n",
1097 FOUR_K((u64)atomic64_read(&zram->stats.bd_count)),
1098 FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)),
1099 FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)));
1100 up_read(&zram->init_lock);
1106 static ssize_t debug_stat_show(struct device *dev,
1107 struct device_attribute *attr, char *buf)
1110 struct zram *zram = dev_to_zram(dev);
1113 down_read(&zram->init_lock);
1114 ret = scnprintf(buf, PAGE_SIZE,
1115 "version: %d\n%8llu %8llu\n",
1117 (u64)atomic64_read(&zram->stats.writestall),
1118 (u64)atomic64_read(&zram->stats.miss_free));
1119 up_read(&zram->init_lock);
1124 static DEVICE_ATTR_RO(io_stat);
1125 static DEVICE_ATTR_RO(mm_stat);
1126 #ifdef CONFIG_ZRAM_WRITEBACK
1127 static DEVICE_ATTR_RO(bd_stat);
1129 static DEVICE_ATTR_RO(debug_stat);
1131 static void zram_meta_free(struct zram *zram, u64 disksize)
1133 size_t num_pages = disksize >> PAGE_SHIFT;
1136 /* Free all pages that are still in this zram device */
1137 for (index = 0; index < num_pages; index++)
1138 zram_free_page(zram, index);
1140 zs_destroy_pool(zram->mem_pool);
1144 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
1148 num_pages = disksize >> PAGE_SHIFT;
1149 zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
1153 zram->mem_pool = zs_create_pool(zram->disk->disk_name);
1154 if (!zram->mem_pool) {
1159 if (!huge_class_size)
1160 huge_class_size = zs_huge_class_size(zram->mem_pool);
1165 * To protect concurrent access to the same index entry,
1166 * caller should hold this table index entry's bit_spinlock to
1167 * indicate this index entry is accessing.
1169 static void zram_free_page(struct zram *zram, size_t index)
1171 unsigned long handle;
1173 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
1174 zram->table[index].ac_time = 0;
1176 if (zram_test_flag(zram, index, ZRAM_IDLE))
1177 zram_clear_flag(zram, index, ZRAM_IDLE);
1179 if (zram_test_flag(zram, index, ZRAM_HUGE)) {
1180 zram_clear_flag(zram, index, ZRAM_HUGE);
1181 atomic64_dec(&zram->stats.huge_pages);
1184 if (zram_test_flag(zram, index, ZRAM_WB)) {
1185 zram_clear_flag(zram, index, ZRAM_WB);
1186 free_block_bdev(zram, zram_get_element(zram, index));
1191 * No memory is allocated for same element filled pages.
1192 * Simply clear same page flag.
1194 if (zram_test_flag(zram, index, ZRAM_SAME)) {
1195 zram_clear_flag(zram, index, ZRAM_SAME);
1196 atomic64_dec(&zram->stats.same_pages);
1200 handle = zram_get_handle(zram, index);
1204 zs_free(zram->mem_pool, handle);
1206 atomic64_sub(zram_get_obj_size(zram, index),
1207 &zram->stats.compr_data_size);
1209 atomic64_dec(&zram->stats.pages_stored);
1210 zram_set_handle(zram, index, 0);
1211 zram_set_obj_size(zram, index, 0);
1212 WARN_ON_ONCE(zram->table[index].flags &
1213 ~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB));
1216 static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index,
1217 struct bio *bio, bool partial_io)
1220 unsigned long handle;
1224 zram_slot_lock(zram, index);
1225 if (zram_test_flag(zram, index, ZRAM_WB)) {
1226 struct bio_vec bvec;
1228 zram_slot_unlock(zram, index);
1230 bvec.bv_page = page;
1231 bvec.bv_len = PAGE_SIZE;
1233 return read_from_bdev(zram, &bvec,
1234 zram_get_element(zram, index),
1238 handle = zram_get_handle(zram, index);
1239 if (!handle || zram_test_flag(zram, index, ZRAM_SAME)) {
1240 unsigned long value;
1243 value = handle ? zram_get_element(zram, index) : 0;
1244 mem = kmap_atomic(page);
1245 zram_fill_page(mem, PAGE_SIZE, value);
1247 zram_slot_unlock(zram, index);
1251 size = zram_get_obj_size(zram, index);
1253 src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
1254 if (size == PAGE_SIZE) {
1255 dst = kmap_atomic(page);
1256 memcpy(dst, src, PAGE_SIZE);
1260 struct zcomp_strm *zstrm = zcomp_stream_get(zram->comp);
1262 dst = kmap_atomic(page);
1263 ret = zcomp_decompress(zstrm, src, size, dst);
1265 zcomp_stream_put(zram->comp);
1267 zs_unmap_object(zram->mem_pool, handle);
1268 zram_slot_unlock(zram, index);
1270 /* Should NEVER happen. Return bio error if it does. */
1272 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1277 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1278 u32 index, int offset, struct bio *bio)
1283 page = bvec->bv_page;
1284 if (is_partial_io(bvec)) {
1285 /* Use a temporary buffer to decompress the page */
1286 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1291 ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec));
1295 if (is_partial_io(bvec)) {
1296 void *dst = kmap_atomic(bvec->bv_page);
1297 void *src = kmap_atomic(page);
1299 memcpy(dst + bvec->bv_offset, src + offset, bvec->bv_len);
1304 if (is_partial_io(bvec))
1310 static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1311 u32 index, struct bio *bio)
1314 unsigned long alloced_pages;
1315 unsigned long handle = 0;
1316 unsigned int comp_len = 0;
1317 void *src, *dst, *mem;
1318 struct zcomp_strm *zstrm;
1319 struct page *page = bvec->bv_page;
1320 unsigned long element = 0;
1321 enum zram_pageflags flags = 0;
1323 mem = kmap_atomic(page);
1324 if (page_same_filled(mem, &element)) {
1326 /* Free memory associated with this sector now. */
1328 atomic64_inc(&zram->stats.same_pages);
1334 zstrm = zcomp_stream_get(zram->comp);
1335 src = kmap_atomic(page);
1336 ret = zcomp_compress(zstrm, src, &comp_len);
1339 if (unlikely(ret)) {
1340 zcomp_stream_put(zram->comp);
1341 pr_err("Compression failed! err=%d\n", ret);
1342 zs_free(zram->mem_pool, handle);
1346 if (comp_len >= huge_class_size)
1347 comp_len = PAGE_SIZE;
1349 * handle allocation has 2 paths:
1350 * a) fast path is executed with preemption disabled (for
1351 * per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
1352 * since we can't sleep;
1353 * b) slow path enables preemption and attempts to allocate
1354 * the page with __GFP_DIRECT_RECLAIM bit set. we have to
1355 * put per-cpu compression stream and, thus, to re-do
1356 * the compression once handle is allocated.
1358 * if we have a 'non-null' handle here then we are coming
1359 * from the slow path and handle has already been allocated.
1362 handle = zs_malloc(zram->mem_pool, comp_len,
1363 __GFP_KSWAPD_RECLAIM |
1368 zcomp_stream_put(zram->comp);
1369 atomic64_inc(&zram->stats.writestall);
1370 handle = zs_malloc(zram->mem_pool, comp_len,
1371 GFP_NOIO | __GFP_HIGHMEM |
1374 goto compress_again;
1378 alloced_pages = zs_get_total_pages(zram->mem_pool);
1379 update_used_max(zram, alloced_pages);
1381 if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1382 zcomp_stream_put(zram->comp);
1383 zs_free(zram->mem_pool, handle);
1387 dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1389 src = zstrm->buffer;
1390 if (comp_len == PAGE_SIZE)
1391 src = kmap_atomic(page);
1392 memcpy(dst, src, comp_len);
1393 if (comp_len == PAGE_SIZE)
1396 zcomp_stream_put(zram->comp);
1397 zs_unmap_object(zram->mem_pool, handle);
1398 atomic64_add(comp_len, &zram->stats.compr_data_size);
1401 * Free memory associated with this sector
1402 * before overwriting unused sectors.
1404 zram_slot_lock(zram, index);
1405 zram_free_page(zram, index);
1407 if (comp_len == PAGE_SIZE) {
1408 zram_set_flag(zram, index, ZRAM_HUGE);
1409 atomic64_inc(&zram->stats.huge_pages);
1413 zram_set_flag(zram, index, flags);
1414 zram_set_element(zram, index, element);
1416 zram_set_handle(zram, index, handle);
1417 zram_set_obj_size(zram, index, comp_len);
1419 zram_slot_unlock(zram, index);
1422 atomic64_inc(&zram->stats.pages_stored);
1426 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1427 u32 index, int offset, struct bio *bio)
1430 struct page *page = NULL;
1435 if (is_partial_io(bvec)) {
1438 * This is a partial IO. We need to read the full page
1439 * before to write the changes.
1441 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1445 ret = __zram_bvec_read(zram, page, index, bio, true);
1449 src = kmap_atomic(bvec->bv_page);
1450 dst = kmap_atomic(page);
1451 memcpy(dst + offset, src + bvec->bv_offset, bvec->bv_len);
1456 vec.bv_len = PAGE_SIZE;
1460 ret = __zram_bvec_write(zram, &vec, index, bio);
1462 if (is_partial_io(bvec))
1468 * zram_bio_discard - handler on discard request
1469 * @index: physical block index in PAGE_SIZE units
1470 * @offset: byte offset within physical block
1472 static void zram_bio_discard(struct zram *zram, u32 index,
1473 int offset, struct bio *bio)
1475 size_t n = bio->bi_iter.bi_size;
1478 * zram manages data in physical block size units. Because logical block
1479 * size isn't identical with physical block size on some arch, we
1480 * could get a discard request pointing to a specific offset within a
1481 * certain physical block. Although we can handle this request by
1482 * reading that physiclal block and decompressing and partially zeroing
1483 * and re-compressing and then re-storing it, this isn't reasonable
1484 * because our intent with a discard request is to save memory. So
1485 * skipping this logical block is appropriate here.
1488 if (n <= (PAGE_SIZE - offset))
1491 n -= (PAGE_SIZE - offset);
1495 while (n >= PAGE_SIZE) {
1496 zram_slot_lock(zram, index);
1497 zram_free_page(zram, index);
1498 zram_slot_unlock(zram, index);
1499 atomic64_inc(&zram->stats.notify_free);
1506 * Returns errno if it has some problem. Otherwise return 0 or 1.
1507 * Returns 0 if IO request was done synchronously
1508 * Returns 1 if IO request was successfully submitted.
1510 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
1511 int offset, unsigned int op, struct bio *bio)
1513 unsigned long start_time = jiffies;
1514 struct request_queue *q = zram->disk->queue;
1517 generic_start_io_acct(q, op, bvec->bv_len >> SECTOR_SHIFT,
1518 &zram->disk->part0);
1520 if (!op_is_write(op)) {
1521 atomic64_inc(&zram->stats.num_reads);
1522 ret = zram_bvec_read(zram, bvec, index, offset, bio);
1523 flush_dcache_page(bvec->bv_page);
1525 atomic64_inc(&zram->stats.num_writes);
1526 ret = zram_bvec_write(zram, bvec, index, offset, bio);
1529 generic_end_io_acct(q, op, &zram->disk->part0, start_time);
1531 zram_slot_lock(zram, index);
1532 zram_accessed(zram, index);
1533 zram_slot_unlock(zram, index);
1535 if (unlikely(ret < 0)) {
1536 if (!op_is_write(op))
1537 atomic64_inc(&zram->stats.failed_reads);
1539 atomic64_inc(&zram->stats.failed_writes);
1545 static void __zram_make_request(struct zram *zram, struct bio *bio)
1549 struct bio_vec bvec;
1550 struct bvec_iter iter;
1552 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1553 offset = (bio->bi_iter.bi_sector &
1554 (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1556 switch (bio_op(bio)) {
1557 case REQ_OP_DISCARD:
1558 case REQ_OP_WRITE_ZEROES:
1559 zram_bio_discard(zram, index, offset, bio);
1566 bio_for_each_segment(bvec, bio, iter) {
1567 struct bio_vec bv = bvec;
1568 unsigned int unwritten = bvec.bv_len;
1571 bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
1573 if (zram_bvec_rw(zram, &bv, index, offset,
1574 bio_op(bio), bio) < 0)
1577 bv.bv_offset += bv.bv_len;
1578 unwritten -= bv.bv_len;
1580 update_position(&index, &offset, &bv);
1581 } while (unwritten);
1592 * Handler function for all zram I/O requests.
1594 static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio)
1596 struct zram *zram = queue->queuedata;
1598 if (!valid_io_request(zram, bio->bi_iter.bi_sector,
1599 bio->bi_iter.bi_size)) {
1600 atomic64_inc(&zram->stats.invalid_io);
1604 __zram_make_request(zram, bio);
1605 return BLK_QC_T_NONE;
1609 return BLK_QC_T_NONE;
1612 static void zram_slot_free_notify(struct block_device *bdev,
1613 unsigned long index)
1617 zram = bdev->bd_disk->private_data;
1619 atomic64_inc(&zram->stats.notify_free);
1620 if (!zram_slot_trylock(zram, index)) {
1621 atomic64_inc(&zram->stats.miss_free);
1625 zram_free_page(zram, index);
1626 zram_slot_unlock(zram, index);
1629 static int zram_rw_page(struct block_device *bdev, sector_t sector,
1630 struct page *page, unsigned int op)
1637 if (PageTransHuge(page))
1639 zram = bdev->bd_disk->private_data;
1641 if (!valid_io_request(zram, sector, PAGE_SIZE)) {
1642 atomic64_inc(&zram->stats.invalid_io);
1647 index = sector >> SECTORS_PER_PAGE_SHIFT;
1648 offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1651 bv.bv_len = PAGE_SIZE;
1654 ret = zram_bvec_rw(zram, &bv, index, offset, op, NULL);
1657 * If I/O fails, just return error(ie, non-zero) without
1658 * calling page_endio.
1659 * It causes resubmit the I/O with bio request by upper functions
1660 * of rw_page(e.g., swap_readpage, __swap_writepage) and
1661 * bio->bi_end_io does things to handle the error
1662 * (e.g., SetPageError, set_page_dirty and extra works).
1664 if (unlikely(ret < 0))
1669 page_endio(page, op_is_write(op), 0);
1680 static void zram_reset_device(struct zram *zram)
1685 down_write(&zram->init_lock);
1687 zram->limit_pages = 0;
1689 if (!init_done(zram)) {
1690 up_write(&zram->init_lock);
1695 disksize = zram->disksize;
1698 set_capacity(zram->disk, 0);
1699 part_stat_set_all(&zram->disk->part0, 0);
1701 up_write(&zram->init_lock);
1702 /* I/O operation under all of CPU are done so let's free */
1703 zram_meta_free(zram, disksize);
1704 memset(&zram->stats, 0, sizeof(zram->stats));
1705 zcomp_destroy(comp);
1709 static ssize_t disksize_store(struct device *dev,
1710 struct device_attribute *attr, const char *buf, size_t len)
1714 struct zram *zram = dev_to_zram(dev);
1717 disksize = memparse(buf, NULL);
1721 down_write(&zram->init_lock);
1722 if (init_done(zram)) {
1723 pr_info("Cannot change disksize for initialized device\n");
1728 disksize = PAGE_ALIGN(disksize);
1729 if (!zram_meta_alloc(zram, disksize)) {
1734 comp = zcomp_create(zram->compressor);
1736 pr_err("Cannot initialise %s compressing backend\n",
1738 err = PTR_ERR(comp);
1743 zram->disksize = disksize;
1744 set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
1746 revalidate_disk(zram->disk);
1747 up_write(&zram->init_lock);
1752 zram_meta_free(zram, disksize);
1754 up_write(&zram->init_lock);
1758 static ssize_t reset_store(struct device *dev,
1759 struct device_attribute *attr, const char *buf, size_t len)
1762 unsigned short do_reset;
1764 struct block_device *bdev;
1766 ret = kstrtou16(buf, 10, &do_reset);
1773 zram = dev_to_zram(dev);
1774 bdev = bdget_disk(zram->disk, 0);
1778 mutex_lock(&bdev->bd_mutex);
1779 /* Do not reset an active device or claimed device */
1780 if (bdev->bd_openers || zram->claim) {
1781 mutex_unlock(&bdev->bd_mutex);
1786 /* From now on, anyone can't open /dev/zram[0-9] */
1788 mutex_unlock(&bdev->bd_mutex);
1790 /* Make sure all the pending I/O are finished */
1792 zram_reset_device(zram);
1793 revalidate_disk(zram->disk);
1796 mutex_lock(&bdev->bd_mutex);
1797 zram->claim = false;
1798 mutex_unlock(&bdev->bd_mutex);
1803 static int zram_open(struct block_device *bdev, fmode_t mode)
1808 WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
1810 zram = bdev->bd_disk->private_data;
1811 /* zram was claimed to reset so open request fails */
1818 static const struct block_device_operations zram_devops = {
1820 .swap_slot_free_notify = zram_slot_free_notify,
1821 .rw_page = zram_rw_page,
1822 .owner = THIS_MODULE
1825 static DEVICE_ATTR_WO(compact);
1826 static DEVICE_ATTR_RW(disksize);
1827 static DEVICE_ATTR_RO(initstate);
1828 static DEVICE_ATTR_WO(reset);
1829 static DEVICE_ATTR_WO(mem_limit);
1830 static DEVICE_ATTR_WO(mem_used_max);
1831 static DEVICE_ATTR_WO(idle);
1832 static DEVICE_ATTR_RW(max_comp_streams);
1833 static DEVICE_ATTR_RW(comp_algorithm);
1834 #ifdef CONFIG_ZRAM_WRITEBACK
1835 static DEVICE_ATTR_RW(backing_dev);
1836 static DEVICE_ATTR_WO(writeback);
1837 static DEVICE_ATTR_RW(writeback_limit);
1838 static DEVICE_ATTR_RW(writeback_limit_enable);
1841 static struct attribute *zram_disk_attrs[] = {
1842 &dev_attr_disksize.attr,
1843 &dev_attr_initstate.attr,
1844 &dev_attr_reset.attr,
1845 &dev_attr_compact.attr,
1846 &dev_attr_mem_limit.attr,
1847 &dev_attr_mem_used_max.attr,
1848 &dev_attr_idle.attr,
1849 &dev_attr_max_comp_streams.attr,
1850 &dev_attr_comp_algorithm.attr,
1851 #ifdef CONFIG_ZRAM_WRITEBACK
1852 &dev_attr_backing_dev.attr,
1853 &dev_attr_writeback.attr,
1854 &dev_attr_writeback_limit.attr,
1855 &dev_attr_writeback_limit_enable.attr,
1857 &dev_attr_io_stat.attr,
1858 &dev_attr_mm_stat.attr,
1859 #ifdef CONFIG_ZRAM_WRITEBACK
1860 &dev_attr_bd_stat.attr,
1862 &dev_attr_debug_stat.attr,
1866 static const struct attribute_group zram_disk_attr_group = {
1867 .attrs = zram_disk_attrs,
1870 static const struct attribute_group *zram_disk_attr_groups[] = {
1871 &zram_disk_attr_group,
1876 * Allocate and initialize new zram device. the function returns
1877 * '>= 0' device_id upon success, and negative value otherwise.
1879 static int zram_add(void)
1882 struct request_queue *queue;
1885 zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1889 ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1894 init_rwsem(&zram->init_lock);
1895 #ifdef CONFIG_ZRAM_WRITEBACK
1896 spin_lock_init(&zram->wb_limit_lock);
1898 queue = blk_alloc_queue(zram_make_request, NUMA_NO_NODE);
1900 pr_err("Error allocating disk queue for device %d\n",
1906 /* gendisk structure */
1907 zram->disk = alloc_disk(1);
1909 pr_err("Error allocating disk structure for device %d\n",
1912 goto out_free_queue;
1915 zram->disk->major = zram_major;
1916 zram->disk->first_minor = device_id;
1917 zram->disk->fops = &zram_devops;
1918 zram->disk->queue = queue;
1919 zram->disk->queue->queuedata = zram;
1920 zram->disk->private_data = zram;
1921 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1923 /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1924 set_capacity(zram->disk, 0);
1925 /* zram devices sort of resembles non-rotational disks */
1926 blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
1927 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1930 * To ensure that we always get PAGE_SIZE aligned
1931 * and n*PAGE_SIZED sized I/O requests.
1933 blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1934 blk_queue_logical_block_size(zram->disk->queue,
1935 ZRAM_LOGICAL_BLOCK_SIZE);
1936 blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1937 blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1938 zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1939 blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1940 blk_queue_flag_set(QUEUE_FLAG_DISCARD, zram->disk->queue);
1943 * zram_bio_discard() will clear all logical blocks if logical block
1944 * size is identical with physical block size(PAGE_SIZE). But if it is
1945 * different, we will skip discarding some parts of logical blocks in
1946 * the part of the request range which isn't aligned to physical block
1947 * size. So we can't ensure that all discarded logical blocks are
1950 if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1951 blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
1953 zram->disk->queue->backing_dev_info->capabilities |=
1954 (BDI_CAP_STABLE_WRITES | BDI_CAP_SYNCHRONOUS_IO);
1955 device_add_disk(NULL, zram->disk, zram_disk_attr_groups);
1957 strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1959 zram_debugfs_register(zram);
1960 pr_info("Added device: %s\n", zram->disk->disk_name);
1964 blk_cleanup_queue(queue);
1966 idr_remove(&zram_index_idr, device_id);
1972 static int zram_remove(struct zram *zram)
1974 struct block_device *bdev;
1976 bdev = bdget_disk(zram->disk, 0);
1980 mutex_lock(&bdev->bd_mutex);
1981 if (bdev->bd_openers || zram->claim) {
1982 mutex_unlock(&bdev->bd_mutex);
1988 mutex_unlock(&bdev->bd_mutex);
1990 zram_debugfs_unregister(zram);
1992 /* Make sure all the pending I/O are finished */
1994 zram_reset_device(zram);
1997 pr_info("Removed device: %s\n", zram->disk->disk_name);
1999 del_gendisk(zram->disk);
2000 blk_cleanup_queue(zram->disk->queue);
2001 put_disk(zram->disk);
2006 /* zram-control sysfs attributes */
2009 * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
2010 * sense that reading from this file does alter the state of your system -- it
2011 * creates a new un-initialized zram device and returns back this device's
2012 * device_id (or an error code if it fails to create a new device).
2014 static ssize_t hot_add_show(struct class *class,
2015 struct class_attribute *attr,
2020 mutex_lock(&zram_index_mutex);
2022 mutex_unlock(&zram_index_mutex);
2026 return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
2028 static CLASS_ATTR_RO(hot_add);
2030 static ssize_t hot_remove_store(struct class *class,
2031 struct class_attribute *attr,
2038 /* dev_id is gendisk->first_minor, which is `int' */
2039 ret = kstrtoint(buf, 10, &dev_id);
2045 mutex_lock(&zram_index_mutex);
2047 zram = idr_find(&zram_index_idr, dev_id);
2049 ret = zram_remove(zram);
2051 idr_remove(&zram_index_idr, dev_id);
2056 mutex_unlock(&zram_index_mutex);
2057 return ret ? ret : count;
2059 static CLASS_ATTR_WO(hot_remove);
2061 static struct attribute *zram_control_class_attrs[] = {
2062 &class_attr_hot_add.attr,
2063 &class_attr_hot_remove.attr,
2066 ATTRIBUTE_GROUPS(zram_control_class);
2068 static struct class zram_control_class = {
2069 .name = "zram-control",
2070 .owner = THIS_MODULE,
2071 .class_groups = zram_control_class_groups,
2074 static int zram_remove_cb(int id, void *ptr, void *data)
2080 static void destroy_devices(void)
2082 class_unregister(&zram_control_class);
2083 idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
2084 zram_debugfs_destroy();
2085 idr_destroy(&zram_index_idr);
2086 unregister_blkdev(zram_major, "zram");
2087 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2090 static int __init zram_init(void)
2094 ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
2095 zcomp_cpu_up_prepare, zcomp_cpu_dead);
2099 ret = class_register(&zram_control_class);
2101 pr_err("Unable to register zram-control class\n");
2102 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2106 zram_debugfs_create();
2107 zram_major = register_blkdev(0, "zram");
2108 if (zram_major <= 0) {
2109 pr_err("Unable to get major number\n");
2110 class_unregister(&zram_control_class);
2111 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2115 while (num_devices != 0) {
2116 mutex_lock(&zram_index_mutex);
2118 mutex_unlock(&zram_index_mutex);
2131 static void __exit zram_exit(void)
2136 module_init(zram_init);
2137 module_exit(zram_exit);
2139 module_param(num_devices, uint, 0);
2140 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
2142 MODULE_LICENSE("Dual BSD/GPL");
2143 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2144 MODULE_DESCRIPTION("Compressed RAM Block Device");