Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Compressed RAM block device
0003  *
0004  * Copyright (C) 2008, 2009, 2010  Nitin Gupta
0005  *               2012, 2013 Minchan Kim
0006  *
0007  * This code is released using a dual license strategy: BSD/GPL
0008  * You can choose the licence that better fits your requirements.
0009  *
0010  * Released under the terms of 3-clause BSD License
0011  * Released under the terms of GNU General Public License Version 2.0
0012  *
0013  */
0014 
0015 #define KMSG_COMPONENT "zram"
0016 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
0017 
0018 #include <linux/module.h>
0019 #include <linux/kernel.h>
0020 #include <linux/bio.h>
0021 #include <linux/bitops.h>
0022 #include <linux/blkdev.h>
0023 #include <linux/buffer_head.h>
0024 #include <linux/device.h>
0025 #include <linux/highmem.h>
0026 #include <linux/slab.h>
0027 #include <linux/backing-dev.h>
0028 #include <linux/string.h>
0029 #include <linux/vmalloc.h>
0030 #include <linux/err.h>
0031 #include <linux/idr.h>
0032 #include <linux/sysfs.h>
0033 #include <linux/debugfs.h>
0034 #include <linux/cpuhotplug.h>
0035 #include <linux/part_stat.h>
0036 
0037 #include "zram_drv.h"
0038 
0039 static DEFINE_IDR(zram_index_idr);
0040 /* idr index must be protected */
0041 static DEFINE_MUTEX(zram_index_mutex);
0042 
0043 static int zram_major;
0044 static const char *default_compressor = CONFIG_ZRAM_DEF_COMP;
0045 
0046 /* Module params (documentation at end) */
0047 static unsigned int num_devices = 1;
0048 /*
0049  * Pages that compress to sizes equals or greater than this are stored
0050  * uncompressed in memory.
0051  */
0052 static size_t huge_class_size;
0053 
0054 static const struct block_device_operations zram_devops;
0055 #ifdef CONFIG_ZRAM_WRITEBACK
0056 static const struct block_device_operations zram_wb_devops;
0057 #endif
0058 
0059 static void zram_free_page(struct zram *zram, size_t index);
0060 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
0061                 u32 index, int offset, struct bio *bio);
0062 
0063 
0064 static int zram_slot_trylock(struct zram *zram, u32 index)
0065 {
0066     return bit_spin_trylock(ZRAM_LOCK, &zram->table[index].flags);
0067 }
0068 
0069 static void zram_slot_lock(struct zram *zram, u32 index)
0070 {
0071     bit_spin_lock(ZRAM_LOCK, &zram->table[index].flags);
0072 }
0073 
0074 static void zram_slot_unlock(struct zram *zram, u32 index)
0075 {
0076     bit_spin_unlock(ZRAM_LOCK, &zram->table[index].flags);
0077 }
0078 
0079 static inline bool init_done(struct zram *zram)
0080 {
0081     return zram->disksize;
0082 }
0083 
0084 static inline struct zram *dev_to_zram(struct device *dev)
0085 {
0086     return (struct zram *)dev_to_disk(dev)->private_data;
0087 }
0088 
0089 static unsigned long zram_get_handle(struct zram *zram, u32 index)
0090 {
0091     return zram->table[index].handle;
0092 }
0093 
0094 static void zram_set_handle(struct zram *zram, u32 index, unsigned long handle)
0095 {
0096     zram->table[index].handle = handle;
0097 }
0098 
0099 /* flag operations require table entry bit_spin_lock() being held */
0100 static bool zram_test_flag(struct zram *zram, u32 index,
0101             enum zram_pageflags flag)
0102 {
0103     return zram->table[index].flags & BIT(flag);
0104 }
0105 
0106 static void zram_set_flag(struct zram *zram, u32 index,
0107             enum zram_pageflags flag)
0108 {
0109     zram->table[index].flags |= BIT(flag);
0110 }
0111 
0112 static void zram_clear_flag(struct zram *zram, u32 index,
0113             enum zram_pageflags flag)
0114 {
0115     zram->table[index].flags &= ~BIT(flag);
0116 }
0117 
0118 static inline void zram_set_element(struct zram *zram, u32 index,
0119             unsigned long element)
0120 {
0121     zram->table[index].element = element;
0122 }
0123 
0124 static unsigned long zram_get_element(struct zram *zram, u32 index)
0125 {
0126     return zram->table[index].element;
0127 }
0128 
0129 static size_t zram_get_obj_size(struct zram *zram, u32 index)
0130 {
0131     return zram->table[index].flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
0132 }
0133 
0134 static void zram_set_obj_size(struct zram *zram,
0135                     u32 index, size_t size)
0136 {
0137     unsigned long flags = zram->table[index].flags >> ZRAM_FLAG_SHIFT;
0138 
0139     zram->table[index].flags = (flags << ZRAM_FLAG_SHIFT) | size;
0140 }
0141 
0142 static inline bool zram_allocated(struct zram *zram, u32 index)
0143 {
0144     return zram_get_obj_size(zram, index) ||
0145             zram_test_flag(zram, index, ZRAM_SAME) ||
0146             zram_test_flag(zram, index, ZRAM_WB);
0147 }
0148 
0149 #if PAGE_SIZE != 4096
0150 static inline bool is_partial_io(struct bio_vec *bvec)
0151 {
0152     return bvec->bv_len != PAGE_SIZE;
0153 }
0154 #else
0155 static inline bool is_partial_io(struct bio_vec *bvec)
0156 {
0157     return false;
0158 }
0159 #endif
0160 
0161 /*
0162  * Check if request is within bounds and aligned on zram logical blocks.
0163  */
0164 static inline bool valid_io_request(struct zram *zram,
0165         sector_t start, unsigned int size)
0166 {
0167     u64 end, bound;
0168 
0169     /* unaligned request */
0170     if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
0171         return false;
0172     if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
0173         return false;
0174 
0175     end = start + (size >> SECTOR_SHIFT);
0176     bound = zram->disksize >> SECTOR_SHIFT;
0177     /* out of range range */
0178     if (unlikely(start >= bound || end > bound || start > end))
0179         return false;
0180 
0181     /* I/O request is valid */
0182     return true;
0183 }
0184 
0185 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
0186 {
0187     *index  += (*offset + bvec->bv_len) / PAGE_SIZE;
0188     *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
0189 }
0190 
0191 static inline void update_used_max(struct zram *zram,
0192                     const unsigned long pages)
0193 {
0194     unsigned long old_max, cur_max;
0195 
0196     old_max = atomic_long_read(&zram->stats.max_used_pages);
0197 
0198     do {
0199         cur_max = old_max;
0200         if (pages > cur_max)
0201             old_max = atomic_long_cmpxchg(
0202                 &zram->stats.max_used_pages, cur_max, pages);
0203     } while (old_max != cur_max);
0204 }
0205 
0206 static inline void zram_fill_page(void *ptr, unsigned long len,
0207                     unsigned long value)
0208 {
0209     WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
0210     memset_l(ptr, value, len / sizeof(unsigned long));
0211 }
0212 
0213 static bool page_same_filled(void *ptr, unsigned long *element)
0214 {
0215     unsigned long *page;
0216     unsigned long val;
0217     unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
0218 
0219     page = (unsigned long *)ptr;
0220     val = page[0];
0221 
0222     if (val != page[last_pos])
0223         return false;
0224 
0225     for (pos = 1; pos < last_pos; pos++) {
0226         if (val != page[pos])
0227             return false;
0228     }
0229 
0230     *element = val;
0231 
0232     return true;
0233 }
0234 
0235 static ssize_t initstate_show(struct device *dev,
0236         struct device_attribute *attr, char *buf)
0237 {
0238     u32 val;
0239     struct zram *zram = dev_to_zram(dev);
0240 
0241     down_read(&zram->init_lock);
0242     val = init_done(zram);
0243     up_read(&zram->init_lock);
0244 
0245     return scnprintf(buf, PAGE_SIZE, "%u\n", val);
0246 }
0247 
0248 static ssize_t disksize_show(struct device *dev,
0249         struct device_attribute *attr, char *buf)
0250 {
0251     struct zram *zram = dev_to_zram(dev);
0252 
0253     return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
0254 }
0255 
0256 static ssize_t mem_limit_store(struct device *dev,
0257         struct device_attribute *attr, const char *buf, size_t len)
0258 {
0259     u64 limit;
0260     char *tmp;
0261     struct zram *zram = dev_to_zram(dev);
0262 
0263     limit = memparse(buf, &tmp);
0264     if (buf == tmp) /* no chars parsed, invalid input */
0265         return -EINVAL;
0266 
0267     down_write(&zram->init_lock);
0268     zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
0269     up_write(&zram->init_lock);
0270 
0271     return len;
0272 }
0273 
0274 static ssize_t mem_used_max_store(struct device *dev,
0275         struct device_attribute *attr, const char *buf, size_t len)
0276 {
0277     int err;
0278     unsigned long val;
0279     struct zram *zram = dev_to_zram(dev);
0280 
0281     err = kstrtoul(buf, 10, &val);
0282     if (err || val != 0)
0283         return -EINVAL;
0284 
0285     down_read(&zram->init_lock);
0286     if (init_done(zram)) {
0287         atomic_long_set(&zram->stats.max_used_pages,
0288                 zs_get_total_pages(zram->mem_pool));
0289     }
0290     up_read(&zram->init_lock);
0291 
0292     return len;
0293 }
0294 
0295 /*
0296  * Mark all pages which are older than or equal to cutoff as IDLE.
0297  * Callers should hold the zram init lock in read mode
0298  */
0299 static void mark_idle(struct zram *zram, ktime_t cutoff)
0300 {
0301     int is_idle = 1;
0302     unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
0303     int index;
0304 
0305     for (index = 0; index < nr_pages; index++) {
0306         /*
0307          * Do not mark ZRAM_UNDER_WB slot as ZRAM_IDLE to close race.
0308          * See the comment in writeback_store.
0309          */
0310         zram_slot_lock(zram, index);
0311         if (zram_allocated(zram, index) &&
0312                 !zram_test_flag(zram, index, ZRAM_UNDER_WB)) {
0313 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
0314             is_idle = !cutoff || ktime_after(cutoff, zram->table[index].ac_time);
0315 #endif
0316             if (is_idle)
0317                 zram_set_flag(zram, index, ZRAM_IDLE);
0318         }
0319         zram_slot_unlock(zram, index);
0320     }
0321 }
0322 
0323 static ssize_t idle_store(struct device *dev,
0324         struct device_attribute *attr, const char *buf, size_t len)
0325 {
0326     struct zram *zram = dev_to_zram(dev);
0327     ktime_t cutoff_time = 0;
0328     ssize_t rv = -EINVAL;
0329 
0330     if (!sysfs_streq(buf, "all")) {
0331         /*
0332          * If it did not parse as 'all' try to treat it as an integer when
0333          * we have memory tracking enabled.
0334          */
0335         u64 age_sec;
0336 
0337         if (IS_ENABLED(CONFIG_ZRAM_MEMORY_TRACKING) && !kstrtoull(buf, 0, &age_sec))
0338             cutoff_time = ktime_sub(ktime_get_boottime(),
0339                     ns_to_ktime(age_sec * NSEC_PER_SEC));
0340         else
0341             goto out;
0342     }
0343 
0344     down_read(&zram->init_lock);
0345     if (!init_done(zram))
0346         goto out_unlock;
0347 
0348     /* A cutoff_time of 0 marks everything as idle, this is the "all" behavior */
0349     mark_idle(zram, cutoff_time);
0350     rv = len;
0351 
0352 out_unlock:
0353     up_read(&zram->init_lock);
0354 out:
0355     return rv;
0356 }
0357 
0358 #ifdef CONFIG_ZRAM_WRITEBACK
0359 static ssize_t writeback_limit_enable_store(struct device *dev,
0360         struct device_attribute *attr, const char *buf, size_t len)
0361 {
0362     struct zram *zram = dev_to_zram(dev);
0363     u64 val;
0364     ssize_t ret = -EINVAL;
0365 
0366     if (kstrtoull(buf, 10, &val))
0367         return ret;
0368 
0369     down_read(&zram->init_lock);
0370     spin_lock(&zram->wb_limit_lock);
0371     zram->wb_limit_enable = val;
0372     spin_unlock(&zram->wb_limit_lock);
0373     up_read(&zram->init_lock);
0374     ret = len;
0375 
0376     return ret;
0377 }
0378 
0379 static ssize_t writeback_limit_enable_show(struct device *dev,
0380         struct device_attribute *attr, char *buf)
0381 {
0382     bool val;
0383     struct zram *zram = dev_to_zram(dev);
0384 
0385     down_read(&zram->init_lock);
0386     spin_lock(&zram->wb_limit_lock);
0387     val = zram->wb_limit_enable;
0388     spin_unlock(&zram->wb_limit_lock);
0389     up_read(&zram->init_lock);
0390 
0391     return scnprintf(buf, PAGE_SIZE, "%d\n", val);
0392 }
0393 
0394 static ssize_t writeback_limit_store(struct device *dev,
0395         struct device_attribute *attr, const char *buf, size_t len)
0396 {
0397     struct zram *zram = dev_to_zram(dev);
0398     u64 val;
0399     ssize_t ret = -EINVAL;
0400 
0401     if (kstrtoull(buf, 10, &val))
0402         return ret;
0403 
0404     down_read(&zram->init_lock);
0405     spin_lock(&zram->wb_limit_lock);
0406     zram->bd_wb_limit = val;
0407     spin_unlock(&zram->wb_limit_lock);
0408     up_read(&zram->init_lock);
0409     ret = len;
0410 
0411     return ret;
0412 }
0413 
0414 static ssize_t writeback_limit_show(struct device *dev,
0415         struct device_attribute *attr, char *buf)
0416 {
0417     u64 val;
0418     struct zram *zram = dev_to_zram(dev);
0419 
0420     down_read(&zram->init_lock);
0421     spin_lock(&zram->wb_limit_lock);
0422     val = zram->bd_wb_limit;
0423     spin_unlock(&zram->wb_limit_lock);
0424     up_read(&zram->init_lock);
0425 
0426     return scnprintf(buf, PAGE_SIZE, "%llu\n", val);
0427 }
0428 
0429 static void reset_bdev(struct zram *zram)
0430 {
0431     struct block_device *bdev;
0432 
0433     if (!zram->backing_dev)
0434         return;
0435 
0436     bdev = zram->bdev;
0437     blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
0438     /* hope filp_close flush all of IO */
0439     filp_close(zram->backing_dev, NULL);
0440     zram->backing_dev = NULL;
0441     zram->bdev = NULL;
0442     zram->disk->fops = &zram_devops;
0443     kvfree(zram->bitmap);
0444     zram->bitmap = NULL;
0445 }
0446 
0447 static ssize_t backing_dev_show(struct device *dev,
0448         struct device_attribute *attr, char *buf)
0449 {
0450     struct file *file;
0451     struct zram *zram = dev_to_zram(dev);
0452     char *p;
0453     ssize_t ret;
0454 
0455     down_read(&zram->init_lock);
0456     file = zram->backing_dev;
0457     if (!file) {
0458         memcpy(buf, "none\n", 5);
0459         up_read(&zram->init_lock);
0460         return 5;
0461     }
0462 
0463     p = file_path(file, buf, PAGE_SIZE - 1);
0464     if (IS_ERR(p)) {
0465         ret = PTR_ERR(p);
0466         goto out;
0467     }
0468 
0469     ret = strlen(p);
0470     memmove(buf, p, ret);
0471     buf[ret++] = '\n';
0472 out:
0473     up_read(&zram->init_lock);
0474     return ret;
0475 }
0476 
0477 static ssize_t backing_dev_store(struct device *dev,
0478         struct device_attribute *attr, const char *buf, size_t len)
0479 {
0480     char *file_name;
0481     size_t sz;
0482     struct file *backing_dev = NULL;
0483     struct inode *inode;
0484     struct address_space *mapping;
0485     unsigned int bitmap_sz;
0486     unsigned long nr_pages, *bitmap = NULL;
0487     struct block_device *bdev = NULL;
0488     int err;
0489     struct zram *zram = dev_to_zram(dev);
0490 
0491     file_name = kmalloc(PATH_MAX, GFP_KERNEL);
0492     if (!file_name)
0493         return -ENOMEM;
0494 
0495     down_write(&zram->init_lock);
0496     if (init_done(zram)) {
0497         pr_info("Can't setup backing device for initialized device\n");
0498         err = -EBUSY;
0499         goto out;
0500     }
0501 
0502     strlcpy(file_name, buf, PATH_MAX);
0503     /* ignore trailing newline */
0504     sz = strlen(file_name);
0505     if (sz > 0 && file_name[sz - 1] == '\n')
0506         file_name[sz - 1] = 0x00;
0507 
0508     backing_dev = filp_open(file_name, O_RDWR|O_LARGEFILE, 0);
0509     if (IS_ERR(backing_dev)) {
0510         err = PTR_ERR(backing_dev);
0511         backing_dev = NULL;
0512         goto out;
0513     }
0514 
0515     mapping = backing_dev->f_mapping;
0516     inode = mapping->host;
0517 
0518     /* Support only block device in this moment */
0519     if (!S_ISBLK(inode->i_mode)) {
0520         err = -ENOTBLK;
0521         goto out;
0522     }
0523 
0524     bdev = blkdev_get_by_dev(inode->i_rdev,
0525             FMODE_READ | FMODE_WRITE | FMODE_EXCL, zram);
0526     if (IS_ERR(bdev)) {
0527         err = PTR_ERR(bdev);
0528         bdev = NULL;
0529         goto out;
0530     }
0531 
0532     nr_pages = i_size_read(inode) >> PAGE_SHIFT;
0533     bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
0534     bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
0535     if (!bitmap) {
0536         err = -ENOMEM;
0537         goto out;
0538     }
0539 
0540     reset_bdev(zram);
0541 
0542     zram->bdev = bdev;
0543     zram->backing_dev = backing_dev;
0544     zram->bitmap = bitmap;
0545     zram->nr_pages = nr_pages;
0546     /*
0547      * With writeback feature, zram does asynchronous IO so it's no longer
0548      * synchronous device so let's remove synchronous io flag. Othewise,
0549      * upper layer(e.g., swap) could wait IO completion rather than
0550      * (submit and return), which will cause system sluggish.
0551      * Furthermore, when the IO function returns(e.g., swap_readpage),
0552      * upper layer expects IO was done so it could deallocate the page
0553      * freely but in fact, IO is going on so finally could cause
0554      * use-after-free when the IO is really done.
0555      */
0556     zram->disk->fops = &zram_wb_devops;
0557     up_write(&zram->init_lock);
0558 
0559     pr_info("setup backing device %s\n", file_name);
0560     kfree(file_name);
0561 
0562     return len;
0563 out:
0564     kvfree(bitmap);
0565 
0566     if (bdev)
0567         blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
0568 
0569     if (backing_dev)
0570         filp_close(backing_dev, NULL);
0571 
0572     up_write(&zram->init_lock);
0573 
0574     kfree(file_name);
0575 
0576     return err;
0577 }
0578 
0579 static unsigned long alloc_block_bdev(struct zram *zram)
0580 {
0581     unsigned long blk_idx = 1;
0582 retry:
0583     /* skip 0 bit to confuse zram.handle = 0 */
0584     blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, blk_idx);
0585     if (blk_idx == zram->nr_pages)
0586         return 0;
0587 
0588     if (test_and_set_bit(blk_idx, zram->bitmap))
0589         goto retry;
0590 
0591     atomic64_inc(&zram->stats.bd_count);
0592     return blk_idx;
0593 }
0594 
0595 static void free_block_bdev(struct zram *zram, unsigned long blk_idx)
0596 {
0597     int was_set;
0598 
0599     was_set = test_and_clear_bit(blk_idx, zram->bitmap);
0600     WARN_ON_ONCE(!was_set);
0601     atomic64_dec(&zram->stats.bd_count);
0602 }
0603 
0604 static void zram_page_end_io(struct bio *bio)
0605 {
0606     struct page *page = bio_first_page_all(bio);
0607 
0608     page_endio(page, op_is_write(bio_op(bio)),
0609             blk_status_to_errno(bio->bi_status));
0610     bio_put(bio);
0611 }
0612 
0613 /*
0614  * Returns 1 if the submission is successful.
0615  */
0616 static int read_from_bdev_async(struct zram *zram, struct bio_vec *bvec,
0617             unsigned long entry, struct bio *parent)
0618 {
0619     struct bio *bio;
0620 
0621     bio = bio_alloc(zram->bdev, 1, parent ? parent->bi_opf : REQ_OP_READ,
0622             GFP_NOIO);
0623     if (!bio)
0624         return -ENOMEM;
0625 
0626     bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
0627     if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset)) {
0628         bio_put(bio);
0629         return -EIO;
0630     }
0631 
0632     if (!parent)
0633         bio->bi_end_io = zram_page_end_io;
0634     else
0635         bio_chain(bio, parent);
0636 
0637     submit_bio(bio);
0638     return 1;
0639 }
0640 
0641 #define PAGE_WB_SIG "page_index="
0642 
0643 #define PAGE_WRITEBACK 0
0644 #define HUGE_WRITEBACK (1<<0)
0645 #define IDLE_WRITEBACK (1<<1)
0646 
0647 
0648 static ssize_t writeback_store(struct device *dev,
0649         struct device_attribute *attr, const char *buf, size_t len)
0650 {
0651     struct zram *zram = dev_to_zram(dev);
0652     unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
0653     unsigned long index = 0;
0654     struct bio bio;
0655     struct bio_vec bio_vec;
0656     struct page *page;
0657     ssize_t ret = len;
0658     int mode, err;
0659     unsigned long blk_idx = 0;
0660 
0661     if (sysfs_streq(buf, "idle"))
0662         mode = IDLE_WRITEBACK;
0663     else if (sysfs_streq(buf, "huge"))
0664         mode = HUGE_WRITEBACK;
0665     else if (sysfs_streq(buf, "huge_idle"))
0666         mode = IDLE_WRITEBACK | HUGE_WRITEBACK;
0667     else {
0668         if (strncmp(buf, PAGE_WB_SIG, sizeof(PAGE_WB_SIG) - 1))
0669             return -EINVAL;
0670 
0671         if (kstrtol(buf + sizeof(PAGE_WB_SIG) - 1, 10, &index) ||
0672                 index >= nr_pages)
0673             return -EINVAL;
0674 
0675         nr_pages = 1;
0676         mode = PAGE_WRITEBACK;
0677     }
0678 
0679     down_read(&zram->init_lock);
0680     if (!init_done(zram)) {
0681         ret = -EINVAL;
0682         goto release_init_lock;
0683     }
0684 
0685     if (!zram->backing_dev) {
0686         ret = -ENODEV;
0687         goto release_init_lock;
0688     }
0689 
0690     page = alloc_page(GFP_KERNEL);
0691     if (!page) {
0692         ret = -ENOMEM;
0693         goto release_init_lock;
0694     }
0695 
0696     for (; nr_pages != 0; index++, nr_pages--) {
0697         struct bio_vec bvec;
0698 
0699         bvec.bv_page = page;
0700         bvec.bv_len = PAGE_SIZE;
0701         bvec.bv_offset = 0;
0702 
0703         spin_lock(&zram->wb_limit_lock);
0704         if (zram->wb_limit_enable && !zram->bd_wb_limit) {
0705             spin_unlock(&zram->wb_limit_lock);
0706             ret = -EIO;
0707             break;
0708         }
0709         spin_unlock(&zram->wb_limit_lock);
0710 
0711         if (!blk_idx) {
0712             blk_idx = alloc_block_bdev(zram);
0713             if (!blk_idx) {
0714                 ret = -ENOSPC;
0715                 break;
0716             }
0717         }
0718 
0719         zram_slot_lock(zram, index);
0720         if (!zram_allocated(zram, index))
0721             goto next;
0722 
0723         if (zram_test_flag(zram, index, ZRAM_WB) ||
0724                 zram_test_flag(zram, index, ZRAM_SAME) ||
0725                 zram_test_flag(zram, index, ZRAM_UNDER_WB))
0726             goto next;
0727 
0728         if (mode & IDLE_WRITEBACK &&
0729               !zram_test_flag(zram, index, ZRAM_IDLE))
0730             goto next;
0731         if (mode & HUGE_WRITEBACK &&
0732               !zram_test_flag(zram, index, ZRAM_HUGE))
0733             goto next;
0734         /*
0735          * Clearing ZRAM_UNDER_WB is duty of caller.
0736          * IOW, zram_free_page never clear it.
0737          */
0738         zram_set_flag(zram, index, ZRAM_UNDER_WB);
0739         /* Need for hugepage writeback racing */
0740         zram_set_flag(zram, index, ZRAM_IDLE);
0741         zram_slot_unlock(zram, index);
0742         if (zram_bvec_read(zram, &bvec, index, 0, NULL)) {
0743             zram_slot_lock(zram, index);
0744             zram_clear_flag(zram, index, ZRAM_UNDER_WB);
0745             zram_clear_flag(zram, index, ZRAM_IDLE);
0746             zram_slot_unlock(zram, index);
0747             continue;
0748         }
0749 
0750         bio_init(&bio, zram->bdev, &bio_vec, 1,
0751              REQ_OP_WRITE | REQ_SYNC);
0752         bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
0753 
0754         bio_add_page(&bio, bvec.bv_page, bvec.bv_len,
0755                 bvec.bv_offset);
0756         /*
0757          * XXX: A single page IO would be inefficient for write
0758          * but it would be not bad as starter.
0759          */
0760         err = submit_bio_wait(&bio);
0761         if (err) {
0762             zram_slot_lock(zram, index);
0763             zram_clear_flag(zram, index, ZRAM_UNDER_WB);
0764             zram_clear_flag(zram, index, ZRAM_IDLE);
0765             zram_slot_unlock(zram, index);
0766             /*
0767              * Return last IO error unless every IO were
0768              * not suceeded.
0769              */
0770             ret = err;
0771             continue;
0772         }
0773 
0774         atomic64_inc(&zram->stats.bd_writes);
0775         /*
0776          * We released zram_slot_lock so need to check if the slot was
0777          * changed. If there is freeing for the slot, we can catch it
0778          * easily by zram_allocated.
0779          * A subtle case is the slot is freed/reallocated/marked as
0780          * ZRAM_IDLE again. To close the race, idle_store doesn't
0781          * mark ZRAM_IDLE once it found the slot was ZRAM_UNDER_WB.
0782          * Thus, we could close the race by checking ZRAM_IDLE bit.
0783          */
0784         zram_slot_lock(zram, index);
0785         if (!zram_allocated(zram, index) ||
0786               !zram_test_flag(zram, index, ZRAM_IDLE)) {
0787             zram_clear_flag(zram, index, ZRAM_UNDER_WB);
0788             zram_clear_flag(zram, index, ZRAM_IDLE);
0789             goto next;
0790         }
0791 
0792         zram_free_page(zram, index);
0793         zram_clear_flag(zram, index, ZRAM_UNDER_WB);
0794         zram_set_flag(zram, index, ZRAM_WB);
0795         zram_set_element(zram, index, blk_idx);
0796         blk_idx = 0;
0797         atomic64_inc(&zram->stats.pages_stored);
0798         spin_lock(&zram->wb_limit_lock);
0799         if (zram->wb_limit_enable && zram->bd_wb_limit > 0)
0800             zram->bd_wb_limit -=  1UL << (PAGE_SHIFT - 12);
0801         spin_unlock(&zram->wb_limit_lock);
0802 next:
0803         zram_slot_unlock(zram, index);
0804     }
0805 
0806     if (blk_idx)
0807         free_block_bdev(zram, blk_idx);
0808     __free_page(page);
0809 release_init_lock:
0810     up_read(&zram->init_lock);
0811 
0812     return ret;
0813 }
0814 
0815 struct zram_work {
0816     struct work_struct work;
0817     struct zram *zram;
0818     unsigned long entry;
0819     struct bio *bio;
0820     struct bio_vec bvec;
0821 };
0822 
0823 #if PAGE_SIZE != 4096
0824 static void zram_sync_read(struct work_struct *work)
0825 {
0826     struct zram_work *zw = container_of(work, struct zram_work, work);
0827     struct zram *zram = zw->zram;
0828     unsigned long entry = zw->entry;
0829     struct bio *bio = zw->bio;
0830 
0831     read_from_bdev_async(zram, &zw->bvec, entry, bio);
0832 }
0833 
0834 /*
0835  * Block layer want one ->submit_bio to be active at a time, so if we use
0836  * chained IO with parent IO in same context, it's a deadlock. To avoid that,
0837  * use a worker thread context.
0838  */
0839 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
0840                 unsigned long entry, struct bio *bio)
0841 {
0842     struct zram_work work;
0843 
0844     work.bvec = *bvec;
0845     work.zram = zram;
0846     work.entry = entry;
0847     work.bio = bio;
0848 
0849     INIT_WORK_ONSTACK(&work.work, zram_sync_read);
0850     queue_work(system_unbound_wq, &work.work);
0851     flush_work(&work.work);
0852     destroy_work_on_stack(&work.work);
0853 
0854     return 1;
0855 }
0856 #else
0857 static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
0858                 unsigned long entry, struct bio *bio)
0859 {
0860     WARN_ON(1);
0861     return -EIO;
0862 }
0863 #endif
0864 
0865 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
0866             unsigned long entry, struct bio *parent, bool sync)
0867 {
0868     atomic64_inc(&zram->stats.bd_reads);
0869     if (sync)
0870         return read_from_bdev_sync(zram, bvec, entry, parent);
0871     else
0872         return read_from_bdev_async(zram, bvec, entry, parent);
0873 }
0874 #else
0875 static inline void reset_bdev(struct zram *zram) {};
0876 static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
0877             unsigned long entry, struct bio *parent, bool sync)
0878 {
0879     return -EIO;
0880 }
0881 
0882 static void free_block_bdev(struct zram *zram, unsigned long blk_idx) {};
0883 #endif
0884 
0885 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
0886 
0887 static struct dentry *zram_debugfs_root;
0888 
0889 static void zram_debugfs_create(void)
0890 {
0891     zram_debugfs_root = debugfs_create_dir("zram", NULL);
0892 }
0893 
0894 static void zram_debugfs_destroy(void)
0895 {
0896     debugfs_remove_recursive(zram_debugfs_root);
0897 }
0898 
0899 static void zram_accessed(struct zram *zram, u32 index)
0900 {
0901     zram_clear_flag(zram, index, ZRAM_IDLE);
0902     zram->table[index].ac_time = ktime_get_boottime();
0903 }
0904 
0905 static ssize_t read_block_state(struct file *file, char __user *buf,
0906                 size_t count, loff_t *ppos)
0907 {
0908     char *kbuf;
0909     ssize_t index, written = 0;
0910     struct zram *zram = file->private_data;
0911     unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
0912     struct timespec64 ts;
0913 
0914     kbuf = kvmalloc(count, GFP_KERNEL);
0915     if (!kbuf)
0916         return -ENOMEM;
0917 
0918     down_read(&zram->init_lock);
0919     if (!init_done(zram)) {
0920         up_read(&zram->init_lock);
0921         kvfree(kbuf);
0922         return -EINVAL;
0923     }
0924 
0925     for (index = *ppos; index < nr_pages; index++) {
0926         int copied;
0927 
0928         zram_slot_lock(zram, index);
0929         if (!zram_allocated(zram, index))
0930             goto next;
0931 
0932         ts = ktime_to_timespec64(zram->table[index].ac_time);
0933         copied = snprintf(kbuf + written, count,
0934             "%12zd %12lld.%06lu %c%c%c%c\n",
0935             index, (s64)ts.tv_sec,
0936             ts.tv_nsec / NSEC_PER_USEC,
0937             zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
0938             zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
0939             zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
0940             zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.');
0941 
0942         if (count <= copied) {
0943             zram_slot_unlock(zram, index);
0944             break;
0945         }
0946         written += copied;
0947         count -= copied;
0948 next:
0949         zram_slot_unlock(zram, index);
0950         *ppos += 1;
0951     }
0952 
0953     up_read(&zram->init_lock);
0954     if (copy_to_user(buf, kbuf, written))
0955         written = -EFAULT;
0956     kvfree(kbuf);
0957 
0958     return written;
0959 }
0960 
0961 static const struct file_operations proc_zram_block_state_op = {
0962     .open = simple_open,
0963     .read = read_block_state,
0964     .llseek = default_llseek,
0965 };
0966 
0967 static void zram_debugfs_register(struct zram *zram)
0968 {
0969     if (!zram_debugfs_root)
0970         return;
0971 
0972     zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
0973                         zram_debugfs_root);
0974     debugfs_create_file("block_state", 0400, zram->debugfs_dir,
0975                 zram, &proc_zram_block_state_op);
0976 }
0977 
0978 static void zram_debugfs_unregister(struct zram *zram)
0979 {
0980     debugfs_remove_recursive(zram->debugfs_dir);
0981 }
0982 #else
0983 static void zram_debugfs_create(void) {};
0984 static void zram_debugfs_destroy(void) {};
0985 static void zram_accessed(struct zram *zram, u32 index)
0986 {
0987     zram_clear_flag(zram, index, ZRAM_IDLE);
0988 };
0989 static void zram_debugfs_register(struct zram *zram) {};
0990 static void zram_debugfs_unregister(struct zram *zram) {};
0991 #endif
0992 
0993 /*
0994  * We switched to per-cpu streams and this attr is not needed anymore.
0995  * However, we will keep it around for some time, because:
0996  * a) we may revert per-cpu streams in the future
0997  * b) it's visible to user space and we need to follow our 2 years
0998  *    retirement rule; but we already have a number of 'soon to be
0999  *    altered' attrs, so max_comp_streams need to wait for the next
1000  *    layoff cycle.
1001  */
1002 static ssize_t max_comp_streams_show(struct device *dev,
1003         struct device_attribute *attr, char *buf)
1004 {
1005     return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
1006 }
1007 
1008 static ssize_t max_comp_streams_store(struct device *dev,
1009         struct device_attribute *attr, const char *buf, size_t len)
1010 {
1011     return len;
1012 }
1013 
1014 static ssize_t comp_algorithm_show(struct device *dev,
1015         struct device_attribute *attr, char *buf)
1016 {
1017     size_t sz;
1018     struct zram *zram = dev_to_zram(dev);
1019 
1020     down_read(&zram->init_lock);
1021     sz = zcomp_available_show(zram->compressor, buf);
1022     up_read(&zram->init_lock);
1023 
1024     return sz;
1025 }
1026 
1027 static ssize_t comp_algorithm_store(struct device *dev,
1028         struct device_attribute *attr, const char *buf, size_t len)
1029 {
1030     struct zram *zram = dev_to_zram(dev);
1031     char compressor[ARRAY_SIZE(zram->compressor)];
1032     size_t sz;
1033 
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;
1039 
1040     if (!zcomp_available_algorithm(compressor))
1041         return -EINVAL;
1042 
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");
1047         return -EBUSY;
1048     }
1049 
1050     strcpy(zram->compressor, compressor);
1051     up_write(&zram->init_lock);
1052     return len;
1053 }
1054 
1055 static ssize_t compact_store(struct device *dev,
1056         struct device_attribute *attr, const char *buf, size_t len)
1057 {
1058     struct zram *zram = dev_to_zram(dev);
1059 
1060     down_read(&zram->init_lock);
1061     if (!init_done(zram)) {
1062         up_read(&zram->init_lock);
1063         return -EINVAL;
1064     }
1065 
1066     zs_compact(zram->mem_pool);
1067     up_read(&zram->init_lock);
1068 
1069     return len;
1070 }
1071 
1072 static ssize_t io_stat_show(struct device *dev,
1073         struct device_attribute *attr, char *buf)
1074 {
1075     struct zram *zram = dev_to_zram(dev);
1076     ssize_t ret;
1077 
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);
1086 
1087     return ret;
1088 }
1089 
1090 static ssize_t mm_stat_show(struct device *dev,
1091         struct device_attribute *attr, char *buf)
1092 {
1093     struct zram *zram = dev_to_zram(dev);
1094     struct zs_pool_stats pool_stats;
1095     u64 orig_size, mem_used = 0;
1096     long max_used;
1097     ssize_t ret;
1098 
1099     memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1100 
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);
1105     }
1106 
1107     orig_size = atomic64_read(&zram->stats.pages_stored);
1108     max_used = atomic_long_read(&zram->stats.max_used_pages);
1109 
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);
1122 
1123     return ret;
1124 }
1125 
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)
1130 {
1131     struct zram *zram = dev_to_zram(dev);
1132     ssize_t ret;
1133 
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);
1141 
1142     return ret;
1143 }
1144 #endif
1145 
1146 static ssize_t debug_stat_show(struct device *dev,
1147         struct device_attribute *attr, char *buf)
1148 {
1149     int version = 1;
1150     struct zram *zram = dev_to_zram(dev);
1151     ssize_t ret;
1152 
1153     down_read(&zram->init_lock);
1154     ret = scnprintf(buf, PAGE_SIZE,
1155             "version: %d\n%8llu %8llu\n",
1156             version,
1157             (u64)atomic64_read(&zram->stats.writestall),
1158             (u64)atomic64_read(&zram->stats.miss_free));
1159     up_read(&zram->init_lock);
1160 
1161     return ret;
1162 }
1163 
1164 static DEVICE_ATTR_RO(io_stat);
1165 static DEVICE_ATTR_RO(mm_stat);
1166 #ifdef CONFIG_ZRAM_WRITEBACK
1167 static DEVICE_ATTR_RO(bd_stat);
1168 #endif
1169 static DEVICE_ATTR_RO(debug_stat);
1170 
1171 static void zram_meta_free(struct zram *zram, u64 disksize)
1172 {
1173     size_t num_pages = disksize >> PAGE_SHIFT;
1174     size_t index;
1175 
1176     /* Free all pages that are still in this zram device */
1177     for (index = 0; index < num_pages; index++)
1178         zram_free_page(zram, index);
1179 
1180     zs_destroy_pool(zram->mem_pool);
1181     vfree(zram->table);
1182 }
1183 
1184 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
1185 {
1186     size_t num_pages;
1187 
1188     num_pages = disksize >> PAGE_SHIFT;
1189     zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
1190     if (!zram->table)
1191         return false;
1192 
1193     zram->mem_pool = zs_create_pool(zram->disk->disk_name);
1194     if (!zram->mem_pool) {
1195         vfree(zram->table);
1196         return false;
1197     }
1198 
1199     if (!huge_class_size)
1200         huge_class_size = zs_huge_class_size(zram->mem_pool);
1201     return true;
1202 }
1203 
1204 /*
1205  * To protect concurrent access to the same index entry,
1206  * caller should hold this table index entry's bit_spinlock to
1207  * indicate this index entry is accessing.
1208  */
1209 static void zram_free_page(struct zram *zram, size_t index)
1210 {
1211     unsigned long handle;
1212 
1213 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
1214     zram->table[index].ac_time = 0;
1215 #endif
1216     if (zram_test_flag(zram, index, ZRAM_IDLE))
1217         zram_clear_flag(zram, index, ZRAM_IDLE);
1218 
1219     if (zram_test_flag(zram, index, ZRAM_HUGE)) {
1220         zram_clear_flag(zram, index, ZRAM_HUGE);
1221         atomic64_dec(&zram->stats.huge_pages);
1222     }
1223 
1224     if (zram_test_flag(zram, index, ZRAM_WB)) {
1225         zram_clear_flag(zram, index, ZRAM_WB);
1226         free_block_bdev(zram, zram_get_element(zram, index));
1227         goto out;
1228     }
1229 
1230     /*
1231      * No memory is allocated for same element filled pages.
1232      * Simply clear same page flag.
1233      */
1234     if (zram_test_flag(zram, index, ZRAM_SAME)) {
1235         zram_clear_flag(zram, index, ZRAM_SAME);
1236         atomic64_dec(&zram->stats.same_pages);
1237         goto out;
1238     }
1239 
1240     handle = zram_get_handle(zram, index);
1241     if (!handle)
1242         return;
1243 
1244     zs_free(zram->mem_pool, handle);
1245 
1246     atomic64_sub(zram_get_obj_size(zram, index),
1247             &zram->stats.compr_data_size);
1248 out:
1249     atomic64_dec(&zram->stats.pages_stored);
1250     zram_set_handle(zram, index, 0);
1251     zram_set_obj_size(zram, index, 0);
1252     WARN_ON_ONCE(zram->table[index].flags &
1253         ~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB));
1254 }
1255 
1256 static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index,
1257                 struct bio *bio, bool partial_io)
1258 {
1259     struct zcomp_strm *zstrm;
1260     unsigned long handle;
1261     unsigned int size;
1262     void *src, *dst;
1263     int ret;
1264 
1265     zram_slot_lock(zram, index);
1266     if (zram_test_flag(zram, index, ZRAM_WB)) {
1267         struct bio_vec bvec;
1268 
1269         zram_slot_unlock(zram, index);
1270 
1271         bvec.bv_page = page;
1272         bvec.bv_len = PAGE_SIZE;
1273         bvec.bv_offset = 0;
1274         return read_from_bdev(zram, &bvec,
1275                 zram_get_element(zram, index),
1276                 bio, partial_io);
1277     }
1278 
1279     handle = zram_get_handle(zram, index);
1280     if (!handle || zram_test_flag(zram, index, ZRAM_SAME)) {
1281         unsigned long value;
1282         void *mem;
1283 
1284         value = handle ? zram_get_element(zram, index) : 0;
1285         mem = kmap_atomic(page);
1286         zram_fill_page(mem, PAGE_SIZE, value);
1287         kunmap_atomic(mem);
1288         zram_slot_unlock(zram, index);
1289         return 0;
1290     }
1291 
1292     size = zram_get_obj_size(zram, index);
1293 
1294     if (size != PAGE_SIZE)
1295         zstrm = zcomp_stream_get(zram->comp);
1296 
1297     src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
1298     if (size == PAGE_SIZE) {
1299         dst = kmap_atomic(page);
1300         memcpy(dst, src, PAGE_SIZE);
1301         kunmap_atomic(dst);
1302         ret = 0;
1303     } else {
1304         dst = kmap_atomic(page);
1305         ret = zcomp_decompress(zstrm, src, size, dst);
1306         kunmap_atomic(dst);
1307         zcomp_stream_put(zram->comp);
1308     }
1309     zs_unmap_object(zram->mem_pool, handle);
1310     zram_slot_unlock(zram, index);
1311 
1312     /* Should NEVER happen. Return bio error if it does. */
1313     if (WARN_ON(ret))
1314         pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1315 
1316     return ret;
1317 }
1318 
1319 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1320                 u32 index, int offset, struct bio *bio)
1321 {
1322     int ret;
1323     struct page *page;
1324 
1325     page = bvec->bv_page;
1326     if (is_partial_io(bvec)) {
1327         /* Use a temporary buffer to decompress the page */
1328         page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1329         if (!page)
1330             return -ENOMEM;
1331     }
1332 
1333     ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec));
1334     if (unlikely(ret))
1335         goto out;
1336 
1337     if (is_partial_io(bvec)) {
1338         void *src = kmap_atomic(page);
1339 
1340         memcpy_to_bvec(bvec, src + offset);
1341         kunmap_atomic(src);
1342     }
1343 out:
1344     if (is_partial_io(bvec))
1345         __free_page(page);
1346 
1347     return ret;
1348 }
1349 
1350 static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1351                 u32 index, struct bio *bio)
1352 {
1353     int ret = 0;
1354     unsigned long alloced_pages;
1355     unsigned long handle = -ENOMEM;
1356     unsigned int comp_len = 0;
1357     void *src, *dst, *mem;
1358     struct zcomp_strm *zstrm;
1359     struct page *page = bvec->bv_page;
1360     unsigned long element = 0;
1361     enum zram_pageflags flags = 0;
1362 
1363     mem = kmap_atomic(page);
1364     if (page_same_filled(mem, &element)) {
1365         kunmap_atomic(mem);
1366         /* Free memory associated with this sector now. */
1367         flags = ZRAM_SAME;
1368         atomic64_inc(&zram->stats.same_pages);
1369         goto out;
1370     }
1371     kunmap_atomic(mem);
1372 
1373 compress_again:
1374     zstrm = zcomp_stream_get(zram->comp);
1375     src = kmap_atomic(page);
1376     ret = zcomp_compress(zstrm, src, &comp_len);
1377     kunmap_atomic(src);
1378 
1379     if (unlikely(ret)) {
1380         zcomp_stream_put(zram->comp);
1381         pr_err("Compression failed! err=%d\n", ret);
1382         zs_free(zram->mem_pool, handle);
1383         return ret;
1384     }
1385 
1386     if (comp_len >= huge_class_size)
1387         comp_len = PAGE_SIZE;
1388     /*
1389      * handle allocation has 2 paths:
1390      * a) fast path is executed with preemption disabled (for
1391      *  per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
1392      *  since we can't sleep;
1393      * b) slow path enables preemption and attempts to allocate
1394      *  the page with __GFP_DIRECT_RECLAIM bit set. we have to
1395      *  put per-cpu compression stream and, thus, to re-do
1396      *  the compression once handle is allocated.
1397      *
1398      * if we have a 'non-null' handle here then we are coming
1399      * from the slow path and handle has already been allocated.
1400      */
1401     if (IS_ERR((void *)handle))
1402         handle = zs_malloc(zram->mem_pool, comp_len,
1403                 __GFP_KSWAPD_RECLAIM |
1404                 __GFP_NOWARN |
1405                 __GFP_HIGHMEM |
1406                 __GFP_MOVABLE);
1407     if (IS_ERR((void *)handle)) {
1408         zcomp_stream_put(zram->comp);
1409         atomic64_inc(&zram->stats.writestall);
1410         handle = zs_malloc(zram->mem_pool, comp_len,
1411                 GFP_NOIO | __GFP_HIGHMEM |
1412                 __GFP_MOVABLE);
1413         if (!IS_ERR((void *)handle))
1414             goto compress_again;
1415         return PTR_ERR((void *)handle);
1416     }
1417 
1418     alloced_pages = zs_get_total_pages(zram->mem_pool);
1419     update_used_max(zram, alloced_pages);
1420 
1421     if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1422         zcomp_stream_put(zram->comp);
1423         zs_free(zram->mem_pool, handle);
1424         return -ENOMEM;
1425     }
1426 
1427     dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1428 
1429     src = zstrm->buffer;
1430     if (comp_len == PAGE_SIZE)
1431         src = kmap_atomic(page);
1432     memcpy(dst, src, comp_len);
1433     if (comp_len == PAGE_SIZE)
1434         kunmap_atomic(src);
1435 
1436     zcomp_stream_put(zram->comp);
1437     zs_unmap_object(zram->mem_pool, handle);
1438     atomic64_add(comp_len, &zram->stats.compr_data_size);
1439 out:
1440     /*
1441      * Free memory associated with this sector
1442      * before overwriting unused sectors.
1443      */
1444     zram_slot_lock(zram, index);
1445     zram_free_page(zram, index);
1446 
1447     if (comp_len == PAGE_SIZE) {
1448         zram_set_flag(zram, index, ZRAM_HUGE);
1449         atomic64_inc(&zram->stats.huge_pages);
1450         atomic64_inc(&zram->stats.huge_pages_since);
1451     }
1452 
1453     if (flags) {
1454         zram_set_flag(zram, index, flags);
1455         zram_set_element(zram, index, element);
1456     }  else {
1457         zram_set_handle(zram, index, handle);
1458         zram_set_obj_size(zram, index, comp_len);
1459     }
1460     zram_slot_unlock(zram, index);
1461 
1462     /* Update stats */
1463     atomic64_inc(&zram->stats.pages_stored);
1464     return ret;
1465 }
1466 
1467 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1468                 u32 index, int offset, struct bio *bio)
1469 {
1470     int ret;
1471     struct page *page = NULL;
1472     struct bio_vec vec;
1473 
1474     vec = *bvec;
1475     if (is_partial_io(bvec)) {
1476         void *dst;
1477         /*
1478          * This is a partial IO. We need to read the full page
1479          * before to write the changes.
1480          */
1481         page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
1482         if (!page)
1483             return -ENOMEM;
1484 
1485         ret = __zram_bvec_read(zram, page, index, bio, true);
1486         if (ret)
1487             goto out;
1488 
1489         dst = kmap_atomic(page);
1490         memcpy_from_bvec(dst + offset, bvec);
1491         kunmap_atomic(dst);
1492 
1493         vec.bv_page = page;
1494         vec.bv_len = PAGE_SIZE;
1495         vec.bv_offset = 0;
1496     }
1497 
1498     ret = __zram_bvec_write(zram, &vec, index, bio);
1499 out:
1500     if (is_partial_io(bvec))
1501         __free_page(page);
1502     return ret;
1503 }
1504 
1505 /*
1506  * zram_bio_discard - handler on discard request
1507  * @index: physical block index in PAGE_SIZE units
1508  * @offset: byte offset within physical block
1509  */
1510 static void zram_bio_discard(struct zram *zram, u32 index,
1511                  int offset, struct bio *bio)
1512 {
1513     size_t n = bio->bi_iter.bi_size;
1514 
1515     /*
1516      * zram manages data in physical block size units. Because logical block
1517      * size isn't identical with physical block size on some arch, we
1518      * could get a discard request pointing to a specific offset within a
1519      * certain physical block.  Although we can handle this request by
1520      * reading that physiclal block and decompressing and partially zeroing
1521      * and re-compressing and then re-storing it, this isn't reasonable
1522      * because our intent with a discard request is to save memory.  So
1523      * skipping this logical block is appropriate here.
1524      */
1525     if (offset) {
1526         if (n <= (PAGE_SIZE - offset))
1527             return;
1528 
1529         n -= (PAGE_SIZE - offset);
1530         index++;
1531     }
1532 
1533     while (n >= PAGE_SIZE) {
1534         zram_slot_lock(zram, index);
1535         zram_free_page(zram, index);
1536         zram_slot_unlock(zram, index);
1537         atomic64_inc(&zram->stats.notify_free);
1538         index++;
1539         n -= PAGE_SIZE;
1540     }
1541 }
1542 
1543 /*
1544  * Returns errno if it has some problem. Otherwise return 0 or 1.
1545  * Returns 0 if IO request was done synchronously
1546  * Returns 1 if IO request was successfully submitted.
1547  */
1548 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
1549             int offset, enum req_op op, struct bio *bio)
1550 {
1551     int ret;
1552 
1553     if (!op_is_write(op)) {
1554         atomic64_inc(&zram->stats.num_reads);
1555         ret = zram_bvec_read(zram, bvec, index, offset, bio);
1556         flush_dcache_page(bvec->bv_page);
1557     } else {
1558         atomic64_inc(&zram->stats.num_writes);
1559         ret = zram_bvec_write(zram, bvec, index, offset, bio);
1560     }
1561 
1562     zram_slot_lock(zram, index);
1563     zram_accessed(zram, index);
1564     zram_slot_unlock(zram, index);
1565 
1566     if (unlikely(ret < 0)) {
1567         if (!op_is_write(op))
1568             atomic64_inc(&zram->stats.failed_reads);
1569         else
1570             atomic64_inc(&zram->stats.failed_writes);
1571     }
1572 
1573     return ret;
1574 }
1575 
1576 static void __zram_make_request(struct zram *zram, struct bio *bio)
1577 {
1578     int offset;
1579     u32 index;
1580     struct bio_vec bvec;
1581     struct bvec_iter iter;
1582     unsigned long start_time;
1583 
1584     index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1585     offset = (bio->bi_iter.bi_sector &
1586           (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1587 
1588     switch (bio_op(bio)) {
1589     case REQ_OP_DISCARD:
1590     case REQ_OP_WRITE_ZEROES:
1591         zram_bio_discard(zram, index, offset, bio);
1592         bio_endio(bio);
1593         return;
1594     default:
1595         break;
1596     }
1597 
1598     start_time = bio_start_io_acct(bio);
1599     bio_for_each_segment(bvec, bio, iter) {
1600         struct bio_vec bv = bvec;
1601         unsigned int unwritten = bvec.bv_len;
1602 
1603         do {
1604             bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
1605                             unwritten);
1606             if (zram_bvec_rw(zram, &bv, index, offset,
1607                      bio_op(bio), bio) < 0) {
1608                 bio->bi_status = BLK_STS_IOERR;
1609                 break;
1610             }
1611 
1612             bv.bv_offset += bv.bv_len;
1613             unwritten -= bv.bv_len;
1614 
1615             update_position(&index, &offset, &bv);
1616         } while (unwritten);
1617     }
1618     bio_end_io_acct(bio, start_time);
1619     bio_endio(bio);
1620 }
1621 
1622 /*
1623  * Handler function for all zram I/O requests.
1624  */
1625 static void zram_submit_bio(struct bio *bio)
1626 {
1627     struct zram *zram = bio->bi_bdev->bd_disk->private_data;
1628 
1629     if (!valid_io_request(zram, bio->bi_iter.bi_sector,
1630                     bio->bi_iter.bi_size)) {
1631         atomic64_inc(&zram->stats.invalid_io);
1632         bio_io_error(bio);
1633         return;
1634     }
1635 
1636     __zram_make_request(zram, bio);
1637 }
1638 
1639 static void zram_slot_free_notify(struct block_device *bdev,
1640                 unsigned long index)
1641 {
1642     struct zram *zram;
1643 
1644     zram = bdev->bd_disk->private_data;
1645 
1646     atomic64_inc(&zram->stats.notify_free);
1647     if (!zram_slot_trylock(zram, index)) {
1648         atomic64_inc(&zram->stats.miss_free);
1649         return;
1650     }
1651 
1652     zram_free_page(zram, index);
1653     zram_slot_unlock(zram, index);
1654 }
1655 
1656 static int zram_rw_page(struct block_device *bdev, sector_t sector,
1657                struct page *page, enum req_op op)
1658 {
1659     int offset, ret;
1660     u32 index;
1661     struct zram *zram;
1662     struct bio_vec bv;
1663     unsigned long start_time;
1664 
1665     if (PageTransHuge(page))
1666         return -ENOTSUPP;
1667     zram = bdev->bd_disk->private_data;
1668 
1669     if (!valid_io_request(zram, sector, PAGE_SIZE)) {
1670         atomic64_inc(&zram->stats.invalid_io);
1671         ret = -EINVAL;
1672         goto out;
1673     }
1674 
1675     index = sector >> SECTORS_PER_PAGE_SHIFT;
1676     offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
1677 
1678     bv.bv_page = page;
1679     bv.bv_len = PAGE_SIZE;
1680     bv.bv_offset = 0;
1681 
1682     start_time = bdev_start_io_acct(bdev->bd_disk->part0,
1683             SECTORS_PER_PAGE, op, jiffies);
1684     ret = zram_bvec_rw(zram, &bv, index, offset, op, NULL);
1685     bdev_end_io_acct(bdev->bd_disk->part0, op, start_time);
1686 out:
1687     /*
1688      * If I/O fails, just return error(ie, non-zero) without
1689      * calling page_endio.
1690      * It causes resubmit the I/O with bio request by upper functions
1691      * of rw_page(e.g., swap_readpage, __swap_writepage) and
1692      * bio->bi_end_io does things to handle the error
1693      * (e.g., SetPageError, set_page_dirty and extra works).
1694      */
1695     if (unlikely(ret < 0))
1696         return ret;
1697 
1698     switch (ret) {
1699     case 0:
1700         page_endio(page, op_is_write(op), 0);
1701         break;
1702     case 1:
1703         ret = 0;
1704         break;
1705     default:
1706         WARN_ON(1);
1707     }
1708     return ret;
1709 }
1710 
1711 static void zram_reset_device(struct zram *zram)
1712 {
1713     struct zcomp *comp;
1714     u64 disksize;
1715 
1716     down_write(&zram->init_lock);
1717 
1718     zram->limit_pages = 0;
1719 
1720     if (!init_done(zram)) {
1721         up_write(&zram->init_lock);
1722         return;
1723     }
1724 
1725     comp = zram->comp;
1726     disksize = zram->disksize;
1727     zram->disksize = 0;
1728 
1729     set_capacity_and_notify(zram->disk, 0);
1730     part_stat_set_all(zram->disk->part0, 0);
1731 
1732     /* I/O operation under all of CPU are done so let's free */
1733     zram_meta_free(zram, disksize);
1734     memset(&zram->stats, 0, sizeof(zram->stats));
1735     zcomp_destroy(comp);
1736     reset_bdev(zram);
1737 
1738     up_write(&zram->init_lock);
1739 }
1740 
1741 static ssize_t disksize_store(struct device *dev,
1742         struct device_attribute *attr, const char *buf, size_t len)
1743 {
1744     u64 disksize;
1745     struct zcomp *comp;
1746     struct zram *zram = dev_to_zram(dev);
1747     int err;
1748 
1749     disksize = memparse(buf, NULL);
1750     if (!disksize)
1751         return -EINVAL;
1752 
1753     down_write(&zram->init_lock);
1754     if (init_done(zram)) {
1755         pr_info("Cannot change disksize for initialized device\n");
1756         err = -EBUSY;
1757         goto out_unlock;
1758     }
1759 
1760     disksize = PAGE_ALIGN(disksize);
1761     if (!zram_meta_alloc(zram, disksize)) {
1762         err = -ENOMEM;
1763         goto out_unlock;
1764     }
1765 
1766     comp = zcomp_create(zram->compressor);
1767     if (IS_ERR(comp)) {
1768         pr_err("Cannot initialise %s compressing backend\n",
1769                 zram->compressor);
1770         err = PTR_ERR(comp);
1771         goto out_free_meta;
1772     }
1773 
1774     zram->comp = comp;
1775     zram->disksize = disksize;
1776     set_capacity_and_notify(zram->disk, zram->disksize >> SECTOR_SHIFT);
1777     up_write(&zram->init_lock);
1778 
1779     return len;
1780 
1781 out_free_meta:
1782     zram_meta_free(zram, disksize);
1783 out_unlock:
1784     up_write(&zram->init_lock);
1785     return err;
1786 }
1787 
1788 static ssize_t reset_store(struct device *dev,
1789         struct device_attribute *attr, const char *buf, size_t len)
1790 {
1791     int ret;
1792     unsigned short do_reset;
1793     struct zram *zram;
1794     struct gendisk *disk;
1795 
1796     ret = kstrtou16(buf, 10, &do_reset);
1797     if (ret)
1798         return ret;
1799 
1800     if (!do_reset)
1801         return -EINVAL;
1802 
1803     zram = dev_to_zram(dev);
1804     disk = zram->disk;
1805 
1806     mutex_lock(&disk->open_mutex);
1807     /* Do not reset an active device or claimed device */
1808     if (disk_openers(disk) || zram->claim) {
1809         mutex_unlock(&disk->open_mutex);
1810         return -EBUSY;
1811     }
1812 
1813     /* From now on, anyone can't open /dev/zram[0-9] */
1814     zram->claim = true;
1815     mutex_unlock(&disk->open_mutex);
1816 
1817     /* Make sure all the pending I/O are finished */
1818     sync_blockdev(disk->part0);
1819     zram_reset_device(zram);
1820 
1821     mutex_lock(&disk->open_mutex);
1822     zram->claim = false;
1823     mutex_unlock(&disk->open_mutex);
1824 
1825     return len;
1826 }
1827 
1828 static int zram_open(struct block_device *bdev, fmode_t mode)
1829 {
1830     int ret = 0;
1831     struct zram *zram;
1832 
1833     WARN_ON(!mutex_is_locked(&bdev->bd_disk->open_mutex));
1834 
1835     zram = bdev->bd_disk->private_data;
1836     /* zram was claimed to reset so open request fails */
1837     if (zram->claim)
1838         ret = -EBUSY;
1839 
1840     return ret;
1841 }
1842 
1843 static const struct block_device_operations zram_devops = {
1844     .open = zram_open,
1845     .submit_bio = zram_submit_bio,
1846     .swap_slot_free_notify = zram_slot_free_notify,
1847     .rw_page = zram_rw_page,
1848     .owner = THIS_MODULE
1849 };
1850 
1851 #ifdef CONFIG_ZRAM_WRITEBACK
1852 static const struct block_device_operations zram_wb_devops = {
1853     .open = zram_open,
1854     .submit_bio = zram_submit_bio,
1855     .swap_slot_free_notify = zram_slot_free_notify,
1856     .owner = THIS_MODULE
1857 };
1858 #endif
1859 
1860 static DEVICE_ATTR_WO(compact);
1861 static DEVICE_ATTR_RW(disksize);
1862 static DEVICE_ATTR_RO(initstate);
1863 static DEVICE_ATTR_WO(reset);
1864 static DEVICE_ATTR_WO(mem_limit);
1865 static DEVICE_ATTR_WO(mem_used_max);
1866 static DEVICE_ATTR_WO(idle);
1867 static DEVICE_ATTR_RW(max_comp_streams);
1868 static DEVICE_ATTR_RW(comp_algorithm);
1869 #ifdef CONFIG_ZRAM_WRITEBACK
1870 static DEVICE_ATTR_RW(backing_dev);
1871 static DEVICE_ATTR_WO(writeback);
1872 static DEVICE_ATTR_RW(writeback_limit);
1873 static DEVICE_ATTR_RW(writeback_limit_enable);
1874 #endif
1875 
1876 static struct attribute *zram_disk_attrs[] = {
1877     &dev_attr_disksize.attr,
1878     &dev_attr_initstate.attr,
1879     &dev_attr_reset.attr,
1880     &dev_attr_compact.attr,
1881     &dev_attr_mem_limit.attr,
1882     &dev_attr_mem_used_max.attr,
1883     &dev_attr_idle.attr,
1884     &dev_attr_max_comp_streams.attr,
1885     &dev_attr_comp_algorithm.attr,
1886 #ifdef CONFIG_ZRAM_WRITEBACK
1887     &dev_attr_backing_dev.attr,
1888     &dev_attr_writeback.attr,
1889     &dev_attr_writeback_limit.attr,
1890     &dev_attr_writeback_limit_enable.attr,
1891 #endif
1892     &dev_attr_io_stat.attr,
1893     &dev_attr_mm_stat.attr,
1894 #ifdef CONFIG_ZRAM_WRITEBACK
1895     &dev_attr_bd_stat.attr,
1896 #endif
1897     &dev_attr_debug_stat.attr,
1898     NULL,
1899 };
1900 
1901 ATTRIBUTE_GROUPS(zram_disk);
1902 
1903 /*
1904  * Allocate and initialize new zram device. the function returns
1905  * '>= 0' device_id upon success, and negative value otherwise.
1906  */
1907 static int zram_add(void)
1908 {
1909     struct zram *zram;
1910     int ret, device_id;
1911 
1912     zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1913     if (!zram)
1914         return -ENOMEM;
1915 
1916     ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1917     if (ret < 0)
1918         goto out_free_dev;
1919     device_id = ret;
1920 
1921     init_rwsem(&zram->init_lock);
1922 #ifdef CONFIG_ZRAM_WRITEBACK
1923     spin_lock_init(&zram->wb_limit_lock);
1924 #endif
1925 
1926     /* gendisk structure */
1927     zram->disk = blk_alloc_disk(NUMA_NO_NODE);
1928     if (!zram->disk) {
1929         pr_err("Error allocating disk structure for device %d\n",
1930             device_id);
1931         ret = -ENOMEM;
1932         goto out_free_idr;
1933     }
1934 
1935     zram->disk->major = zram_major;
1936     zram->disk->first_minor = device_id;
1937     zram->disk->minors = 1;
1938     zram->disk->flags |= GENHD_FL_NO_PART;
1939     zram->disk->fops = &zram_devops;
1940     zram->disk->private_data = zram;
1941     snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1942 
1943     /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1944     set_capacity(zram->disk, 0);
1945     /* zram devices sort of resembles non-rotational disks */
1946     blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
1947     blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1948 
1949     /*
1950      * To ensure that we always get PAGE_SIZE aligned
1951      * and n*PAGE_SIZED sized I/O requests.
1952      */
1953     blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1954     blk_queue_logical_block_size(zram->disk->queue,
1955                     ZRAM_LOGICAL_BLOCK_SIZE);
1956     blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1957     blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1958     zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1959     blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1960 
1961     /*
1962      * zram_bio_discard() will clear all logical blocks if logical block
1963      * size is identical with physical block size(PAGE_SIZE). But if it is
1964      * different, we will skip discarding some parts of logical blocks in
1965      * the part of the request range which isn't aligned to physical block
1966      * size.  So we can't ensure that all discarded logical blocks are
1967      * zeroed.
1968      */
1969     if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1970         blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
1971 
1972     blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, zram->disk->queue);
1973     ret = device_add_disk(NULL, zram->disk, zram_disk_groups);
1974     if (ret)
1975         goto out_cleanup_disk;
1976 
1977     strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1978 
1979     zram_debugfs_register(zram);
1980     pr_info("Added device: %s\n", zram->disk->disk_name);
1981     return device_id;
1982 
1983 out_cleanup_disk:
1984     put_disk(zram->disk);
1985 out_free_idr:
1986     idr_remove(&zram_index_idr, device_id);
1987 out_free_dev:
1988     kfree(zram);
1989     return ret;
1990 }
1991 
1992 static int zram_remove(struct zram *zram)
1993 {
1994     bool claimed;
1995 
1996     mutex_lock(&zram->disk->open_mutex);
1997     if (disk_openers(zram->disk)) {
1998         mutex_unlock(&zram->disk->open_mutex);
1999         return -EBUSY;
2000     }
2001 
2002     claimed = zram->claim;
2003     if (!claimed)
2004         zram->claim = true;
2005     mutex_unlock(&zram->disk->open_mutex);
2006 
2007     zram_debugfs_unregister(zram);
2008 
2009     if (claimed) {
2010         /*
2011          * If we were claimed by reset_store(), del_gendisk() will
2012          * wait until reset_store() is done, so nothing need to do.
2013          */
2014         ;
2015     } else {
2016         /* Make sure all the pending I/O are finished */
2017         sync_blockdev(zram->disk->part0);
2018         zram_reset_device(zram);
2019     }
2020 
2021     pr_info("Removed device: %s\n", zram->disk->disk_name);
2022 
2023     del_gendisk(zram->disk);
2024 
2025     /* del_gendisk drains pending reset_store */
2026     WARN_ON_ONCE(claimed && zram->claim);
2027 
2028     /*
2029      * disksize_store() may be called in between zram_reset_device()
2030      * and del_gendisk(), so run the last reset to avoid leaking
2031      * anything allocated with disksize_store()
2032      */
2033     zram_reset_device(zram);
2034 
2035     put_disk(zram->disk);
2036     kfree(zram);
2037     return 0;
2038 }
2039 
2040 /* zram-control sysfs attributes */
2041 
2042 /*
2043  * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
2044  * sense that reading from this file does alter the state of your system -- it
2045  * creates a new un-initialized zram device and returns back this device's
2046  * device_id (or an error code if it fails to create a new device).
2047  */
2048 static ssize_t hot_add_show(struct class *class,
2049             struct class_attribute *attr,
2050             char *buf)
2051 {
2052     int ret;
2053 
2054     mutex_lock(&zram_index_mutex);
2055     ret = zram_add();
2056     mutex_unlock(&zram_index_mutex);
2057 
2058     if (ret < 0)
2059         return ret;
2060     return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
2061 }
2062 static struct class_attribute class_attr_hot_add =
2063     __ATTR(hot_add, 0400, hot_add_show, NULL);
2064 
2065 static ssize_t hot_remove_store(struct class *class,
2066             struct class_attribute *attr,
2067             const char *buf,
2068             size_t count)
2069 {
2070     struct zram *zram;
2071     int ret, dev_id;
2072 
2073     /* dev_id is gendisk->first_minor, which is `int' */
2074     ret = kstrtoint(buf, 10, &dev_id);
2075     if (ret)
2076         return ret;
2077     if (dev_id < 0)
2078         return -EINVAL;
2079 
2080     mutex_lock(&zram_index_mutex);
2081 
2082     zram = idr_find(&zram_index_idr, dev_id);
2083     if (zram) {
2084         ret = zram_remove(zram);
2085         if (!ret)
2086             idr_remove(&zram_index_idr, dev_id);
2087     } else {
2088         ret = -ENODEV;
2089     }
2090 
2091     mutex_unlock(&zram_index_mutex);
2092     return ret ? ret : count;
2093 }
2094 static CLASS_ATTR_WO(hot_remove);
2095 
2096 static struct attribute *zram_control_class_attrs[] = {
2097     &class_attr_hot_add.attr,
2098     &class_attr_hot_remove.attr,
2099     NULL,
2100 };
2101 ATTRIBUTE_GROUPS(zram_control_class);
2102 
2103 static struct class zram_control_class = {
2104     .name       = "zram-control",
2105     .owner      = THIS_MODULE,
2106     .class_groups   = zram_control_class_groups,
2107 };
2108 
2109 static int zram_remove_cb(int id, void *ptr, void *data)
2110 {
2111     WARN_ON_ONCE(zram_remove(ptr));
2112     return 0;
2113 }
2114 
2115 static void destroy_devices(void)
2116 {
2117     class_unregister(&zram_control_class);
2118     idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
2119     zram_debugfs_destroy();
2120     idr_destroy(&zram_index_idr);
2121     unregister_blkdev(zram_major, "zram");
2122     cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2123 }
2124 
2125 static int __init zram_init(void)
2126 {
2127     int ret;
2128 
2129     ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
2130                       zcomp_cpu_up_prepare, zcomp_cpu_dead);
2131     if (ret < 0)
2132         return ret;
2133 
2134     ret = class_register(&zram_control_class);
2135     if (ret) {
2136         pr_err("Unable to register zram-control class\n");
2137         cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2138         return ret;
2139     }
2140 
2141     zram_debugfs_create();
2142     zram_major = register_blkdev(0, "zram");
2143     if (zram_major <= 0) {
2144         pr_err("Unable to get major number\n");
2145         class_unregister(&zram_control_class);
2146         cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2147         return -EBUSY;
2148     }
2149 
2150     while (num_devices != 0) {
2151         mutex_lock(&zram_index_mutex);
2152         ret = zram_add();
2153         mutex_unlock(&zram_index_mutex);
2154         if (ret < 0)
2155             goto out_error;
2156         num_devices--;
2157     }
2158 
2159     return 0;
2160 
2161 out_error:
2162     destroy_devices();
2163     return ret;
2164 }
2165 
2166 static void __exit zram_exit(void)
2167 {
2168     destroy_devices();
2169 }
2170 
2171 module_init(zram_init);
2172 module_exit(zram_exit);
2173 
2174 module_param(num_devices, uint, 0);
2175 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
2176 
2177 MODULE_LICENSE("Dual BSD/GPL");
2178 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2179 MODULE_DESCRIPTION("Compressed RAM Block Device");