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>
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 = "lzo";
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 void zram_free_page(struct zram *zram, size_t index);
55 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
56 u32 index, int offset, struct bio *bio);
59 static int zram_slot_trylock(struct zram *zram, u32 index)
61 return bit_spin_trylock(ZRAM_LOCK, &zram->table[index].flags);
64 static void zram_slot_lock(struct zram *zram, u32 index)
66 bit_spin_lock(ZRAM_LOCK, &zram->table[index].flags);
69 static void zram_slot_unlock(struct zram *zram, u32 index)
71 bit_spin_unlock(ZRAM_LOCK, &zram->table[index].flags);
74 static inline bool init_done(struct zram *zram)
76 return zram->disksize;
79 static inline struct zram *dev_to_zram(struct device *dev)
81 return (struct zram *)dev_to_disk(dev)->private_data;
84 static unsigned long zram_get_handle(struct zram *zram, u32 index)
86 return zram->table[index].handle;
89 static void zram_set_handle(struct zram *zram, u32 index, unsigned long handle)
91 zram->table[index].handle = handle;
94 /* flag operations require table entry bit_spin_lock() being held */
95 static bool zram_test_flag(struct zram *zram, u32 index,
96 enum zram_pageflags flag)
98 return zram->table[index].flags & BIT(flag);
101 static void zram_set_flag(struct zram *zram, u32 index,
102 enum zram_pageflags flag)
104 zram->table[index].flags |= BIT(flag);
107 static void zram_clear_flag(struct zram *zram, u32 index,
108 enum zram_pageflags flag)
110 zram->table[index].flags &= ~BIT(flag);
113 static inline void zram_set_element(struct zram *zram, u32 index,
114 unsigned long element)
116 zram->table[index].element = element;
119 static unsigned long zram_get_element(struct zram *zram, u32 index)
121 return zram->table[index].element;
124 static size_t zram_get_obj_size(struct zram *zram, u32 index)
126 return zram->table[index].flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
129 static void zram_set_obj_size(struct zram *zram,
130 u32 index, size_t size)
132 unsigned long flags = zram->table[index].flags >> ZRAM_FLAG_SHIFT;
134 zram->table[index].flags = (flags << ZRAM_FLAG_SHIFT) | size;
137 static inline bool zram_allocated(struct zram *zram, u32 index)
139 return zram_get_obj_size(zram, index) ||
140 zram_test_flag(zram, index, ZRAM_SAME) ||
141 zram_test_flag(zram, index, ZRAM_WB);
144 #if PAGE_SIZE != 4096
145 static inline bool is_partial_io(struct bio_vec *bvec)
147 return bvec->bv_len != PAGE_SIZE;
150 static inline bool is_partial_io(struct bio_vec *bvec)
157 * Check if request is within bounds and aligned on zram logical blocks.
159 static inline bool valid_io_request(struct zram *zram,
160 sector_t start, unsigned int size)
164 /* unaligned request */
165 if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
167 if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
170 end = start + (size >> SECTOR_SHIFT);
171 bound = zram->disksize >> SECTOR_SHIFT;
172 /* out of range range */
173 if (unlikely(start >= bound || end > bound || start > end))
176 /* I/O request is valid */
180 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
182 *index += (*offset + bvec->bv_len) / PAGE_SIZE;
183 *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
186 static inline void update_used_max(struct zram *zram,
187 const unsigned long pages)
189 unsigned long old_max, cur_max;
191 old_max = atomic_long_read(&zram->stats.max_used_pages);
196 old_max = atomic_long_cmpxchg(
197 &zram->stats.max_used_pages, cur_max, pages);
198 } while (old_max != cur_max);
201 static inline void zram_fill_page(void *ptr, unsigned long len,
204 WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
205 memset_l(ptr, value, len / sizeof(unsigned long));
208 static bool page_same_filled(void *ptr, unsigned long *element)
214 page = (unsigned long *)ptr;
217 for (pos = 1; pos < PAGE_SIZE / sizeof(*page); pos++) {
218 if (val != page[pos])
227 static ssize_t initstate_show(struct device *dev,
228 struct device_attribute *attr, char *buf)
231 struct zram *zram = dev_to_zram(dev);
233 down_read(&zram->init_lock);
234 val = init_done(zram);
235 up_read(&zram->init_lock);
237 return scnprintf(buf, PAGE_SIZE, "%u\n", val);
240 static ssize_t disksize_show(struct device *dev,
241 struct device_attribute *attr, char *buf)
243 struct zram *zram = dev_to_zram(dev);
245 return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
248 static ssize_t mem_limit_store(struct device *dev,
249 struct device_attribute *attr, const char *buf, size_t len)
253 struct zram *zram = dev_to_zram(dev);
255 limit = memparse(buf, &tmp);
256 if (buf == tmp) /* no chars parsed, invalid input */
259 down_write(&zram->init_lock);
260 zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
261 up_write(&zram->init_lock);
266 static ssize_t mem_used_max_store(struct device *dev,
267 struct device_attribute *attr, const char *buf, size_t len)
271 struct zram *zram = dev_to_zram(dev);
273 err = kstrtoul(buf, 10, &val);
277 down_read(&zram->init_lock);
278 if (init_done(zram)) {
279 atomic_long_set(&zram->stats.max_used_pages,
280 zs_get_total_pages(zram->mem_pool));
282 up_read(&zram->init_lock);
287 static ssize_t idle_store(struct device *dev,
288 struct device_attribute *attr, const char *buf, size_t len)
290 struct zram *zram = dev_to_zram(dev);
291 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
296 sz = strscpy(mode_buf, buf, sizeof(mode_buf));
300 /* ignore trailing new line */
301 if (mode_buf[sz - 1] == '\n')
302 mode_buf[sz - 1] = 0x00;
304 if (strcmp(mode_buf, "all"))
307 down_read(&zram->init_lock);
308 if (!init_done(zram)) {
309 up_read(&zram->init_lock);
313 for (index = 0; index < nr_pages; index++) {
315 * Do not mark ZRAM_UNDER_WB slot as ZRAM_IDLE to close race.
316 * See the comment in writeback_store.
318 zram_slot_lock(zram, index);
319 if (!zram_allocated(zram, index) ||
320 zram_test_flag(zram, index, ZRAM_UNDER_WB))
322 zram_set_flag(zram, index, ZRAM_IDLE);
324 zram_slot_unlock(zram, index);
327 up_read(&zram->init_lock);
332 #ifdef CONFIG_ZRAM_WRITEBACK
333 static ssize_t writeback_limit_store(struct device *dev,
334 struct device_attribute *attr, const char *buf, size_t len)
336 struct zram *zram = dev_to_zram(dev);
338 ssize_t ret = -EINVAL;
340 if (kstrtoull(buf, 10, &val))
343 down_read(&zram->init_lock);
344 atomic64_set(&zram->stats.bd_wb_limit, val);
346 zram->stop_writeback = false;
347 up_read(&zram->init_lock);
353 static ssize_t writeback_limit_show(struct device *dev,
354 struct device_attribute *attr, char *buf)
357 struct zram *zram = dev_to_zram(dev);
359 down_read(&zram->init_lock);
360 val = atomic64_read(&zram->stats.bd_wb_limit);
361 up_read(&zram->init_lock);
363 return scnprintf(buf, PAGE_SIZE, "%llu\n", val);
366 static void reset_bdev(struct zram *zram)
368 struct block_device *bdev;
370 if (!zram->backing_dev)
374 if (zram->old_block_size)
375 set_blocksize(bdev, zram->old_block_size);
376 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
377 /* hope filp_close flush all of IO */
378 filp_close(zram->backing_dev, NULL);
379 zram->backing_dev = NULL;
380 zram->old_block_size = 0;
382 zram->disk->queue->backing_dev_info->capabilities |=
383 BDI_CAP_SYNCHRONOUS_IO;
384 kvfree(zram->bitmap);
388 static ssize_t backing_dev_show(struct device *dev,
389 struct device_attribute *attr, char *buf)
391 struct zram *zram = dev_to_zram(dev);
392 struct file *file = zram->backing_dev;
396 down_read(&zram->init_lock);
397 if (!zram->backing_dev) {
398 memcpy(buf, "none\n", 5);
399 up_read(&zram->init_lock);
403 p = file_path(file, buf, PAGE_SIZE - 1);
410 memmove(buf, p, ret);
413 up_read(&zram->init_lock);
417 static ssize_t backing_dev_store(struct device *dev,
418 struct device_attribute *attr, const char *buf, size_t len)
422 struct file *backing_dev = NULL;
424 struct address_space *mapping;
425 unsigned int bitmap_sz, old_block_size = 0;
426 unsigned long nr_pages, *bitmap = NULL;
427 struct block_device *bdev = NULL;
429 struct zram *zram = dev_to_zram(dev);
431 file_name = kmalloc(PATH_MAX, GFP_KERNEL);
435 down_write(&zram->init_lock);
436 if (init_done(zram)) {
437 pr_info("Can't setup backing device for initialized device\n");
442 strlcpy(file_name, buf, PATH_MAX);
443 /* ignore trailing newline */
444 sz = strlen(file_name);
445 if (sz > 0 && file_name[sz - 1] == '\n')
446 file_name[sz - 1] = 0x00;
448 backing_dev = filp_open(file_name, O_RDWR|O_LARGEFILE, 0);
449 if (IS_ERR(backing_dev)) {
450 err = PTR_ERR(backing_dev);
455 mapping = backing_dev->f_mapping;
456 inode = mapping->host;
458 /* Support only block device in this moment */
459 if (!S_ISBLK(inode->i_mode)) {
464 bdev = bdgrab(I_BDEV(inode));
465 err = blkdev_get(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL, zram);
471 nr_pages = i_size_read(inode) >> PAGE_SHIFT;
472 bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
473 bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
479 old_block_size = block_size(bdev);
480 err = set_blocksize(bdev, PAGE_SIZE);
486 zram->old_block_size = old_block_size;
488 zram->backing_dev = backing_dev;
489 zram->bitmap = bitmap;
490 zram->nr_pages = nr_pages;
492 * With writeback feature, zram does asynchronous IO so it's no longer
493 * synchronous device so let's remove synchronous io flag. Othewise,
494 * upper layer(e.g., swap) could wait IO completion rather than
495 * (submit and return), which will cause system sluggish.
496 * Furthermore, when the IO function returns(e.g., swap_readpage),
497 * upper layer expects IO was done so it could deallocate the page
498 * freely but in fact, IO is going on so finally could cause
499 * use-after-free when the IO is really done.
501 zram->disk->queue->backing_dev_info->capabilities &=
502 ~BDI_CAP_SYNCHRONOUS_IO;
503 up_write(&zram->init_lock);
505 pr_info("setup backing device %s\n", file_name);
514 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
517 filp_close(backing_dev, NULL);
519 up_write(&zram->init_lock);
526 static unsigned long alloc_block_bdev(struct zram *zram)
528 unsigned long blk_idx = 1;
530 /* skip 0 bit to confuse zram.handle = 0 */
531 blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, blk_idx);
532 if (blk_idx == zram->nr_pages)
535 if (test_and_set_bit(blk_idx, zram->bitmap))
538 atomic64_inc(&zram->stats.bd_count);
542 static void free_block_bdev(struct zram *zram, unsigned long blk_idx)
546 was_set = test_and_clear_bit(blk_idx, zram->bitmap);
547 WARN_ON_ONCE(!was_set);
548 atomic64_dec(&zram->stats.bd_count);
551 static void zram_page_end_io(struct bio *bio)
553 struct page *page = bio_first_page_all(bio);
555 page_endio(page, op_is_write(bio_op(bio)),
556 blk_status_to_errno(bio->bi_status));
561 * Returns 1 if the submission is successful.
563 static int read_from_bdev_async(struct zram *zram, struct bio_vec *bvec,
564 unsigned long entry, struct bio *parent)
568 bio = bio_alloc(GFP_ATOMIC, 1);
572 bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
573 bio_set_dev(bio, zram->bdev);
574 if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset)) {
580 bio->bi_opf = REQ_OP_READ;
581 bio->bi_end_io = zram_page_end_io;
583 bio->bi_opf = parent->bi_opf;
584 bio_chain(bio, parent);
591 #define HUGE_WRITEBACK 0x1
592 #define IDLE_WRITEBACK 0x2
594 static ssize_t writeback_store(struct device *dev,
595 struct device_attribute *attr, const char *buf, size_t len)
597 struct zram *zram = dev_to_zram(dev);
598 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
601 struct bio_vec bio_vec;
605 unsigned long mode = -1UL;
606 unsigned long blk_idx = 0;
608 sz = strscpy(mode_buf, buf, sizeof(mode_buf));
612 /* ignore trailing newline */
613 if (mode_buf[sz - 1] == '\n')
614 mode_buf[sz - 1] = 0x00;
616 if (!strcmp(mode_buf, "idle"))
617 mode = IDLE_WRITEBACK;
618 else if (!strcmp(mode_buf, "huge"))
619 mode = HUGE_WRITEBACK;
624 down_read(&zram->init_lock);
625 if (!init_done(zram)) {
627 goto release_init_lock;
630 if (!zram->backing_dev) {
632 goto release_init_lock;
635 page = alloc_page(GFP_KERNEL);
638 goto release_init_lock;
641 for (index = 0; index < nr_pages; index++) {
645 bvec.bv_len = PAGE_SIZE;
648 if (zram->stop_writeback) {
654 blk_idx = alloc_block_bdev(zram);
661 zram_slot_lock(zram, index);
662 if (!zram_allocated(zram, index))
665 if (zram_test_flag(zram, index, ZRAM_WB) ||
666 zram_test_flag(zram, index, ZRAM_SAME) ||
667 zram_test_flag(zram, index, ZRAM_UNDER_WB))
670 if ((mode & IDLE_WRITEBACK &&
671 !zram_test_flag(zram, index, ZRAM_IDLE)) &&
672 (mode & HUGE_WRITEBACK &&
673 !zram_test_flag(zram, index, ZRAM_HUGE)))
676 * Clearing ZRAM_UNDER_WB is duty of caller.
677 * IOW, zram_free_page never clear it.
679 zram_set_flag(zram, index, ZRAM_UNDER_WB);
680 /* Need for hugepage writeback racing */
681 zram_set_flag(zram, index, ZRAM_IDLE);
682 zram_slot_unlock(zram, index);
683 if (zram_bvec_read(zram, &bvec, index, 0, NULL)) {
684 zram_slot_lock(zram, index);
685 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
686 zram_clear_flag(zram, index, ZRAM_IDLE);
687 zram_slot_unlock(zram, index);
691 bio_init(&bio, &bio_vec, 1);
692 bio_set_dev(&bio, zram->bdev);
693 bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
694 bio.bi_opf = REQ_OP_WRITE | REQ_SYNC;
696 bio_add_page(&bio, bvec.bv_page, bvec.bv_len,
699 * XXX: A single page IO would be inefficient for write
700 * but it would be not bad as starter.
702 ret = submit_bio_wait(&bio);
704 zram_slot_lock(zram, index);
705 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
706 zram_clear_flag(zram, index, ZRAM_IDLE);
707 zram_slot_unlock(zram, index);
711 atomic64_inc(&zram->stats.bd_writes);
713 * We released zram_slot_lock so need to check if the slot was
714 * changed. If there is freeing for the slot, we can catch it
715 * easily by zram_allocated.
716 * A subtle case is the slot is freed/reallocated/marked as
717 * ZRAM_IDLE again. To close the race, idle_store doesn't
718 * mark ZRAM_IDLE once it found the slot was ZRAM_UNDER_WB.
719 * Thus, we could close the race by checking ZRAM_IDLE bit.
721 zram_slot_lock(zram, index);
722 if (!zram_allocated(zram, index) ||
723 !zram_test_flag(zram, index, ZRAM_IDLE)) {
724 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
725 zram_clear_flag(zram, index, ZRAM_IDLE);
729 zram_free_page(zram, index);
730 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
731 zram_set_flag(zram, index, ZRAM_WB);
732 zram_set_element(zram, index, blk_idx);
734 atomic64_inc(&zram->stats.pages_stored);
735 if (atomic64_add_unless(&zram->stats.bd_wb_limit,
736 -1 << (PAGE_SHIFT - 12), 0)) {
737 if (atomic64_read(&zram->stats.bd_wb_limit) == 0)
738 zram->stop_writeback = true;
741 zram_slot_unlock(zram, index);
745 free_block_bdev(zram, blk_idx);
749 up_read(&zram->init_lock);
755 struct work_struct work;
761 #if PAGE_SIZE != 4096
762 static void zram_sync_read(struct work_struct *work)
765 struct zram_work *zw = container_of(work, struct zram_work, work);
766 struct zram *zram = zw->zram;
767 unsigned long entry = zw->entry;
768 struct bio *bio = zw->bio;
770 read_from_bdev_async(zram, &bvec, entry, bio);
774 * Block layer want one ->make_request_fn to be active at a time
775 * so if we use chained IO with parent IO in same context,
776 * it's a deadlock. To avoid, it, it uses worker thread context.
778 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
779 unsigned long entry, struct bio *bio)
781 struct zram_work work;
787 INIT_WORK_ONSTACK(&work.work, zram_sync_read);
788 queue_work(system_unbound_wq, &work.work);
789 flush_work(&work.work);
790 destroy_work_on_stack(&work.work);
795 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
796 unsigned long entry, struct bio *bio)
803 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
804 unsigned long entry, struct bio *parent, bool sync)
806 atomic64_inc(&zram->stats.bd_reads);
808 return read_from_bdev_sync(zram, bvec, entry, parent);
810 return read_from_bdev_async(zram, bvec, entry, parent);
813 static inline void reset_bdev(struct zram *zram) {};
814 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
815 unsigned long entry, struct bio *parent, bool sync)
820 static void free_block_bdev(struct zram *zram, unsigned long blk_idx) {};
823 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
825 static struct dentry *zram_debugfs_root;
827 static void zram_debugfs_create(void)
829 zram_debugfs_root = debugfs_create_dir("zram", NULL);
832 static void zram_debugfs_destroy(void)
834 debugfs_remove_recursive(zram_debugfs_root);
837 static void zram_accessed(struct zram *zram, u32 index)
839 zram_clear_flag(zram, index, ZRAM_IDLE);
840 zram->table[index].ac_time = ktime_get_boottime();
843 static ssize_t read_block_state(struct file *file, char __user *buf,
844 size_t count, loff_t *ppos)
847 ssize_t index, written = 0;
848 struct zram *zram = file->private_data;
849 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
850 struct timespec64 ts;
852 kbuf = kvmalloc(count, GFP_KERNEL);
856 down_read(&zram->init_lock);
857 if (!init_done(zram)) {
858 up_read(&zram->init_lock);
863 for (index = *ppos; index < nr_pages; index++) {
866 zram_slot_lock(zram, index);
867 if (!zram_allocated(zram, index))
870 ts = ktime_to_timespec64(zram->table[index].ac_time);
871 copied = snprintf(kbuf + written, count,
872 "%12zd %12lld.%06lu %c%c%c%c\n",
873 index, (s64)ts.tv_sec,
874 ts.tv_nsec / NSEC_PER_USEC,
875 zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
876 zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
877 zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
878 zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.');
880 if (count < copied) {
881 zram_slot_unlock(zram, index);
887 zram_slot_unlock(zram, index);
891 up_read(&zram->init_lock);
892 if (copy_to_user(buf, kbuf, written))
899 static const struct file_operations proc_zram_block_state_op = {
901 .read = read_block_state,
902 .llseek = default_llseek,
905 static void zram_debugfs_register(struct zram *zram)
907 if (!zram_debugfs_root)
910 zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
912 debugfs_create_file("block_state", 0400, zram->debugfs_dir,
913 zram, &proc_zram_block_state_op);
916 static void zram_debugfs_unregister(struct zram *zram)
918 debugfs_remove_recursive(zram->debugfs_dir);
921 static void zram_debugfs_create(void) {};
922 static void zram_debugfs_destroy(void) {};
923 static void zram_accessed(struct zram *zram, u32 index)
925 zram_clear_flag(zram, index, ZRAM_IDLE);
927 static void zram_debugfs_register(struct zram *zram) {};
928 static void zram_debugfs_unregister(struct zram *zram) {};
932 * We switched to per-cpu streams and this attr is not needed anymore.
933 * However, we will keep it around for some time, because:
934 * a) we may revert per-cpu streams in the future
935 * b) it's visible to user space and we need to follow our 2 years
936 * retirement rule; but we already have a number of 'soon to be
937 * altered' attrs, so max_comp_streams need to wait for the next
940 static ssize_t max_comp_streams_show(struct device *dev,
941 struct device_attribute *attr, char *buf)
943 return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
946 static ssize_t max_comp_streams_store(struct device *dev,
947 struct device_attribute *attr, const char *buf, size_t len)
952 static ssize_t comp_algorithm_show(struct device *dev,
953 struct device_attribute *attr, char *buf)
956 struct zram *zram = dev_to_zram(dev);
958 down_read(&zram->init_lock);
959 sz = zcomp_available_show(zram->compressor, buf);
960 up_read(&zram->init_lock);
965 static ssize_t comp_algorithm_store(struct device *dev,
966 struct device_attribute *attr, const char *buf, size_t len)
968 struct zram *zram = dev_to_zram(dev);
969 char compressor[ARRAY_SIZE(zram->compressor)];
972 strlcpy(compressor, buf, sizeof(compressor));
973 /* ignore trailing newline */
974 sz = strlen(compressor);
975 if (sz > 0 && compressor[sz - 1] == '\n')
976 compressor[sz - 1] = 0x00;
978 if (!zcomp_available_algorithm(compressor))
981 down_write(&zram->init_lock);
982 if (init_done(zram)) {
983 up_write(&zram->init_lock);
984 pr_info("Can't change algorithm for initialized device\n");
988 strcpy(zram->compressor, compressor);
989 up_write(&zram->init_lock);
993 static ssize_t compact_store(struct device *dev,
994 struct device_attribute *attr, const char *buf, size_t len)
996 struct zram *zram = dev_to_zram(dev);
998 down_read(&zram->init_lock);
999 if (!init_done(zram)) {
1000 up_read(&zram->init_lock);
1004 zs_compact(zram->mem_pool);
1005 up_read(&zram->init_lock);
1010 static ssize_t io_stat_show(struct device *dev,
1011 struct device_attribute *attr, char *buf)
1013 struct zram *zram = dev_to_zram(dev);
1016 down_read(&zram->init_lock);
1017 ret = scnprintf(buf, PAGE_SIZE,
1018 "%8llu %8llu %8llu %8llu\n",
1019 (u64)atomic64_read(&zram->stats.failed_reads),
1020 (u64)atomic64_read(&zram->stats.failed_writes),
1021 (u64)atomic64_read(&zram->stats.invalid_io),
1022 (u64)atomic64_read(&zram->stats.notify_free));
1023 up_read(&zram->init_lock);
1028 static ssize_t mm_stat_show(struct device *dev,
1029 struct device_attribute *attr, char *buf)
1031 struct zram *zram = dev_to_zram(dev);
1032 struct zs_pool_stats pool_stats;
1033 u64 orig_size, mem_used = 0;
1037 memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1039 down_read(&zram->init_lock);
1040 if (init_done(zram)) {
1041 mem_used = zs_get_total_pages(zram->mem_pool);
1042 zs_pool_stats(zram->mem_pool, &pool_stats);
1045 orig_size = atomic64_read(&zram->stats.pages_stored);
1046 max_used = atomic_long_read(&zram->stats.max_used_pages);
1048 ret = scnprintf(buf, PAGE_SIZE,
1049 "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu\n",
1050 orig_size << PAGE_SHIFT,
1051 (u64)atomic64_read(&zram->stats.compr_data_size),
1052 mem_used << PAGE_SHIFT,
1053 zram->limit_pages << PAGE_SHIFT,
1054 max_used << PAGE_SHIFT,
1055 (u64)atomic64_read(&zram->stats.same_pages),
1056 pool_stats.pages_compacted,
1057 (u64)atomic64_read(&zram->stats.huge_pages));
1058 up_read(&zram->init_lock);
1063 #ifdef CONFIG_ZRAM_WRITEBACK
1064 #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
1065 static ssize_t bd_stat_show(struct device *dev,
1066 struct device_attribute *attr, char *buf)
1068 struct zram *zram = dev_to_zram(dev);
1071 down_read(&zram->init_lock);
1072 ret = scnprintf(buf, PAGE_SIZE,
1073 "%8llu %8llu %8llu\n",
1074 FOUR_K((u64)atomic64_read(&zram->stats.bd_count)),
1075 FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)),
1076 FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)));
1077 up_read(&zram->init_lock);
1083 static ssize_t debug_stat_show(struct device *dev,
1084 struct device_attribute *attr, char *buf)
1087 struct zram *zram = dev_to_zram(dev);
1090 down_read(&zram->init_lock);
1091 ret = scnprintf(buf, PAGE_SIZE,
1092 "version: %d\n%8llu %8llu\n",
1094 (u64)atomic64_read(&zram->stats.writestall),
1095 (u64)atomic64_read(&zram->stats.miss_free));
1096 up_read(&zram->init_lock);
1101 static DEVICE_ATTR_RO(io_stat);
1102 static DEVICE_ATTR_RO(mm_stat);
1103 #ifdef CONFIG_ZRAM_WRITEBACK
1104 static DEVICE_ATTR_RO(bd_stat);
1106 static DEVICE_ATTR_RO(debug_stat);
1108 static void zram_meta_free(struct zram *zram, u64 disksize)
1110 size_t num_pages = disksize >> PAGE_SHIFT;
1113 /* Free all pages that are still in this zram device */
1114 for (index = 0; index < num_pages; index++)
1115 zram_free_page(zram, index);
1117 zs_destroy_pool(zram->mem_pool);
1121 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
1125 num_pages = disksize >> PAGE_SHIFT;
1126 zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
1130 zram->mem_pool = zs_create_pool(zram->disk->disk_name);
1131 if (!zram->mem_pool) {
1136 if (!huge_class_size)
1137 huge_class_size = zs_huge_class_size(zram->mem_pool);
1142 * To protect concurrent access to the same index entry,
1143 * caller should hold this table index entry's bit_spinlock to
1144 * indicate this index entry is accessing.
1146 static void zram_free_page(struct zram *zram, size_t index)
1148 unsigned long handle;
1150 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
1151 zram->table[index].ac_time = 0;
1153 if (zram_test_flag(zram, index, ZRAM_IDLE))
1154 zram_clear_flag(zram, index, ZRAM_IDLE);
1156 if (zram_test_flag(zram, index, ZRAM_HUGE)) {
1157 zram_clear_flag(zram, index, ZRAM_HUGE);
1158 atomic64_dec(&zram->stats.huge_pages);
1161 if (zram_test_flag(zram, index, ZRAM_WB)) {
1162 zram_clear_flag(zram, index, ZRAM_WB);
1163 free_block_bdev(zram, zram_get_element(zram, index));
1168 * No memory is allocated for same element filled pages.
1169 * Simply clear same page flag.
1171 if (zram_test_flag(zram, index, ZRAM_SAME)) {
1172 zram_clear_flag(zram, index, ZRAM_SAME);
1173 atomic64_dec(&zram->stats.same_pages);
1177 handle = zram_get_handle(zram, index);
1181 zs_free(zram->mem_pool, handle);
1183 atomic64_sub(zram_get_obj_size(zram, index),
1184 &zram->stats.compr_data_size);
1186 atomic64_dec(&zram->stats.pages_stored);
1187 zram_set_handle(zram, index, 0);
1188 zram_set_obj_size(zram, index, 0);
1189 WARN_ON_ONCE(zram->table[index].flags &
1190 ~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB));
1193 static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index,
1194 struct bio *bio, bool partial_io)
1197 unsigned long handle;
1201 zram_slot_lock(zram, index);
1202 if (zram_test_flag(zram, index, ZRAM_WB)) {
1203 struct bio_vec bvec;
1205 zram_slot_unlock(zram, index);
1207 bvec.bv_page = page;
1208 bvec.bv_len = PAGE_SIZE;
1210 return read_from_bdev(zram, &bvec,
1211 zram_get_element(zram, index),
1215 handle = zram_get_handle(zram, index);
1216 if (!handle || zram_test_flag(zram, index, ZRAM_SAME)) {
1217 unsigned long value;
1220 value = handle ? zram_get_element(zram, index) : 0;
1221 mem = kmap_atomic(page);
1222 zram_fill_page(mem, PAGE_SIZE, value);
1224 zram_slot_unlock(zram, index);
1228 size = zram_get_obj_size(zram, index);
1230 src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
1231 if (size == PAGE_SIZE) {
1232 dst = kmap_atomic(page);
1233 memcpy(dst, src, PAGE_SIZE);
1237 struct zcomp_strm *zstrm = zcomp_stream_get(zram->comp);
1239 dst = kmap_atomic(page);
1240 ret = zcomp_decompress(zstrm, src, size, dst);
1242 zcomp_stream_put(zram->comp);
1244 zs_unmap_object(zram->mem_pool, handle);
1245 zram_slot_unlock(zram, index);
1247 /* Should NEVER happen. Return bio error if it does. */
1249 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1254 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1255 u32 index, int offset, struct bio *bio)
1260 page = bvec->bv_page;
1261 if (is_partial_io(bvec)) {
1262 /* Use a temporary buffer to decompress the page */
1263 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1268 ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec));
1272 if (is_partial_io(bvec)) {
1273 void *dst = kmap_atomic(bvec->bv_page);
1274 void *src = kmap_atomic(page);
1276 memcpy(dst + bvec->bv_offset, src + offset, bvec->bv_len);
1281 if (is_partial_io(bvec))
1287 static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1288 u32 index, struct bio *bio)
1291 unsigned long alloced_pages;
1292 unsigned long handle = 0;
1293 unsigned int comp_len = 0;
1294 void *src, *dst, *mem;
1295 struct zcomp_strm *zstrm;
1296 struct page *page = bvec->bv_page;
1297 unsigned long element = 0;
1298 enum zram_pageflags flags = 0;
1300 mem = kmap_atomic(page);
1301 if (page_same_filled(mem, &element)) {
1303 /* Free memory associated with this sector now. */
1305 atomic64_inc(&zram->stats.same_pages);
1311 zstrm = zcomp_stream_get(zram->comp);
1312 src = kmap_atomic(page);
1313 ret = zcomp_compress(zstrm, src, &comp_len);
1316 if (unlikely(ret)) {
1317 zcomp_stream_put(zram->comp);
1318 pr_err("Compression failed! err=%d\n", ret);
1319 zs_free(zram->mem_pool, handle);
1323 if (comp_len >= huge_class_size)
1324 comp_len = PAGE_SIZE;
1326 * handle allocation has 2 paths:
1327 * a) fast path is executed with preemption disabled (for
1328 * per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
1329 * since we can't sleep;
1330 * b) slow path enables preemption and attempts to allocate
1331 * the page with __GFP_DIRECT_RECLAIM bit set. we have to
1332 * put per-cpu compression stream and, thus, to re-do
1333 * the compression once handle is allocated.
1335 * if we have a 'non-null' handle here then we are coming
1336 * from the slow path and handle has already been allocated.
1339 handle = zs_malloc(zram->mem_pool, comp_len,
1340 __GFP_KSWAPD_RECLAIM |
1345 zcomp_stream_put(zram->comp);
1346 atomic64_inc(&zram->stats.writestall);
1347 handle = zs_malloc(zram->mem_pool, comp_len,
1348 GFP_NOIO | __GFP_HIGHMEM |
1351 goto compress_again;
1355 alloced_pages = zs_get_total_pages(zram->mem_pool);
1356 update_used_max(zram, alloced_pages);
1358 if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1359 zcomp_stream_put(zram->comp);
1360 zs_free(zram->mem_pool, handle);
1364 dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1366 src = zstrm->buffer;
1367 if (comp_len == PAGE_SIZE)
1368 src = kmap_atomic(page);
1369 memcpy(dst, src, comp_len);
1370 if (comp_len == PAGE_SIZE)
1373 zcomp_stream_put(zram->comp);
1374 zs_unmap_object(zram->mem_pool, handle);
1375 atomic64_add(comp_len, &zram->stats.compr_data_size);
1378 * Free memory associated with this sector
1379 * before overwriting unused sectors.
1381 zram_slot_lock(zram, index);
1382 zram_free_page(zram, index);
1384 if (comp_len == PAGE_SIZE) {
1385 zram_set_flag(zram, index, ZRAM_HUGE);
1386 atomic64_inc(&zram->stats.huge_pages);
1390 zram_set_flag(zram, index, flags);
1391 zram_set_element(zram, index, element);
1393 zram_set_handle(zram, index, handle);
1394 zram_set_obj_size(zram, index, comp_len);
1396 zram_slot_unlock(zram, index);
1399 atomic64_inc(&zram->stats.pages_stored);
1403 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1404 u32 index, int offset, struct bio *bio)
1407 struct page *page = NULL;
1412 if (is_partial_io(bvec)) {
1415 * This is a partial IO. We need to read the full page
1416 * before to write the changes.
1418 page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1422 ret = __zram_bvec_read(zram, page, index, bio, true);
1426 src = kmap_atomic(bvec->bv_page);
1427 dst = kmap_atomic(page);
1428 memcpy(dst + offset, src + bvec->bv_offset, bvec->bv_len);
1433 vec.bv_len = PAGE_SIZE;
1437 ret = __zram_bvec_write(zram, &vec, index, bio);
1439 if (is_partial_io(bvec))
1445 * zram_bio_discard - handler on discard request
1446 * @index: physical block index in PAGE_SIZE units
1447 * @offset: byte offset within physical block
1449 static void zram_bio_discard(struct zram *zram, u32 index,
1450 int offset, struct bio *bio)
1452 size_t n = bio->bi_iter.bi_size;
1455 * zram manages data in physical block size units. Because logical block
1456 * size isn't identical with physical block size on some arch, we
1457 * could get a discard request pointing to a specific offset within a
1458 * certain physical block. Although we can handle this request by
1459 * reading that physiclal block and decompressing and partially zeroing
1460 * and re-compressing and then re-storing it, this isn't reasonable
1461 * because our intent with a discard request is to save memory. So
1462 * skipping this logical block is appropriate here.
1465 if (n <= (PAGE_SIZE - offset))
1468 n -= (PAGE_SIZE - offset);
1472 while (n >= PAGE_SIZE) {
1473 zram_slot_lock(zram, index);
1474 zram_free_page(zram, index);
1475 zram_slot_unlock(zram, index);
1476 atomic64_inc(&zram->stats.notify_free);
1483 * Returns errno if it has some problem. Otherwise return 0 or 1.
1484 * Returns 0 if IO request was done synchronously
1485 * Returns 1 if IO request was successfully submitted.
1487 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
1488 int offset, unsigned int op, struct bio *bio)
1490 unsigned long start_time = jiffies;
1491 struct request_queue *q = zram->disk->queue;
1494 generic_start_io_acct(q, op, bvec->bv_len >> SECTOR_SHIFT,
1495 &zram->disk->part0);
1497 if (!op_is_write(op)) {
1498 atomic64_inc(&zram->stats.num_reads);
1499 ret = zram_bvec_read(zram, bvec, index, offset, bio);
1500 flush_dcache_page(bvec->bv_page);
1502 atomic64_inc(&zram->stats.num_writes);
1503 ret = zram_bvec_write(zram, bvec, index, offset, bio);
1506 generic_end_io_acct(q, op, &zram->disk->part0, start_time);
1508 zram_slot_lock(zram, index);
1509 zram_accessed(zram, index);
1510 zram_slot_unlock(zram, index);
1512 if (unlikely(ret < 0)) {
1513 if (!op_is_write(op))
1514 atomic64_inc(&zram->stats.failed_reads);
1516 atomic64_inc(&zram->stats.failed_writes);
1522 static void __zram_make_request(struct zram *zram, struct bio *bio)
1526 struct bio_vec bvec;
1527 struct bvec_iter iter;
1529 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1530 offset = (bio->bi_iter.bi_sector &
1531 (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1533 switch (bio_op(bio)) {
1534 case REQ_OP_DISCARD:
1535 case REQ_OP_WRITE_ZEROES:
1536 zram_bio_discard(zram, index, offset, bio);
1543 bio_for_each_segment(bvec, bio, iter) {
1544 struct bio_vec bv = bvec;
1545 unsigned int unwritten = bvec.bv_len;
1548 bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
1550 if (zram_bvec_rw(zram, &bv, index, offset,
1551 bio_op(bio), bio) < 0)
1554 bv.bv_offset += bv.bv_len;
1555 unwritten -= bv.bv_len;
1557 update_position(&index, &offset, &bv);
1558 } while (unwritten);
1569 * Handler function for all zram I/O requests.
1571 static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio)
1573 struct zram *zram = queue->queuedata;
1575 if (!valid_io_request(zram, bio->bi_iter.bi_sector,
1576 bio->bi_iter.bi_size)) {
1577 atomic64_inc(&zram->stats.invalid_io);
1581 __zram_make_request(zram, bio);
1582 return BLK_QC_T_NONE;
1586 return BLK_QC_T_NONE;
1589 static void zram_slot_free_notify(struct block_device *bdev,
1590 unsigned long index)
1594 zram = bdev->bd_disk->private_data;
1596 atomic64_inc(&zram->stats.notify_free);
1597 if (!zram_slot_trylock(zram, index)) {
1598 atomic64_inc(&zram->stats.miss_free);
1602 zram_free_page(zram, index);
1603 zram_slot_unlock(zram, index);
1606 static int zram_rw_page(struct block_device *bdev, sector_t sector,
1607 struct page *page, unsigned int op)
1614 if (PageTransHuge(page))
1616 zram = bdev->bd_disk->private_data;
1618 if (!valid_io_request(zram, sector, PAGE_SIZE)) {
1619 atomic64_inc(&zram->stats.invalid_io);
1624 index = sector >> SECTORS_PER_PAGE_SHIFT;
1625 offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1628 bv.bv_len = PAGE_SIZE;
1631 ret = zram_bvec_rw(zram, &bv, index, offset, op, NULL);
1634 * If I/O fails, just return error(ie, non-zero) without
1635 * calling page_endio.
1636 * It causes resubmit the I/O with bio request by upper functions
1637 * of rw_page(e.g., swap_readpage, __swap_writepage) and
1638 * bio->bi_end_io does things to handle the error
1639 * (e.g., SetPageError, set_page_dirty and extra works).
1641 if (unlikely(ret < 0))
1646 page_endio(page, op_is_write(op), 0);
1657 static void zram_reset_device(struct zram *zram)
1662 down_write(&zram->init_lock);
1664 zram->limit_pages = 0;
1666 if (!init_done(zram)) {
1667 up_write(&zram->init_lock);
1672 disksize = zram->disksize;
1675 set_capacity(zram->disk, 0);
1676 part_stat_set_all(&zram->disk->part0, 0);
1678 up_write(&zram->init_lock);
1679 /* I/O operation under all of CPU are done so let's free */
1680 zram_meta_free(zram, disksize);
1681 memset(&zram->stats, 0, sizeof(zram->stats));
1682 zcomp_destroy(comp);
1686 static ssize_t disksize_store(struct device *dev,
1687 struct device_attribute *attr, const char *buf, size_t len)
1691 struct zram *zram = dev_to_zram(dev);
1694 disksize = memparse(buf, NULL);
1698 down_write(&zram->init_lock);
1699 if (init_done(zram)) {
1700 pr_info("Cannot change disksize for initialized device\n");
1705 disksize = PAGE_ALIGN(disksize);
1706 if (!zram_meta_alloc(zram, disksize)) {
1711 comp = zcomp_create(zram->compressor);
1713 pr_err("Cannot initialise %s compressing backend\n",
1715 err = PTR_ERR(comp);
1720 zram->disksize = disksize;
1721 set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
1723 revalidate_disk(zram->disk);
1724 up_write(&zram->init_lock);
1729 zram_meta_free(zram, disksize);
1731 up_write(&zram->init_lock);
1735 static ssize_t reset_store(struct device *dev,
1736 struct device_attribute *attr, const char *buf, size_t len)
1739 unsigned short do_reset;
1741 struct block_device *bdev;
1743 ret = kstrtou16(buf, 10, &do_reset);
1750 zram = dev_to_zram(dev);
1751 bdev = bdget_disk(zram->disk, 0);
1755 mutex_lock(&bdev->bd_mutex);
1756 /* Do not reset an active device or claimed device */
1757 if (bdev->bd_openers || zram->claim) {
1758 mutex_unlock(&bdev->bd_mutex);
1763 /* From now on, anyone can't open /dev/zram[0-9] */
1765 mutex_unlock(&bdev->bd_mutex);
1767 /* Make sure all the pending I/O are finished */
1769 zram_reset_device(zram);
1770 revalidate_disk(zram->disk);
1773 mutex_lock(&bdev->bd_mutex);
1774 zram->claim = false;
1775 mutex_unlock(&bdev->bd_mutex);
1780 static int zram_open(struct block_device *bdev, fmode_t mode)
1785 WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
1787 zram = bdev->bd_disk->private_data;
1788 /* zram was claimed to reset so open request fails */
1795 static const struct block_device_operations zram_devops = {
1797 .swap_slot_free_notify = zram_slot_free_notify,
1798 .rw_page = zram_rw_page,
1799 .owner = THIS_MODULE
1802 static DEVICE_ATTR_WO(compact);
1803 static DEVICE_ATTR_RW(disksize);
1804 static DEVICE_ATTR_RO(initstate);
1805 static DEVICE_ATTR_WO(reset);
1806 static DEVICE_ATTR_WO(mem_limit);
1807 static DEVICE_ATTR_WO(mem_used_max);
1808 static DEVICE_ATTR_WO(idle);
1809 static DEVICE_ATTR_RW(max_comp_streams);
1810 static DEVICE_ATTR_RW(comp_algorithm);
1811 #ifdef CONFIG_ZRAM_WRITEBACK
1812 static DEVICE_ATTR_RW(backing_dev);
1813 static DEVICE_ATTR_WO(writeback);
1814 static DEVICE_ATTR_RW(writeback_limit);
1817 static struct attribute *zram_disk_attrs[] = {
1818 &dev_attr_disksize.attr,
1819 &dev_attr_initstate.attr,
1820 &dev_attr_reset.attr,
1821 &dev_attr_compact.attr,
1822 &dev_attr_mem_limit.attr,
1823 &dev_attr_mem_used_max.attr,
1824 &dev_attr_idle.attr,
1825 &dev_attr_max_comp_streams.attr,
1826 &dev_attr_comp_algorithm.attr,
1827 #ifdef CONFIG_ZRAM_WRITEBACK
1828 &dev_attr_backing_dev.attr,
1829 &dev_attr_writeback.attr,
1830 &dev_attr_writeback_limit.attr,
1832 &dev_attr_io_stat.attr,
1833 &dev_attr_mm_stat.attr,
1834 #ifdef CONFIG_ZRAM_WRITEBACK
1835 &dev_attr_bd_stat.attr,
1837 &dev_attr_debug_stat.attr,
1841 static const struct attribute_group zram_disk_attr_group = {
1842 .attrs = zram_disk_attrs,
1845 static const struct attribute_group *zram_disk_attr_groups[] = {
1846 &zram_disk_attr_group,
1851 * Allocate and initialize new zram device. the function returns
1852 * '>= 0' device_id upon success, and negative value otherwise.
1854 static int zram_add(void)
1857 struct request_queue *queue;
1860 zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1864 ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1869 init_rwsem(&zram->init_lock);
1871 queue = blk_alloc_queue(GFP_KERNEL);
1873 pr_err("Error allocating disk queue for device %d\n",
1879 blk_queue_make_request(queue, zram_make_request);
1881 /* gendisk structure */
1882 zram->disk = alloc_disk(1);
1884 pr_err("Error allocating disk structure for device %d\n",
1887 goto out_free_queue;
1890 zram->disk->major = zram_major;
1891 zram->disk->first_minor = device_id;
1892 zram->disk->fops = &zram_devops;
1893 zram->disk->queue = queue;
1894 zram->disk->queue->queuedata = zram;
1895 zram->disk->private_data = zram;
1896 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1898 /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1899 set_capacity(zram->disk, 0);
1900 /* zram devices sort of resembles non-rotational disks */
1901 blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
1902 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1905 * To ensure that we always get PAGE_SIZE aligned
1906 * and n*PAGE_SIZED sized I/O requests.
1908 blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1909 blk_queue_logical_block_size(zram->disk->queue,
1910 ZRAM_LOGICAL_BLOCK_SIZE);
1911 blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1912 blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1913 zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1914 blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1915 blk_queue_flag_set(QUEUE_FLAG_DISCARD, zram->disk->queue);
1918 * zram_bio_discard() will clear all logical blocks if logical block
1919 * size is identical with physical block size(PAGE_SIZE). But if it is
1920 * different, we will skip discarding some parts of logical blocks in
1921 * the part of the request range which isn't aligned to physical block
1922 * size. So we can't ensure that all discarded logical blocks are
1925 if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1926 blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
1928 zram->disk->queue->backing_dev_info->capabilities |=
1929 (BDI_CAP_STABLE_WRITES | BDI_CAP_SYNCHRONOUS_IO);
1930 device_add_disk(NULL, zram->disk, zram_disk_attr_groups);
1932 strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1934 zram_debugfs_register(zram);
1935 pr_info("Added device: %s\n", zram->disk->disk_name);
1939 blk_cleanup_queue(queue);
1941 idr_remove(&zram_index_idr, device_id);
1947 static int zram_remove(struct zram *zram)
1949 struct block_device *bdev;
1951 bdev = bdget_disk(zram->disk, 0);
1955 mutex_lock(&bdev->bd_mutex);
1956 if (bdev->bd_openers || zram->claim) {
1957 mutex_unlock(&bdev->bd_mutex);
1963 mutex_unlock(&bdev->bd_mutex);
1965 zram_debugfs_unregister(zram);
1967 /* Make sure all the pending I/O are finished */
1969 zram_reset_device(zram);
1972 pr_info("Removed device: %s\n", zram->disk->disk_name);
1974 del_gendisk(zram->disk);
1975 blk_cleanup_queue(zram->disk->queue);
1976 put_disk(zram->disk);
1981 /* zram-control sysfs attributes */
1984 * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
1985 * sense that reading from this file does alter the state of your system -- it
1986 * creates a new un-initialized zram device and returns back this device's
1987 * device_id (or an error code if it fails to create a new device).
1989 static ssize_t hot_add_show(struct class *class,
1990 struct class_attribute *attr,
1995 mutex_lock(&zram_index_mutex);
1997 mutex_unlock(&zram_index_mutex);
2001 return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
2003 static CLASS_ATTR_RO(hot_add);
2005 static ssize_t hot_remove_store(struct class *class,
2006 struct class_attribute *attr,
2013 /* dev_id is gendisk->first_minor, which is `int' */
2014 ret = kstrtoint(buf, 10, &dev_id);
2020 mutex_lock(&zram_index_mutex);
2022 zram = idr_find(&zram_index_idr, dev_id);
2024 ret = zram_remove(zram);
2026 idr_remove(&zram_index_idr, dev_id);
2031 mutex_unlock(&zram_index_mutex);
2032 return ret ? ret : count;
2034 static CLASS_ATTR_WO(hot_remove);
2036 static struct attribute *zram_control_class_attrs[] = {
2037 &class_attr_hot_add.attr,
2038 &class_attr_hot_remove.attr,
2041 ATTRIBUTE_GROUPS(zram_control_class);
2043 static struct class zram_control_class = {
2044 .name = "zram-control",
2045 .owner = THIS_MODULE,
2046 .class_groups = zram_control_class_groups,
2049 static int zram_remove_cb(int id, void *ptr, void *data)
2055 static void destroy_devices(void)
2057 class_unregister(&zram_control_class);
2058 idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
2059 zram_debugfs_destroy();
2060 idr_destroy(&zram_index_idr);
2061 unregister_blkdev(zram_major, "zram");
2062 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2065 static int __init zram_init(void)
2069 ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
2070 zcomp_cpu_up_prepare, zcomp_cpu_dead);
2074 ret = class_register(&zram_control_class);
2076 pr_err("Unable to register zram-control class\n");
2077 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2081 zram_debugfs_create();
2082 zram_major = register_blkdev(0, "zram");
2083 if (zram_major <= 0) {
2084 pr_err("Unable to get major number\n");
2085 class_unregister(&zram_control_class);
2086 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2090 while (num_devices != 0) {
2091 mutex_lock(&zram_index_mutex);
2093 mutex_unlock(&zram_index_mutex);
2106 static void __exit zram_exit(void)
2111 module_init(zram_init);
2112 module_exit(zram_exit);
2114 module_param(num_devices, uint, 0);
2115 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
2117 MODULE_LICENSE("Dual BSD/GPL");
2118 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2119 MODULE_DESCRIPTION("Compressed RAM Block Device");