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/highmem.h>
26 #include <linux/slab.h>
27 #include <linux/backing-dev.h>
28 #include <linux/string.h>
29 #include <linux/vmalloc.h>
30 #include <linux/err.h>
31 #include <linux/idr.h>
32 #include <linux/sysfs.h>
33 #include <linux/debugfs.h>
34 #include <linux/cpuhotplug.h>
35 #include <linux/part_stat.h>
39 static DEFINE_IDR(zram_index_idr);
40 /* idr index must be protected */
41 static DEFINE_MUTEX(zram_index_mutex);
43 static int zram_major;
44 static const char *default_compressor = CONFIG_ZRAM_DEF_COMP;
46 /* Module params (documentation at end) */
47 static unsigned int num_devices = 1;
49 * Pages that compress to sizes equals or greater than this are stored
50 * uncompressed in memory.
52 static size_t huge_class_size;
54 static const struct block_device_operations zram_devops;
55 #ifdef CONFIG_ZRAM_WRITEBACK
56 static const struct block_device_operations zram_wb_devops;
59 static void zram_free_page(struct zram *zram, size_t index);
60 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
61 u32 index, int offset, struct bio *bio);
64 static int zram_slot_trylock(struct zram *zram, u32 index)
66 return bit_spin_trylock(ZRAM_LOCK, &zram->table[index].flags);
69 static void zram_slot_lock(struct zram *zram, u32 index)
71 bit_spin_lock(ZRAM_LOCK, &zram->table[index].flags);
74 static void zram_slot_unlock(struct zram *zram, u32 index)
76 bit_spin_unlock(ZRAM_LOCK, &zram->table[index].flags);
79 static inline bool init_done(struct zram *zram)
81 return zram->disksize;
84 static inline struct zram *dev_to_zram(struct device *dev)
86 return (struct zram *)dev_to_disk(dev)->private_data;
89 static unsigned long zram_get_handle(struct zram *zram, u32 index)
91 return zram->table[index].handle;
94 static void zram_set_handle(struct zram *zram, u32 index, unsigned long handle)
96 zram->table[index].handle = handle;
99 /* flag operations require table entry bit_spin_lock() being held */
100 static bool zram_test_flag(struct zram *zram, u32 index,
101 enum zram_pageflags flag)
103 return zram->table[index].flags & BIT(flag);
106 static void zram_set_flag(struct zram *zram, u32 index,
107 enum zram_pageflags flag)
109 zram->table[index].flags |= BIT(flag);
112 static void zram_clear_flag(struct zram *zram, u32 index,
113 enum zram_pageflags flag)
115 zram->table[index].flags &= ~BIT(flag);
118 static inline void zram_set_element(struct zram *zram, u32 index,
119 unsigned long element)
121 zram->table[index].element = element;
124 static unsigned long zram_get_element(struct zram *zram, u32 index)
126 return zram->table[index].element;
129 static size_t zram_get_obj_size(struct zram *zram, u32 index)
131 return zram->table[index].flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
134 static void zram_set_obj_size(struct zram *zram,
135 u32 index, size_t size)
137 unsigned long flags = zram->table[index].flags >> ZRAM_FLAG_SHIFT;
139 zram->table[index].flags = (flags << ZRAM_FLAG_SHIFT) | size;
142 static inline bool zram_allocated(struct zram *zram, u32 index)
144 return zram_get_obj_size(zram, index) ||
145 zram_test_flag(zram, index, ZRAM_SAME) ||
146 zram_test_flag(zram, index, ZRAM_WB);
149 #if PAGE_SIZE != 4096
150 static inline bool is_partial_io(struct bio_vec *bvec)
152 return bvec->bv_len != PAGE_SIZE;
155 static inline bool is_partial_io(struct bio_vec *bvec)
162 * Check if request is within bounds and aligned on zram logical blocks.
164 static inline bool valid_io_request(struct zram *zram,
165 sector_t start, unsigned int size)
169 /* unaligned request */
170 if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
172 if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
175 end = start + (size >> SECTOR_SHIFT);
176 bound = zram->disksize >> SECTOR_SHIFT;
177 /* out of range range */
178 if (unlikely(start >= bound || end > bound || start > end))
181 /* I/O request is valid */
185 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
187 *index += (*offset + bvec->bv_len) / PAGE_SIZE;
188 *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
191 static inline void update_used_max(struct zram *zram,
192 const unsigned long pages)
194 unsigned long old_max, cur_max;
196 old_max = atomic_long_read(&zram->stats.max_used_pages);
201 old_max = atomic_long_cmpxchg(
202 &zram->stats.max_used_pages, cur_max, pages);
203 } while (old_max != cur_max);
206 static inline void zram_fill_page(void *ptr, unsigned long len,
209 WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
210 memset_l(ptr, value, len / sizeof(unsigned long));
213 static bool page_same_filled(void *ptr, unsigned long *element)
217 unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
219 page = (unsigned long *)ptr;
222 if (val != page[last_pos])
225 for (pos = 1; pos < last_pos; pos++) {
226 if (val != page[pos])
235 static ssize_t initstate_show(struct device *dev,
236 struct device_attribute *attr, char *buf)
239 struct zram *zram = dev_to_zram(dev);
241 down_read(&zram->init_lock);
242 val = init_done(zram);
243 up_read(&zram->init_lock);
245 return scnprintf(buf, PAGE_SIZE, "%u\n", val);
248 static ssize_t disksize_show(struct device *dev,
249 struct device_attribute *attr, char *buf)
251 struct zram *zram = dev_to_zram(dev);
253 return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
256 static ssize_t mem_limit_store(struct device *dev,
257 struct device_attribute *attr, const char *buf, size_t len)
261 struct zram *zram = dev_to_zram(dev);
263 limit = memparse(buf, &tmp);
264 if (buf == tmp) /* no chars parsed, invalid input */
267 down_write(&zram->init_lock);
268 zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
269 up_write(&zram->init_lock);
274 static ssize_t mem_used_max_store(struct device *dev,
275 struct device_attribute *attr, const char *buf, size_t len)
279 struct zram *zram = dev_to_zram(dev);
281 err = kstrtoul(buf, 10, &val);
285 down_read(&zram->init_lock);
286 if (init_done(zram)) {
287 atomic_long_set(&zram->stats.max_used_pages,
288 zs_get_total_pages(zram->mem_pool));
290 up_read(&zram->init_lock);
296 * Mark all pages which are older than or equal to cutoff as IDLE.
297 * Callers should hold the zram init lock in read mode
299 static void mark_idle(struct zram *zram, ktime_t cutoff)
302 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
305 for (index = 0; index < nr_pages; index++) {
307 * Do not mark ZRAM_UNDER_WB slot as ZRAM_IDLE to close race.
308 * See the comment in writeback_store.
310 zram_slot_lock(zram, index);
311 if (zram_allocated(zram, index) &&
312 !zram_test_flag(zram, index, ZRAM_UNDER_WB)) {
313 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
314 is_idle = !cutoff || ktime_after(cutoff, zram->table[index].ac_time);
317 zram_set_flag(zram, index, ZRAM_IDLE);
319 zram_slot_unlock(zram, index);
323 static ssize_t idle_store(struct device *dev,
324 struct device_attribute *attr, const char *buf, size_t len)
326 struct zram *zram = dev_to_zram(dev);
327 ktime_t cutoff_time = 0;
328 ssize_t rv = -EINVAL;
330 if (!sysfs_streq(buf, "all")) {
332 * If it did not parse as 'all' try to treat it as an integer when
333 * we have memory tracking enabled.
337 if (IS_ENABLED(CONFIG_ZRAM_MEMORY_TRACKING) && !kstrtoull(buf, 0, &age_sec))
338 cutoff_time = ktime_sub(ktime_get_boottime(),
339 ns_to_ktime(age_sec * NSEC_PER_SEC));
344 down_read(&zram->init_lock);
345 if (!init_done(zram))
348 /* A cutoff_time of 0 marks everything as idle, this is the "all" behavior */
349 mark_idle(zram, cutoff_time);
353 up_read(&zram->init_lock);
358 #ifdef CONFIG_ZRAM_WRITEBACK
359 static ssize_t writeback_limit_enable_store(struct device *dev,
360 struct device_attribute *attr, const char *buf, size_t len)
362 struct zram *zram = dev_to_zram(dev);
364 ssize_t ret = -EINVAL;
366 if (kstrtoull(buf, 10, &val))
369 down_read(&zram->init_lock);
370 spin_lock(&zram->wb_limit_lock);
371 zram->wb_limit_enable = val;
372 spin_unlock(&zram->wb_limit_lock);
373 up_read(&zram->init_lock);
379 static ssize_t writeback_limit_enable_show(struct device *dev,
380 struct device_attribute *attr, char *buf)
383 struct zram *zram = dev_to_zram(dev);
385 down_read(&zram->init_lock);
386 spin_lock(&zram->wb_limit_lock);
387 val = zram->wb_limit_enable;
388 spin_unlock(&zram->wb_limit_lock);
389 up_read(&zram->init_lock);
391 return scnprintf(buf, PAGE_SIZE, "%d\n", val);
394 static ssize_t writeback_limit_store(struct device *dev,
395 struct device_attribute *attr, const char *buf, size_t len)
397 struct zram *zram = dev_to_zram(dev);
399 ssize_t ret = -EINVAL;
401 if (kstrtoull(buf, 10, &val))
404 down_read(&zram->init_lock);
405 spin_lock(&zram->wb_limit_lock);
406 zram->bd_wb_limit = val;
407 spin_unlock(&zram->wb_limit_lock);
408 up_read(&zram->init_lock);
414 static ssize_t writeback_limit_show(struct device *dev,
415 struct device_attribute *attr, char *buf)
418 struct zram *zram = dev_to_zram(dev);
420 down_read(&zram->init_lock);
421 spin_lock(&zram->wb_limit_lock);
422 val = zram->bd_wb_limit;
423 spin_unlock(&zram->wb_limit_lock);
424 up_read(&zram->init_lock);
426 return scnprintf(buf, PAGE_SIZE, "%llu\n", val);
429 static void reset_bdev(struct zram *zram)
431 struct block_device *bdev;
433 if (!zram->backing_dev)
437 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
438 /* hope filp_close flush all of IO */
439 filp_close(zram->backing_dev, NULL);
440 zram->backing_dev = NULL;
442 zram->disk->fops = &zram_devops;
443 kvfree(zram->bitmap);
447 static ssize_t backing_dev_show(struct device *dev,
448 struct device_attribute *attr, char *buf)
451 struct zram *zram = dev_to_zram(dev);
455 down_read(&zram->init_lock);
456 file = zram->backing_dev;
458 memcpy(buf, "none\n", 5);
459 up_read(&zram->init_lock);
463 p = file_path(file, buf, PAGE_SIZE - 1);
470 memmove(buf, p, ret);
473 up_read(&zram->init_lock);
477 static ssize_t backing_dev_store(struct device *dev,
478 struct device_attribute *attr, const char *buf, size_t len)
482 struct file *backing_dev = NULL;
484 struct address_space *mapping;
485 unsigned int bitmap_sz;
486 unsigned long nr_pages, *bitmap = NULL;
487 struct block_device *bdev = NULL;
489 struct zram *zram = dev_to_zram(dev);
491 file_name = kmalloc(PATH_MAX, GFP_KERNEL);
495 down_write(&zram->init_lock);
496 if (init_done(zram)) {
497 pr_info("Can't setup backing device for initialized device\n");
502 strlcpy(file_name, buf, PATH_MAX);
503 /* ignore trailing newline */
504 sz = strlen(file_name);
505 if (sz > 0 && file_name[sz - 1] == '\n')
506 file_name[sz - 1] = 0x00;
508 backing_dev = filp_open(file_name, O_RDWR|O_LARGEFILE, 0);
509 if (IS_ERR(backing_dev)) {
510 err = PTR_ERR(backing_dev);
515 mapping = backing_dev->f_mapping;
516 inode = mapping->host;
518 /* Support only block device in this moment */
519 if (!S_ISBLK(inode->i_mode)) {
524 bdev = blkdev_get_by_dev(inode->i_rdev,
525 FMODE_READ | FMODE_WRITE | FMODE_EXCL, zram);
532 nr_pages = i_size_read(inode) >> PAGE_SHIFT;
533 bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
534 bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
543 zram->backing_dev = backing_dev;
544 zram->bitmap = bitmap;
545 zram->nr_pages = nr_pages;
547 * With writeback feature, zram does asynchronous IO so it's no longer
548 * synchronous device so let's remove synchronous io flag. Othewise,
549 * upper layer(e.g., swap) could wait IO completion rather than
550 * (submit and return), which will cause system sluggish.
551 * Furthermore, when the IO function returns(e.g., swap_readpage),
552 * upper layer expects IO was done so it could deallocate the page
553 * freely but in fact, IO is going on so finally could cause
554 * use-after-free when the IO is really done.
556 zram->disk->fops = &zram_wb_devops;
557 up_write(&zram->init_lock);
559 pr_info("setup backing device %s\n", file_name);
567 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
570 filp_close(backing_dev, NULL);
572 up_write(&zram->init_lock);
579 static unsigned long alloc_block_bdev(struct zram *zram)
581 unsigned long blk_idx = 1;
583 /* skip 0 bit to confuse zram.handle = 0 */
584 blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, blk_idx);
585 if (blk_idx == zram->nr_pages)
588 if (test_and_set_bit(blk_idx, zram->bitmap))
591 atomic64_inc(&zram->stats.bd_count);
595 static void free_block_bdev(struct zram *zram, unsigned long blk_idx)
599 was_set = test_and_clear_bit(blk_idx, zram->bitmap);
600 WARN_ON_ONCE(!was_set);
601 atomic64_dec(&zram->stats.bd_count);
604 static void zram_page_end_io(struct bio *bio)
606 struct page *page = bio_first_page_all(bio);
608 page_endio(page, op_is_write(bio_op(bio)),
609 blk_status_to_errno(bio->bi_status));
614 * Returns 1 if the submission is successful.
616 static int read_from_bdev_async(struct zram *zram, struct bio_vec *bvec,
617 unsigned long entry, struct bio *parent)
621 bio = bio_alloc(zram->bdev, 1, parent ? parent->bi_opf : REQ_OP_READ,
626 bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
627 if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset)) {
633 bio->bi_end_io = zram_page_end_io;
635 bio_chain(bio, parent);
641 #define PAGE_WB_SIG "page_index="
643 #define PAGE_WRITEBACK 0
644 #define HUGE_WRITEBACK (1<<0)
645 #define IDLE_WRITEBACK (1<<1)
648 static ssize_t writeback_store(struct device *dev,
649 struct device_attribute *attr, const char *buf, size_t len)
651 struct zram *zram = dev_to_zram(dev);
652 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
653 unsigned long index = 0;
655 struct bio_vec bio_vec;
659 unsigned long blk_idx = 0;
661 if (sysfs_streq(buf, "idle"))
662 mode = IDLE_WRITEBACK;
663 else if (sysfs_streq(buf, "huge"))
664 mode = HUGE_WRITEBACK;
665 else if (sysfs_streq(buf, "huge_idle"))
666 mode = IDLE_WRITEBACK | HUGE_WRITEBACK;
668 if (strncmp(buf, PAGE_WB_SIG, sizeof(PAGE_WB_SIG) - 1))
671 if (kstrtol(buf + sizeof(PAGE_WB_SIG) - 1, 10, &index) ||
676 mode = PAGE_WRITEBACK;
679 down_read(&zram->init_lock);
680 if (!init_done(zram)) {
682 goto release_init_lock;
685 if (!zram->backing_dev) {
687 goto release_init_lock;
690 page = alloc_page(GFP_KERNEL);
693 goto release_init_lock;
696 for (; nr_pages != 0; index++, nr_pages--) {
700 bvec.bv_len = PAGE_SIZE;
703 spin_lock(&zram->wb_limit_lock);
704 if (zram->wb_limit_enable && !zram->bd_wb_limit) {
705 spin_unlock(&zram->wb_limit_lock);
709 spin_unlock(&zram->wb_limit_lock);
712 blk_idx = alloc_block_bdev(zram);
719 zram_slot_lock(zram, index);
720 if (!zram_allocated(zram, index))
723 if (zram_test_flag(zram, index, ZRAM_WB) ||
724 zram_test_flag(zram, index, ZRAM_SAME) ||
725 zram_test_flag(zram, index, ZRAM_UNDER_WB))
728 if (mode & IDLE_WRITEBACK &&
729 !zram_test_flag(zram, index, ZRAM_IDLE))
731 if (mode & HUGE_WRITEBACK &&
732 !zram_test_flag(zram, index, ZRAM_HUGE))
735 * Clearing ZRAM_UNDER_WB is duty of caller.
736 * IOW, zram_free_page never clear it.
738 zram_set_flag(zram, index, ZRAM_UNDER_WB);
739 /* Need for hugepage writeback racing */
740 zram_set_flag(zram, index, ZRAM_IDLE);
741 zram_slot_unlock(zram, index);
742 if (zram_bvec_read(zram, &bvec, index, 0, NULL)) {
743 zram_slot_lock(zram, index);
744 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
745 zram_clear_flag(zram, index, ZRAM_IDLE);
746 zram_slot_unlock(zram, index);
750 bio_init(&bio, zram->bdev, &bio_vec, 1,
751 REQ_OP_WRITE | REQ_SYNC);
752 bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
754 bio_add_page(&bio, bvec.bv_page, bvec.bv_len,
757 * XXX: A single page IO would be inefficient for write
758 * but it would be not bad as starter.
760 err = submit_bio_wait(&bio);
762 zram_slot_lock(zram, index);
763 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
764 zram_clear_flag(zram, index, ZRAM_IDLE);
765 zram_slot_unlock(zram, index);
767 * Return last IO error unless every IO were
774 atomic64_inc(&zram->stats.bd_writes);
776 * We released zram_slot_lock so need to check if the slot was
777 * changed. If there is freeing for the slot, we can catch it
778 * easily by zram_allocated.
779 * A subtle case is the slot is freed/reallocated/marked as
780 * ZRAM_IDLE again. To close the race, idle_store doesn't
781 * mark ZRAM_IDLE once it found the slot was ZRAM_UNDER_WB.
782 * Thus, we could close the race by checking ZRAM_IDLE bit.
784 zram_slot_lock(zram, index);
785 if (!zram_allocated(zram, index) ||
786 !zram_test_flag(zram, index, ZRAM_IDLE)) {
787 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
788 zram_clear_flag(zram, index, ZRAM_IDLE);
792 zram_free_page(zram, index);
793 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
794 zram_set_flag(zram, index, ZRAM_WB);
795 zram_set_element(zram, index, blk_idx);
797 atomic64_inc(&zram->stats.pages_stored);
798 spin_lock(&zram->wb_limit_lock);
799 if (zram->wb_limit_enable && zram->bd_wb_limit > 0)
800 zram->bd_wb_limit -= 1UL << (PAGE_SHIFT - 12);
801 spin_unlock(&zram->wb_limit_lock);
803 zram_slot_unlock(zram, index);
807 free_block_bdev(zram, blk_idx);
810 up_read(&zram->init_lock);
816 struct work_struct work;
823 #if PAGE_SIZE != 4096
824 static void zram_sync_read(struct work_struct *work)
826 struct zram_work *zw = container_of(work, struct zram_work, work);
827 struct zram *zram = zw->zram;
828 unsigned long entry = zw->entry;
829 struct bio *bio = zw->bio;
831 read_from_bdev_async(zram, &zw->bvec, entry, bio);
835 * Block layer want one ->submit_bio to be active at a time, so if we use
836 * chained IO with parent IO in same context, it's a deadlock. To avoid that,
837 * use a worker thread context.
839 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
840 unsigned long entry, struct bio *bio)
842 struct zram_work work;
849 INIT_WORK_ONSTACK(&work.work, zram_sync_read);
850 queue_work(system_unbound_wq, &work.work);
851 flush_work(&work.work);
852 destroy_work_on_stack(&work.work);
857 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
858 unsigned long entry, struct bio *bio)
865 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
866 unsigned long entry, struct bio *parent, bool sync)
868 atomic64_inc(&zram->stats.bd_reads);
870 return read_from_bdev_sync(zram, bvec, entry, parent);
872 return read_from_bdev_async(zram, bvec, entry, parent);
875 static inline void reset_bdev(struct zram *zram) {};
876 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
877 unsigned long entry, struct bio *parent, bool sync)
882 static void free_block_bdev(struct zram *zram, unsigned long blk_idx) {};
885 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
887 static struct dentry *zram_debugfs_root;
889 static void zram_debugfs_create(void)
891 zram_debugfs_root = debugfs_create_dir("zram", NULL);
894 static void zram_debugfs_destroy(void)
896 debugfs_remove_recursive(zram_debugfs_root);
899 static void zram_accessed(struct zram *zram, u32 index)
901 zram_clear_flag(zram, index, ZRAM_IDLE);
902 zram->table[index].ac_time = ktime_get_boottime();
905 static ssize_t read_block_state(struct file *file, char __user *buf,
906 size_t count, loff_t *ppos)
909 ssize_t index, written = 0;
910 struct zram *zram = file->private_data;
911 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
912 struct timespec64 ts;
914 kbuf = kvmalloc(count, GFP_KERNEL);
918 down_read(&zram->init_lock);
919 if (!init_done(zram)) {
920 up_read(&zram->init_lock);
925 for (index = *ppos; index < nr_pages; index++) {
928 zram_slot_lock(zram, index);
929 if (!zram_allocated(zram, index))
932 ts = ktime_to_timespec64(zram->table[index].ac_time);
933 copied = snprintf(kbuf + written, count,
934 "%12zd %12lld.%06lu %c%c%c%c\n",
935 index, (s64)ts.tv_sec,
936 ts.tv_nsec / NSEC_PER_USEC,
937 zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
938 zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
939 zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
940 zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.');
942 if (count <= copied) {
943 zram_slot_unlock(zram, index);
949 zram_slot_unlock(zram, index);
953 up_read(&zram->init_lock);
954 if (copy_to_user(buf, kbuf, written))
961 static const struct file_operations proc_zram_block_state_op = {
963 .read = read_block_state,
964 .llseek = default_llseek,
967 static void zram_debugfs_register(struct zram *zram)
969 if (!zram_debugfs_root)
972 zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
974 debugfs_create_file("block_state", 0400, zram->debugfs_dir,
975 zram, &proc_zram_block_state_op);
978 static void zram_debugfs_unregister(struct zram *zram)
980 debugfs_remove_recursive(zram->debugfs_dir);
983 static void zram_debugfs_create(void) {};
984 static void zram_debugfs_destroy(void) {};
985 static void zram_accessed(struct zram *zram, u32 index)
987 zram_clear_flag(zram, index, ZRAM_IDLE);
989 static void zram_debugfs_register(struct zram *zram) {};
990 static void zram_debugfs_unregister(struct zram *zram) {};
994 * We switched to per-cpu streams and this attr is not needed anymore.
995 * However, we will keep it around for some time, because:
996 * a) we may revert per-cpu streams in the future
997 * b) it's visible to user space and we need to follow our 2 years
998 * retirement rule; but we already have a number of 'soon to be
999 * altered' attrs, so max_comp_streams need to wait for the next
1002 static ssize_t max_comp_streams_show(struct device *dev,
1003 struct device_attribute *attr, char *buf)
1005 return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
1008 static ssize_t max_comp_streams_store(struct device *dev,
1009 struct device_attribute *attr, const char *buf, size_t len)
1014 static ssize_t comp_algorithm_show(struct device *dev,
1015 struct device_attribute *attr, char *buf)
1018 struct zram *zram = dev_to_zram(dev);
1020 down_read(&zram->init_lock);
1021 sz = zcomp_available_show(zram->compressor, buf);
1022 up_read(&zram->init_lock);
1027 static ssize_t comp_algorithm_store(struct device *dev,
1028 struct device_attribute *attr, const char *buf, size_t len)
1030 struct zram *zram = dev_to_zram(dev);
1031 char compressor[ARRAY_SIZE(zram->compressor)];
1034 strlcpy(compressor, buf, sizeof(compressor));
1035 /* ignore trailing newline */
1036 sz = strlen(compressor);
1037 if (sz > 0 && compressor[sz - 1] == '\n')
1038 compressor[sz - 1] = 0x00;
1040 if (!zcomp_available_algorithm(compressor))
1043 down_write(&zram->init_lock);
1044 if (init_done(zram)) {
1045 up_write(&zram->init_lock);
1046 pr_info("Can't change algorithm for initialized device\n");
1050 strcpy(zram->compressor, compressor);
1051 up_write(&zram->init_lock);
1055 static ssize_t compact_store(struct device *dev,
1056 struct device_attribute *attr, const char *buf, size_t len)
1058 struct zram *zram = dev_to_zram(dev);
1060 down_read(&zram->init_lock);
1061 if (!init_done(zram)) {
1062 up_read(&zram->init_lock);
1066 zs_compact(zram->mem_pool);
1067 up_read(&zram->init_lock);
1072 static ssize_t io_stat_show(struct device *dev,
1073 struct device_attribute *attr, char *buf)
1075 struct zram *zram = dev_to_zram(dev);
1078 down_read(&zram->init_lock);
1079 ret = scnprintf(buf, PAGE_SIZE,
1080 "%8llu %8llu %8llu %8llu\n",
1081 (u64)atomic64_read(&zram->stats.failed_reads),
1082 (u64)atomic64_read(&zram->stats.failed_writes),
1083 (u64)atomic64_read(&zram->stats.invalid_io),
1084 (u64)atomic64_read(&zram->stats.notify_free));
1085 up_read(&zram->init_lock);
1090 static ssize_t mm_stat_show(struct device *dev,
1091 struct device_attribute *attr, char *buf)
1093 struct zram *zram = dev_to_zram(dev);
1094 struct zs_pool_stats pool_stats;
1095 u64 orig_size, mem_used = 0;
1099 memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1101 down_read(&zram->init_lock);
1102 if (init_done(zram)) {
1103 mem_used = zs_get_total_pages(zram->mem_pool);
1104 zs_pool_stats(zram->mem_pool, &pool_stats);
1107 orig_size = atomic64_read(&zram->stats.pages_stored);
1108 max_used = atomic_long_read(&zram->stats.max_used_pages);
1110 ret = scnprintf(buf, PAGE_SIZE,
1111 "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu %8llu\n",
1112 orig_size << PAGE_SHIFT,
1113 (u64)atomic64_read(&zram->stats.compr_data_size),
1114 mem_used << PAGE_SHIFT,
1115 zram->limit_pages << PAGE_SHIFT,
1116 max_used << PAGE_SHIFT,
1117 (u64)atomic64_read(&zram->stats.same_pages),
1118 atomic_long_read(&pool_stats.pages_compacted),
1119 (u64)atomic64_read(&zram->stats.huge_pages),
1120 (u64)atomic64_read(&zram->stats.huge_pages_since));
1121 up_read(&zram->init_lock);
1126 #ifdef CONFIG_ZRAM_WRITEBACK
1127 #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
1128 static ssize_t bd_stat_show(struct device *dev,
1129 struct device_attribute *attr, char *buf)
1131 struct zram *zram = dev_to_zram(dev);
1134 down_read(&zram->init_lock);
1135 ret = scnprintf(buf, PAGE_SIZE,
1136 "%8llu %8llu %8llu\n",
1137 FOUR_K((u64)atomic64_read(&zram->stats.bd_count)),
1138 FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)),
1139 FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)));
1140 up_read(&zram->init_lock);
1146 static ssize_t debug_stat_show(struct device *dev,
1147 struct device_attribute *attr, char *buf)
1150 struct zram *zram = dev_to_zram(dev);
1153 down_read(&zram->init_lock);
1154 ret = scnprintf(buf, PAGE_SIZE,
1155 "version: %d\n%8llu\n",
1157 (u64)atomic64_read(&zram->stats.miss_free));
1158 up_read(&zram->init_lock);
1163 static DEVICE_ATTR_RO(io_stat);
1164 static DEVICE_ATTR_RO(mm_stat);
1165 #ifdef CONFIG_ZRAM_WRITEBACK
1166 static DEVICE_ATTR_RO(bd_stat);
1168 static DEVICE_ATTR_RO(debug_stat);
1170 static void zram_meta_free(struct zram *zram, u64 disksize)
1172 size_t num_pages = disksize >> PAGE_SHIFT;
1175 /* Free all pages that are still in this zram device */
1176 for (index = 0; index < num_pages; index++)
1177 zram_free_page(zram, index);
1179 zs_destroy_pool(zram->mem_pool);
1183 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
1187 num_pages = disksize >> PAGE_SHIFT;
1188 zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
1192 zram->mem_pool = zs_create_pool(zram->disk->disk_name);
1193 if (!zram->mem_pool) {
1198 if (!huge_class_size)
1199 huge_class_size = zs_huge_class_size(zram->mem_pool);
1204 * To protect concurrent access to the same index entry,
1205 * caller should hold this table index entry's bit_spinlock to
1206 * indicate this index entry is accessing.
1208 static void zram_free_page(struct zram *zram, size_t index)
1210 unsigned long handle;
1212 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
1213 zram->table[index].ac_time = 0;
1215 if (zram_test_flag(zram, index, ZRAM_IDLE))
1216 zram_clear_flag(zram, index, ZRAM_IDLE);
1218 if (zram_test_flag(zram, index, ZRAM_HUGE)) {
1219 zram_clear_flag(zram, index, ZRAM_HUGE);
1220 atomic64_dec(&zram->stats.huge_pages);
1223 if (zram_test_flag(zram, index, ZRAM_WB)) {
1224 zram_clear_flag(zram, index, ZRAM_WB);
1225 free_block_bdev(zram, zram_get_element(zram, index));
1230 * No memory is allocated for same element filled pages.
1231 * Simply clear same page flag.
1233 if (zram_test_flag(zram, index, ZRAM_SAME)) {
1234 zram_clear_flag(zram, index, ZRAM_SAME);
1235 atomic64_dec(&zram->stats.same_pages);
1239 handle = zram_get_handle(zram, index);
1243 zs_free(zram->mem_pool, handle);
1245 atomic64_sub(zram_get_obj_size(zram, index),
1246 &zram->stats.compr_data_size);
1248 atomic64_dec(&zram->stats.pages_stored);
1249 zram_set_handle(zram, index, 0);
1250 zram_set_obj_size(zram, index, 0);
1251 WARN_ON_ONCE(zram->table[index].flags &
1252 ~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB));
1255 static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index,
1256 struct bio *bio, bool partial_io)
1258 struct zcomp_strm *zstrm;
1259 unsigned long handle;
1264 zram_slot_lock(zram, index);
1265 if (zram_test_flag(zram, index, ZRAM_WB)) {
1266 struct bio_vec bvec;
1268 zram_slot_unlock(zram, index);
1270 bvec.bv_page = page;
1271 bvec.bv_len = PAGE_SIZE;
1273 return read_from_bdev(zram, &bvec,
1274 zram_get_element(zram, index),
1278 handle = zram_get_handle(zram, index);
1279 if (!handle || zram_test_flag(zram, index, ZRAM_SAME)) {
1280 unsigned long value;
1283 value = handle ? zram_get_element(zram, index) : 0;
1284 mem = kmap_atomic(page);
1285 zram_fill_page(mem, PAGE_SIZE, value);
1287 zram_slot_unlock(zram, index);
1291 size = zram_get_obj_size(zram, index);
1293 if (size != PAGE_SIZE)
1294 zstrm = zcomp_stream_get(zram->comp);
1296 src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
1297 if (size == PAGE_SIZE) {
1298 dst = kmap_atomic(page);
1299 memcpy(dst, src, PAGE_SIZE);
1303 dst = kmap_atomic(page);
1304 ret = zcomp_decompress(zstrm, src, size, dst);
1306 zcomp_stream_put(zram->comp);
1308 zs_unmap_object(zram->mem_pool, handle);
1309 zram_slot_unlock(zram, index);
1311 /* Should NEVER happen. Return bio error if it does. */
1313 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1318 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1319 u32 index, int offset, struct bio *bio)
1324 page = bvec->bv_page;
1325 if (is_partial_io(bvec)) {
1326 /* Use a temporary buffer to decompress the page */
1327 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1332 ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec));
1336 if (is_partial_io(bvec)) {
1337 void *src = kmap_atomic(page);
1339 memcpy_to_bvec(bvec, src + offset);
1343 if (is_partial_io(bvec))
1349 static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1350 u32 index, struct bio *bio)
1353 unsigned long alloced_pages;
1354 unsigned long handle = 0;
1355 unsigned int comp_len = 0;
1356 void *src, *dst, *mem;
1357 struct zcomp_strm *zstrm;
1358 struct page *page = bvec->bv_page;
1359 unsigned long element = 0;
1360 enum zram_pageflags flags = 0;
1362 mem = kmap_atomic(page);
1363 if (page_same_filled(mem, &element)) {
1365 /* Free memory associated with this sector now. */
1367 atomic64_inc(&zram->stats.same_pages);
1372 zstrm = zcomp_stream_get(zram->comp);
1373 src = kmap_atomic(page);
1374 ret = zcomp_compress(zstrm, src, &comp_len);
1377 if (unlikely(ret)) {
1378 zcomp_stream_put(zram->comp);
1379 pr_err("Compression failed! err=%d\n", ret);
1383 if (comp_len >= huge_class_size)
1384 comp_len = PAGE_SIZE;
1386 handle = zs_malloc(zram->mem_pool, comp_len,
1387 __GFP_KSWAPD_RECLAIM |
1392 if (IS_ERR((void *)handle)) {
1393 zcomp_stream_put(zram->comp);
1394 return PTR_ERR((void *)handle);
1397 alloced_pages = zs_get_total_pages(zram->mem_pool);
1398 update_used_max(zram, alloced_pages);
1400 if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1401 zcomp_stream_put(zram->comp);
1402 zs_free(zram->mem_pool, handle);
1406 dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1408 src = zstrm->buffer;
1409 if (comp_len == PAGE_SIZE)
1410 src = kmap_atomic(page);
1411 memcpy(dst, src, comp_len);
1412 if (comp_len == PAGE_SIZE)
1415 zcomp_stream_put(zram->comp);
1416 zs_unmap_object(zram->mem_pool, handle);
1417 atomic64_add(comp_len, &zram->stats.compr_data_size);
1420 * Free memory associated with this sector
1421 * before overwriting unused sectors.
1423 zram_slot_lock(zram, index);
1424 zram_free_page(zram, index);
1426 if (comp_len == PAGE_SIZE) {
1427 zram_set_flag(zram, index, ZRAM_HUGE);
1428 atomic64_inc(&zram->stats.huge_pages);
1429 atomic64_inc(&zram->stats.huge_pages_since);
1433 zram_set_flag(zram, index, flags);
1434 zram_set_element(zram, index, element);
1436 zram_set_handle(zram, index, handle);
1437 zram_set_obj_size(zram, index, comp_len);
1439 zram_slot_unlock(zram, index);
1442 atomic64_inc(&zram->stats.pages_stored);
1446 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1447 u32 index, int offset, struct bio *bio)
1450 struct page *page = NULL;
1454 if (is_partial_io(bvec)) {
1457 * This is a partial IO. We need to read the full page
1458 * before to write the changes.
1460 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1464 ret = __zram_bvec_read(zram, page, index, bio, true);
1468 dst = kmap_atomic(page);
1469 memcpy_from_bvec(dst + offset, bvec);
1473 vec.bv_len = PAGE_SIZE;
1477 ret = __zram_bvec_write(zram, &vec, index, bio);
1479 if (is_partial_io(bvec))
1485 * zram_bio_discard - handler on discard request
1486 * @index: physical block index in PAGE_SIZE units
1487 * @offset: byte offset within physical block
1489 static void zram_bio_discard(struct zram *zram, u32 index,
1490 int offset, struct bio *bio)
1492 size_t n = bio->bi_iter.bi_size;
1495 * zram manages data in physical block size units. Because logical block
1496 * size isn't identical with physical block size on some arch, we
1497 * could get a discard request pointing to a specific offset within a
1498 * certain physical block. Although we can handle this request by
1499 * reading that physiclal block and decompressing and partially zeroing
1500 * and re-compressing and then re-storing it, this isn't reasonable
1501 * because our intent with a discard request is to save memory. So
1502 * skipping this logical block is appropriate here.
1505 if (n <= (PAGE_SIZE - offset))
1508 n -= (PAGE_SIZE - offset);
1512 while (n >= PAGE_SIZE) {
1513 zram_slot_lock(zram, index);
1514 zram_free_page(zram, index);
1515 zram_slot_unlock(zram, index);
1516 atomic64_inc(&zram->stats.notify_free);
1523 * Returns errno if it has some problem. Otherwise return 0 or 1.
1524 * Returns 0 if IO request was done synchronously
1525 * Returns 1 if IO request was successfully submitted.
1527 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
1528 int offset, enum req_op op, struct bio *bio)
1532 if (!op_is_write(op)) {
1533 atomic64_inc(&zram->stats.num_reads);
1534 ret = zram_bvec_read(zram, bvec, index, offset, bio);
1535 flush_dcache_page(bvec->bv_page);
1537 atomic64_inc(&zram->stats.num_writes);
1538 ret = zram_bvec_write(zram, bvec, index, offset, bio);
1541 zram_slot_lock(zram, index);
1542 zram_accessed(zram, index);
1543 zram_slot_unlock(zram, index);
1545 if (unlikely(ret < 0)) {
1546 if (!op_is_write(op))
1547 atomic64_inc(&zram->stats.failed_reads);
1549 atomic64_inc(&zram->stats.failed_writes);
1555 static void __zram_make_request(struct zram *zram, struct bio *bio)
1559 struct bio_vec bvec;
1560 struct bvec_iter iter;
1561 unsigned long start_time;
1563 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1564 offset = (bio->bi_iter.bi_sector &
1565 (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1567 switch (bio_op(bio)) {
1568 case REQ_OP_DISCARD:
1569 case REQ_OP_WRITE_ZEROES:
1570 zram_bio_discard(zram, index, offset, bio);
1577 start_time = bio_start_io_acct(bio);
1578 bio_for_each_segment(bvec, bio, iter) {
1579 struct bio_vec bv = bvec;
1580 unsigned int unwritten = bvec.bv_len;
1583 bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
1585 if (zram_bvec_rw(zram, &bv, index, offset,
1586 bio_op(bio), bio) < 0) {
1587 bio->bi_status = BLK_STS_IOERR;
1591 bv.bv_offset += bv.bv_len;
1592 unwritten -= bv.bv_len;
1594 update_position(&index, &offset, &bv);
1595 } while (unwritten);
1597 bio_end_io_acct(bio, start_time);
1602 * Handler function for all zram I/O requests.
1604 static void zram_submit_bio(struct bio *bio)
1606 struct zram *zram = bio->bi_bdev->bd_disk->private_data;
1608 if (!valid_io_request(zram, bio->bi_iter.bi_sector,
1609 bio->bi_iter.bi_size)) {
1610 atomic64_inc(&zram->stats.invalid_io);
1615 __zram_make_request(zram, bio);
1618 static void zram_slot_free_notify(struct block_device *bdev,
1619 unsigned long index)
1623 zram = bdev->bd_disk->private_data;
1625 atomic64_inc(&zram->stats.notify_free);
1626 if (!zram_slot_trylock(zram, index)) {
1627 atomic64_inc(&zram->stats.miss_free);
1631 zram_free_page(zram, index);
1632 zram_slot_unlock(zram, index);
1635 static int zram_rw_page(struct block_device *bdev, sector_t sector,
1636 struct page *page, enum req_op op)
1642 unsigned long start_time;
1644 if (PageTransHuge(page))
1646 zram = bdev->bd_disk->private_data;
1648 if (!valid_io_request(zram, sector, PAGE_SIZE)) {
1649 atomic64_inc(&zram->stats.invalid_io);
1654 index = sector >> SECTORS_PER_PAGE_SHIFT;
1655 offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1658 bv.bv_len = PAGE_SIZE;
1661 start_time = bdev_start_io_acct(bdev->bd_disk->part0,
1662 SECTORS_PER_PAGE, op, jiffies);
1663 ret = zram_bvec_rw(zram, &bv, index, offset, op, NULL);
1664 bdev_end_io_acct(bdev->bd_disk->part0, op, start_time);
1667 * If I/O fails, just return error(ie, non-zero) without
1668 * calling page_endio.
1669 * It causes resubmit the I/O with bio request by upper functions
1670 * of rw_page(e.g., swap_readpage, __swap_writepage) and
1671 * bio->bi_end_io does things to handle the error
1672 * (e.g., SetPageError, set_page_dirty and extra works).
1674 if (unlikely(ret < 0))
1679 page_endio(page, op_is_write(op), 0);
1690 static void zram_reset_device(struct zram *zram)
1695 down_write(&zram->init_lock);
1697 zram->limit_pages = 0;
1699 if (!init_done(zram)) {
1700 up_write(&zram->init_lock);
1705 disksize = zram->disksize;
1708 set_capacity_and_notify(zram->disk, 0);
1709 part_stat_set_all(zram->disk->part0, 0);
1711 /* I/O operation under all of CPU are done so let's free */
1712 zram_meta_free(zram, disksize);
1713 memset(&zram->stats, 0, sizeof(zram->stats));
1714 zcomp_destroy(comp);
1717 up_write(&zram->init_lock);
1720 static ssize_t disksize_store(struct device *dev,
1721 struct device_attribute *attr, const char *buf, size_t len)
1725 struct zram *zram = dev_to_zram(dev);
1728 disksize = memparse(buf, NULL);
1732 down_write(&zram->init_lock);
1733 if (init_done(zram)) {
1734 pr_info("Cannot change disksize for initialized device\n");
1739 disksize = PAGE_ALIGN(disksize);
1740 if (!zram_meta_alloc(zram, disksize)) {
1745 comp = zcomp_create(zram->compressor);
1747 pr_err("Cannot initialise %s compressing backend\n",
1749 err = PTR_ERR(comp);
1754 zram->disksize = disksize;
1755 set_capacity_and_notify(zram->disk, zram->disksize >> SECTOR_SHIFT);
1756 up_write(&zram->init_lock);
1761 zram_meta_free(zram, disksize);
1763 up_write(&zram->init_lock);
1767 static ssize_t reset_store(struct device *dev,
1768 struct device_attribute *attr, const char *buf, size_t len)
1771 unsigned short do_reset;
1773 struct gendisk *disk;
1775 ret = kstrtou16(buf, 10, &do_reset);
1782 zram = dev_to_zram(dev);
1785 mutex_lock(&disk->open_mutex);
1786 /* Do not reset an active device or claimed device */
1787 if (disk_openers(disk) || zram->claim) {
1788 mutex_unlock(&disk->open_mutex);
1792 /* From now on, anyone can't open /dev/zram[0-9] */
1794 mutex_unlock(&disk->open_mutex);
1796 /* Make sure all the pending I/O are finished */
1797 sync_blockdev(disk->part0);
1798 zram_reset_device(zram);
1800 mutex_lock(&disk->open_mutex);
1801 zram->claim = false;
1802 mutex_unlock(&disk->open_mutex);
1807 static int zram_open(struct block_device *bdev, fmode_t mode)
1812 WARN_ON(!mutex_is_locked(&bdev->bd_disk->open_mutex));
1814 zram = bdev->bd_disk->private_data;
1815 /* zram was claimed to reset so open request fails */
1822 static const struct block_device_operations zram_devops = {
1824 .submit_bio = zram_submit_bio,
1825 .swap_slot_free_notify = zram_slot_free_notify,
1826 .rw_page = zram_rw_page,
1827 .owner = THIS_MODULE
1830 #ifdef CONFIG_ZRAM_WRITEBACK
1831 static const struct block_device_operations zram_wb_devops = {
1833 .submit_bio = zram_submit_bio,
1834 .swap_slot_free_notify = zram_slot_free_notify,
1835 .owner = THIS_MODULE
1839 static DEVICE_ATTR_WO(compact);
1840 static DEVICE_ATTR_RW(disksize);
1841 static DEVICE_ATTR_RO(initstate);
1842 static DEVICE_ATTR_WO(reset);
1843 static DEVICE_ATTR_WO(mem_limit);
1844 static DEVICE_ATTR_WO(mem_used_max);
1845 static DEVICE_ATTR_WO(idle);
1846 static DEVICE_ATTR_RW(max_comp_streams);
1847 static DEVICE_ATTR_RW(comp_algorithm);
1848 #ifdef CONFIG_ZRAM_WRITEBACK
1849 static DEVICE_ATTR_RW(backing_dev);
1850 static DEVICE_ATTR_WO(writeback);
1851 static DEVICE_ATTR_RW(writeback_limit);
1852 static DEVICE_ATTR_RW(writeback_limit_enable);
1855 static struct attribute *zram_disk_attrs[] = {
1856 &dev_attr_disksize.attr,
1857 &dev_attr_initstate.attr,
1858 &dev_attr_reset.attr,
1859 &dev_attr_compact.attr,
1860 &dev_attr_mem_limit.attr,
1861 &dev_attr_mem_used_max.attr,
1862 &dev_attr_idle.attr,
1863 &dev_attr_max_comp_streams.attr,
1864 &dev_attr_comp_algorithm.attr,
1865 #ifdef CONFIG_ZRAM_WRITEBACK
1866 &dev_attr_backing_dev.attr,
1867 &dev_attr_writeback.attr,
1868 &dev_attr_writeback_limit.attr,
1869 &dev_attr_writeback_limit_enable.attr,
1871 &dev_attr_io_stat.attr,
1872 &dev_attr_mm_stat.attr,
1873 #ifdef CONFIG_ZRAM_WRITEBACK
1874 &dev_attr_bd_stat.attr,
1876 &dev_attr_debug_stat.attr,
1880 ATTRIBUTE_GROUPS(zram_disk);
1883 * Allocate and initialize new zram device. the function returns
1884 * '>= 0' device_id upon success, and negative value otherwise.
1886 static int zram_add(void)
1891 zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1895 ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1900 init_rwsem(&zram->init_lock);
1901 #ifdef CONFIG_ZRAM_WRITEBACK
1902 spin_lock_init(&zram->wb_limit_lock);
1905 /* gendisk structure */
1906 zram->disk = blk_alloc_disk(NUMA_NO_NODE);
1908 pr_err("Error allocating disk structure for device %d\n",
1914 zram->disk->major = zram_major;
1915 zram->disk->first_minor = device_id;
1916 zram->disk->minors = 1;
1917 zram->disk->flags |= GENHD_FL_NO_PART;
1918 zram->disk->fops = &zram_devops;
1919 zram->disk->private_data = zram;
1920 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1922 /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1923 set_capacity(zram->disk, 0);
1924 /* zram devices sort of resembles non-rotational disks */
1925 blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
1926 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1929 * To ensure that we always get PAGE_SIZE aligned
1930 * and n*PAGE_SIZED sized I/O requests.
1932 blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1933 blk_queue_logical_block_size(zram->disk->queue,
1934 ZRAM_LOGICAL_BLOCK_SIZE);
1935 blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1936 blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1937 zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1938 blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1941 * zram_bio_discard() will clear all logical blocks if logical block
1942 * size is identical with physical block size(PAGE_SIZE). But if it is
1943 * different, we will skip discarding some parts of logical blocks in
1944 * the part of the request range which isn't aligned to physical block
1945 * size. So we can't ensure that all discarded logical blocks are
1948 if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1949 blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
1951 ret = device_add_disk(NULL, zram->disk, zram_disk_groups);
1953 goto out_cleanup_disk;
1955 strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1957 zram_debugfs_register(zram);
1958 pr_info("Added device: %s\n", zram->disk->disk_name);
1962 put_disk(zram->disk);
1964 idr_remove(&zram_index_idr, device_id);
1970 static int zram_remove(struct zram *zram)
1974 mutex_lock(&zram->disk->open_mutex);
1975 if (disk_openers(zram->disk)) {
1976 mutex_unlock(&zram->disk->open_mutex);
1980 claimed = zram->claim;
1983 mutex_unlock(&zram->disk->open_mutex);
1985 zram_debugfs_unregister(zram);
1989 * If we were claimed by reset_store(), del_gendisk() will
1990 * wait until reset_store() is done, so nothing need to do.
1994 /* Make sure all the pending I/O are finished */
1995 sync_blockdev(zram->disk->part0);
1996 zram_reset_device(zram);
1999 pr_info("Removed device: %s\n", zram->disk->disk_name);
2001 del_gendisk(zram->disk);
2003 /* del_gendisk drains pending reset_store */
2004 WARN_ON_ONCE(claimed && zram->claim);
2007 * disksize_store() may be called in between zram_reset_device()
2008 * and del_gendisk(), so run the last reset to avoid leaking
2009 * anything allocated with disksize_store()
2011 zram_reset_device(zram);
2013 put_disk(zram->disk);
2018 /* zram-control sysfs attributes */
2021 * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
2022 * sense that reading from this file does alter the state of your system -- it
2023 * creates a new un-initialized zram device and returns back this device's
2024 * device_id (or an error code if it fails to create a new device).
2026 static ssize_t hot_add_show(struct class *class,
2027 struct class_attribute *attr,
2032 mutex_lock(&zram_index_mutex);
2034 mutex_unlock(&zram_index_mutex);
2038 return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
2040 static struct class_attribute class_attr_hot_add =
2041 __ATTR(hot_add, 0400, hot_add_show, NULL);
2043 static ssize_t hot_remove_store(struct class *class,
2044 struct class_attribute *attr,
2051 /* dev_id is gendisk->first_minor, which is `int' */
2052 ret = kstrtoint(buf, 10, &dev_id);
2058 mutex_lock(&zram_index_mutex);
2060 zram = idr_find(&zram_index_idr, dev_id);
2062 ret = zram_remove(zram);
2064 idr_remove(&zram_index_idr, dev_id);
2069 mutex_unlock(&zram_index_mutex);
2070 return ret ? ret : count;
2072 static CLASS_ATTR_WO(hot_remove);
2074 static struct attribute *zram_control_class_attrs[] = {
2075 &class_attr_hot_add.attr,
2076 &class_attr_hot_remove.attr,
2079 ATTRIBUTE_GROUPS(zram_control_class);
2081 static struct class zram_control_class = {
2082 .name = "zram-control",
2083 .owner = THIS_MODULE,
2084 .class_groups = zram_control_class_groups,
2087 static int zram_remove_cb(int id, void *ptr, void *data)
2089 WARN_ON_ONCE(zram_remove(ptr));
2093 static void destroy_devices(void)
2095 class_unregister(&zram_control_class);
2096 idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
2097 zram_debugfs_destroy();
2098 idr_destroy(&zram_index_idr);
2099 unregister_blkdev(zram_major, "zram");
2100 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2103 static int __init zram_init(void)
2107 ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
2108 zcomp_cpu_up_prepare, zcomp_cpu_dead);
2112 ret = class_register(&zram_control_class);
2114 pr_err("Unable to register zram-control class\n");
2115 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2119 zram_debugfs_create();
2120 zram_major = register_blkdev(0, "zram");
2121 if (zram_major <= 0) {
2122 pr_err("Unable to get major number\n");
2123 class_unregister(&zram_control_class);
2124 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2128 while (num_devices != 0) {
2129 mutex_lock(&zram_index_mutex);
2131 mutex_unlock(&zram_index_mutex);
2144 static void __exit zram_exit(void)
2149 module_init(zram_init);
2150 module_exit(zram_exit);
2152 module_param(num_devices, uint, 0);
2153 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
2155 MODULE_LICENSE("Dual BSD/GPL");
2156 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2157 MODULE_DESCRIPTION("Compressed RAM Block Device");