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>
37 static DEFINE_IDR(zram_index_idr);
38 /* idr index must be protected */
39 static DEFINE_MUTEX(zram_index_mutex);
41 static int zram_major;
42 static const char *default_compressor = "lzo";
44 /* Module params (documentation at end) */
45 static unsigned int num_devices = 1;
47 static inline void deprecated_attr_warn(const char *name)
49 pr_warn_once("%d (%s) Attribute %s (and others) will be removed. %s\n",
53 "See zram documentation.");
56 #define ZRAM_ATTR_RO(name) \
57 static ssize_t name##_show(struct device *d, \
58 struct device_attribute *attr, char *b) \
60 struct zram *zram = dev_to_zram(d); \
62 deprecated_attr_warn(__stringify(name)); \
63 return scnprintf(b, PAGE_SIZE, "%llu\n", \
64 (u64)atomic64_read(&zram->stats.name)); \
66 static DEVICE_ATTR_RO(name);
68 static inline bool init_done(struct zram *zram)
70 return zram->disksize;
73 static inline struct zram *dev_to_zram(struct device *dev)
75 return (struct zram *)dev_to_disk(dev)->private_data;
78 /* flag operations require table entry bit_spin_lock() being held */
79 static int zram_test_flag(struct zram_meta *meta, u32 index,
80 enum zram_pageflags flag)
82 return meta->table[index].value & BIT(flag);
85 static void zram_set_flag(struct zram_meta *meta, u32 index,
86 enum zram_pageflags flag)
88 meta->table[index].value |= BIT(flag);
91 static void zram_clear_flag(struct zram_meta *meta, u32 index,
92 enum zram_pageflags flag)
94 meta->table[index].value &= ~BIT(flag);
97 static size_t zram_get_obj_size(struct zram_meta *meta, u32 index)
99 return meta->table[index].value & (BIT(ZRAM_FLAG_SHIFT) - 1);
102 static void zram_set_obj_size(struct zram_meta *meta,
103 u32 index, size_t size)
105 unsigned long flags = meta->table[index].value >> ZRAM_FLAG_SHIFT;
107 meta->table[index].value = (flags << ZRAM_FLAG_SHIFT) | size;
110 static inline bool is_partial_io(struct bio_vec *bvec)
112 return bvec->bv_len != PAGE_SIZE;
115 static void zram_revalidate_disk(struct zram *zram)
117 revalidate_disk(zram->disk);
118 /* revalidate_disk reset the BDI_CAP_STABLE_WRITES so set again */
119 zram->disk->queue->backing_dev_info.capabilities |=
120 BDI_CAP_STABLE_WRITES;
124 * Check if request is within bounds and aligned on zram logical blocks.
126 static inline bool valid_io_request(struct zram *zram,
127 sector_t start, unsigned int size)
131 /* unaligned request */
132 if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
134 if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
137 end = start + (size >> SECTOR_SHIFT);
138 bound = zram->disksize >> SECTOR_SHIFT;
139 /* out of range range */
140 if (unlikely(start >= bound || end > bound || start > end))
143 /* I/O request is valid */
147 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
149 if (*offset + bvec->bv_len >= PAGE_SIZE)
151 *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
154 static inline void update_used_max(struct zram *zram,
155 const unsigned long pages)
157 unsigned long old_max, cur_max;
159 old_max = atomic_long_read(&zram->stats.max_used_pages);
164 old_max = atomic_long_cmpxchg(
165 &zram->stats.max_used_pages, cur_max, pages);
166 } while (old_max != cur_max);
169 static bool page_zero_filled(void *ptr)
174 page = (unsigned long *)ptr;
176 for (pos = 0; pos != PAGE_SIZE / sizeof(*page); pos++) {
184 static void handle_zero_page(struct bio_vec *bvec)
186 struct page *page = bvec->bv_page;
189 user_mem = kmap_atomic(page);
190 if (is_partial_io(bvec))
191 memset(user_mem + bvec->bv_offset, 0, bvec->bv_len);
193 clear_page(user_mem);
194 kunmap_atomic(user_mem);
196 flush_dcache_page(page);
199 static ssize_t initstate_show(struct device *dev,
200 struct device_attribute *attr, char *buf)
203 struct zram *zram = dev_to_zram(dev);
205 down_read(&zram->init_lock);
206 val = init_done(zram);
207 up_read(&zram->init_lock);
209 return scnprintf(buf, PAGE_SIZE, "%u\n", val);
212 static ssize_t disksize_show(struct device *dev,
213 struct device_attribute *attr, char *buf)
215 struct zram *zram = dev_to_zram(dev);
217 return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
220 static ssize_t orig_data_size_show(struct device *dev,
221 struct device_attribute *attr, char *buf)
223 struct zram *zram = dev_to_zram(dev);
225 deprecated_attr_warn("orig_data_size");
226 return scnprintf(buf, PAGE_SIZE, "%llu\n",
227 (u64)(atomic64_read(&zram->stats.pages_stored)) << PAGE_SHIFT);
230 static ssize_t mem_used_total_show(struct device *dev,
231 struct device_attribute *attr, char *buf)
234 struct zram *zram = dev_to_zram(dev);
236 deprecated_attr_warn("mem_used_total");
237 down_read(&zram->init_lock);
238 if (init_done(zram)) {
239 struct zram_meta *meta = zram->meta;
240 val = zs_get_total_pages(meta->mem_pool);
242 up_read(&zram->init_lock);
244 return scnprintf(buf, PAGE_SIZE, "%llu\n", val << PAGE_SHIFT);
247 static ssize_t mem_limit_show(struct device *dev,
248 struct device_attribute *attr, char *buf)
251 struct zram *zram = dev_to_zram(dev);
253 deprecated_attr_warn("mem_limit");
254 down_read(&zram->init_lock);
255 val = zram->limit_pages;
256 up_read(&zram->init_lock);
258 return scnprintf(buf, PAGE_SIZE, "%llu\n", val << PAGE_SHIFT);
261 static ssize_t mem_limit_store(struct device *dev,
262 struct device_attribute *attr, const char *buf, size_t len)
266 struct zram *zram = dev_to_zram(dev);
268 limit = memparse(buf, &tmp);
269 if (buf == tmp) /* no chars parsed, invalid input */
272 down_write(&zram->init_lock);
273 zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
274 up_write(&zram->init_lock);
279 static ssize_t mem_used_max_show(struct device *dev,
280 struct device_attribute *attr, char *buf)
283 struct zram *zram = dev_to_zram(dev);
285 deprecated_attr_warn("mem_used_max");
286 down_read(&zram->init_lock);
288 val = atomic_long_read(&zram->stats.max_used_pages);
289 up_read(&zram->init_lock);
291 return scnprintf(buf, PAGE_SIZE, "%llu\n", val << PAGE_SHIFT);
294 static ssize_t mem_used_max_store(struct device *dev,
295 struct device_attribute *attr, const char *buf, size_t len)
299 struct zram *zram = dev_to_zram(dev);
301 err = kstrtoul(buf, 10, &val);
305 down_read(&zram->init_lock);
306 if (init_done(zram)) {
307 struct zram_meta *meta = zram->meta;
308 atomic_long_set(&zram->stats.max_used_pages,
309 zs_get_total_pages(meta->mem_pool));
311 up_read(&zram->init_lock);
317 * We switched to per-cpu streams and this attr is not needed anymore.
318 * However, we will keep it around for some time, because:
319 * a) we may revert per-cpu streams in the future
320 * b) it's visible to user space and we need to follow our 2 years
321 * retirement rule; but we already have a number of 'soon to be
322 * altered' attrs, so max_comp_streams need to wait for the next
325 static ssize_t max_comp_streams_show(struct device *dev,
326 struct device_attribute *attr, char *buf)
328 return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
331 static ssize_t max_comp_streams_store(struct device *dev,
332 struct device_attribute *attr, const char *buf, size_t len)
337 static ssize_t comp_algorithm_show(struct device *dev,
338 struct device_attribute *attr, char *buf)
341 struct zram *zram = dev_to_zram(dev);
343 down_read(&zram->init_lock);
344 sz = zcomp_available_show(zram->compressor, buf);
345 up_read(&zram->init_lock);
350 static ssize_t comp_algorithm_store(struct device *dev,
351 struct device_attribute *attr, const char *buf, size_t len)
353 struct zram *zram = dev_to_zram(dev);
354 char compressor[CRYPTO_MAX_ALG_NAME];
357 strlcpy(compressor, buf, sizeof(compressor));
358 /* ignore trailing newline */
359 sz = strlen(compressor);
360 if (sz > 0 && compressor[sz - 1] == '\n')
361 compressor[sz - 1] = 0x00;
363 if (!zcomp_available_algorithm(compressor))
366 down_write(&zram->init_lock);
367 if (init_done(zram)) {
368 up_write(&zram->init_lock);
369 pr_info("Can't change algorithm for initialized device\n");
373 strlcpy(zram->compressor, compressor, sizeof(compressor));
374 up_write(&zram->init_lock);
378 static ssize_t compact_store(struct device *dev,
379 struct device_attribute *attr, const char *buf, size_t len)
381 struct zram *zram = dev_to_zram(dev);
382 struct zram_meta *meta;
384 down_read(&zram->init_lock);
385 if (!init_done(zram)) {
386 up_read(&zram->init_lock);
391 zs_compact(meta->mem_pool);
392 up_read(&zram->init_lock);
397 static ssize_t io_stat_show(struct device *dev,
398 struct device_attribute *attr, char *buf)
400 struct zram *zram = dev_to_zram(dev);
403 down_read(&zram->init_lock);
404 ret = scnprintf(buf, PAGE_SIZE,
405 "%8llu %8llu %8llu %8llu\n",
406 (u64)atomic64_read(&zram->stats.failed_reads),
407 (u64)atomic64_read(&zram->stats.failed_writes),
408 (u64)atomic64_read(&zram->stats.invalid_io),
409 (u64)atomic64_read(&zram->stats.notify_free));
410 up_read(&zram->init_lock);
415 static ssize_t mm_stat_show(struct device *dev,
416 struct device_attribute *attr, char *buf)
418 struct zram *zram = dev_to_zram(dev);
419 struct zs_pool_stats pool_stats;
420 u64 orig_size, mem_used = 0;
424 memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
426 down_read(&zram->init_lock);
427 if (init_done(zram)) {
428 mem_used = zs_get_total_pages(zram->meta->mem_pool);
429 zs_pool_stats(zram->meta->mem_pool, &pool_stats);
432 orig_size = atomic64_read(&zram->stats.pages_stored);
433 max_used = atomic_long_read(&zram->stats.max_used_pages);
435 ret = scnprintf(buf, PAGE_SIZE,
436 "%8llu %8llu %8llu %8lu %8ld %8llu %8lu\n",
437 orig_size << PAGE_SHIFT,
438 (u64)atomic64_read(&zram->stats.compr_data_size),
439 mem_used << PAGE_SHIFT,
440 zram->limit_pages << PAGE_SHIFT,
441 max_used << PAGE_SHIFT,
442 (u64)atomic64_read(&zram->stats.zero_pages),
443 atomic_long_read(&pool_stats.pages_compacted));
444 up_read(&zram->init_lock);
449 static ssize_t debug_stat_show(struct device *dev,
450 struct device_attribute *attr, char *buf)
453 struct zram *zram = dev_to_zram(dev);
456 down_read(&zram->init_lock);
457 ret = scnprintf(buf, PAGE_SIZE,
458 "version: %d\n%8llu\n",
460 (u64)atomic64_read(&zram->stats.writestall));
461 up_read(&zram->init_lock);
466 static DEVICE_ATTR_RO(io_stat);
467 static DEVICE_ATTR_RO(mm_stat);
468 static DEVICE_ATTR_RO(debug_stat);
469 ZRAM_ATTR_RO(num_reads);
470 ZRAM_ATTR_RO(num_writes);
471 ZRAM_ATTR_RO(failed_reads);
472 ZRAM_ATTR_RO(failed_writes);
473 ZRAM_ATTR_RO(invalid_io);
474 ZRAM_ATTR_RO(notify_free);
475 ZRAM_ATTR_RO(zero_pages);
476 ZRAM_ATTR_RO(compr_data_size);
478 static inline bool zram_meta_get(struct zram *zram)
480 if (atomic_inc_not_zero(&zram->refcount))
485 static inline void zram_meta_put(struct zram *zram)
487 atomic_dec(&zram->refcount);
490 static void zram_meta_free(struct zram_meta *meta, u64 disksize)
492 size_t num_pages = disksize >> PAGE_SHIFT;
495 /* Free all pages that are still in this zram device */
496 for (index = 0; index < num_pages; index++) {
497 unsigned long handle = meta->table[index].handle;
502 zs_free(meta->mem_pool, handle);
505 zs_destroy_pool(meta->mem_pool);
510 static struct zram_meta *zram_meta_alloc(char *pool_name, u64 disksize)
513 struct zram_meta *meta = kmalloc(sizeof(*meta), GFP_KERNEL);
518 num_pages = disksize >> PAGE_SHIFT;
519 meta->table = vzalloc(num_pages * sizeof(*meta->table));
521 pr_err("Error allocating zram address table\n");
525 meta->mem_pool = zs_create_pool(pool_name);
526 if (!meta->mem_pool) {
527 pr_err("Error creating memory pool\n");
540 * To protect concurrent access to the same index entry,
541 * caller should hold this table index entry's bit_spinlock to
542 * indicate this index entry is accessing.
544 static void zram_free_page(struct zram *zram, size_t index)
546 struct zram_meta *meta = zram->meta;
547 unsigned long handle = meta->table[index].handle;
549 if (unlikely(!handle)) {
551 * No memory is allocated for zero filled pages.
552 * Simply clear zero page flag.
554 if (zram_test_flag(meta, index, ZRAM_ZERO)) {
555 zram_clear_flag(meta, index, ZRAM_ZERO);
556 atomic64_dec(&zram->stats.zero_pages);
561 zs_free(meta->mem_pool, handle);
563 atomic64_sub(zram_get_obj_size(meta, index),
564 &zram->stats.compr_data_size);
565 atomic64_dec(&zram->stats.pages_stored);
567 meta->table[index].handle = 0;
568 zram_set_obj_size(meta, index, 0);
571 static int zram_decompress_page(struct zram *zram, char *mem, u32 index)
575 struct zram_meta *meta = zram->meta;
576 unsigned long handle;
579 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
580 handle = meta->table[index].handle;
581 size = zram_get_obj_size(meta, index);
583 if (!handle || zram_test_flag(meta, index, ZRAM_ZERO)) {
584 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
585 memset(mem, 0, PAGE_SIZE);
589 cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_RO);
590 if (size == PAGE_SIZE) {
591 memcpy(mem, cmem, PAGE_SIZE);
593 struct zcomp_strm *zstrm = zcomp_stream_get(zram->comp);
595 ret = zcomp_decompress(zstrm, cmem, size, mem);
596 zcomp_stream_put(zram->comp);
598 zs_unmap_object(meta->mem_pool, handle);
599 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
601 /* Should NEVER happen. Return bio error if it does. */
603 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
610 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
611 u32 index, int offset)
615 unsigned char *user_mem, *uncmem = NULL;
616 struct zram_meta *meta = zram->meta;
617 page = bvec->bv_page;
619 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
620 if (unlikely(!meta->table[index].handle) ||
621 zram_test_flag(meta, index, ZRAM_ZERO)) {
622 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
623 handle_zero_page(bvec);
626 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
628 if (is_partial_io(bvec))
629 /* Use a temporary buffer to decompress the page */
630 uncmem = kmalloc(PAGE_SIZE, GFP_NOIO);
632 user_mem = kmap_atomic(page);
633 if (!is_partial_io(bvec))
637 pr_err("Unable to allocate temp memory\n");
642 ret = zram_decompress_page(zram, uncmem, index);
643 /* Should NEVER happen. Return bio error if it does. */
647 if (is_partial_io(bvec))
648 memcpy(user_mem + bvec->bv_offset, uncmem + offset,
651 flush_dcache_page(page);
654 kunmap_atomic(user_mem);
655 if (is_partial_io(bvec))
660 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec, u32 index,
665 unsigned long handle = 0;
667 unsigned char *user_mem, *cmem, *src, *uncmem = NULL;
668 struct zram_meta *meta = zram->meta;
669 struct zcomp_strm *zstrm = NULL;
670 unsigned long alloced_pages;
672 page = bvec->bv_page;
673 if (is_partial_io(bvec)) {
675 * This is a partial IO. We need to read the full page
676 * before to write the changes.
678 uncmem = kmalloc(PAGE_SIZE, GFP_NOIO);
683 ret = zram_decompress_page(zram, uncmem, index);
689 user_mem = kmap_atomic(page);
690 if (is_partial_io(bvec)) {
691 memcpy(uncmem + offset, user_mem + bvec->bv_offset,
693 kunmap_atomic(user_mem);
699 if (page_zero_filled(uncmem)) {
701 kunmap_atomic(user_mem);
702 /* Free memory associated with this sector now. */
703 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
704 zram_free_page(zram, index);
705 zram_set_flag(meta, index, ZRAM_ZERO);
706 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
708 atomic64_inc(&zram->stats.zero_pages);
713 zstrm = zcomp_stream_get(zram->comp);
714 ret = zcomp_compress(zstrm, uncmem, &clen);
715 if (!is_partial_io(bvec)) {
716 kunmap_atomic(user_mem);
722 pr_err("Compression failed! err=%d\n", ret);
727 if (unlikely(clen > max_zpage_size)) {
729 if (is_partial_io(bvec))
734 * handle allocation has 2 paths:
735 * a) fast path is executed with preemption disabled (for
736 * per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
737 * since we can't sleep;
738 * b) slow path enables preemption and attempts to allocate
739 * the page with __GFP_DIRECT_RECLAIM bit set. we have to
740 * put per-cpu compression stream and, thus, to re-do
741 * the compression once handle is allocated.
743 * if we have a 'non-null' handle here then we are coming
744 * from the slow path and handle has already been allocated.
747 handle = zs_malloc(meta->mem_pool, clen,
748 __GFP_KSWAPD_RECLAIM |
753 zcomp_stream_put(zram->comp);
756 atomic64_inc(&zram->stats.writestall);
758 handle = zs_malloc(meta->mem_pool, clen,
759 GFP_NOIO | __GFP_HIGHMEM |
764 pr_err("Error allocating memory for compressed page: %u, size=%u\n",
770 alloced_pages = zs_get_total_pages(meta->mem_pool);
771 update_used_max(zram, alloced_pages);
773 if (zram->limit_pages && alloced_pages > zram->limit_pages) {
774 zs_free(meta->mem_pool, handle);
779 cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_WO);
781 if ((clen == PAGE_SIZE) && !is_partial_io(bvec)) {
782 src = kmap_atomic(page);
783 memcpy(cmem, src, PAGE_SIZE);
786 memcpy(cmem, src, clen);
789 zcomp_stream_put(zram->comp);
791 zs_unmap_object(meta->mem_pool, handle);
794 * Free memory associated with this sector
795 * before overwriting unused sectors.
797 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
798 zram_free_page(zram, index);
800 meta->table[index].handle = handle;
801 zram_set_obj_size(meta, index, clen);
802 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
805 atomic64_add(clen, &zram->stats.compr_data_size);
806 atomic64_inc(&zram->stats.pages_stored);
809 zcomp_stream_put(zram->comp);
810 if (is_partial_io(bvec))
816 * zram_bio_discard - handler on discard request
817 * @index: physical block index in PAGE_SIZE units
818 * @offset: byte offset within physical block
820 static void zram_bio_discard(struct zram *zram, u32 index,
821 int offset, struct bio *bio)
823 size_t n = bio->bi_iter.bi_size;
824 struct zram_meta *meta = zram->meta;
827 * zram manages data in physical block size units. Because logical block
828 * size isn't identical with physical block size on some arch, we
829 * could get a discard request pointing to a specific offset within a
830 * certain physical block. Although we can handle this request by
831 * reading that physiclal block and decompressing and partially zeroing
832 * and re-compressing and then re-storing it, this isn't reasonable
833 * because our intent with a discard request is to save memory. So
834 * skipping this logical block is appropriate here.
837 if (n <= (PAGE_SIZE - offset))
840 n -= (PAGE_SIZE - offset);
844 while (n >= PAGE_SIZE) {
845 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
846 zram_free_page(zram, index);
847 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
848 atomic64_inc(&zram->stats.notify_free);
854 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
855 int offset, bool is_write)
857 unsigned long start_time = jiffies;
858 int rw_acct = is_write ? REQ_OP_WRITE : REQ_OP_READ;
861 generic_start_io_acct(rw_acct, bvec->bv_len >> SECTOR_SHIFT,
865 atomic64_inc(&zram->stats.num_reads);
866 ret = zram_bvec_read(zram, bvec, index, offset);
868 atomic64_inc(&zram->stats.num_writes);
869 ret = zram_bvec_write(zram, bvec, index, offset);
872 generic_end_io_acct(rw_acct, &zram->disk->part0, start_time);
876 atomic64_inc(&zram->stats.failed_reads);
878 atomic64_inc(&zram->stats.failed_writes);
884 static void __zram_make_request(struct zram *zram, struct bio *bio)
889 struct bvec_iter iter;
891 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
892 offset = (bio->bi_iter.bi_sector &
893 (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
895 if (unlikely(bio_op(bio) == REQ_OP_DISCARD)) {
896 zram_bio_discard(zram, index, offset, bio);
901 bio_for_each_segment(bvec, bio, iter) {
902 int max_transfer_size = PAGE_SIZE - offset;
904 if (bvec.bv_len > max_transfer_size) {
906 * zram_bvec_rw() can only make operation on a single
907 * zram page. Split the bio vector.
911 bv.bv_page = bvec.bv_page;
912 bv.bv_len = max_transfer_size;
913 bv.bv_offset = bvec.bv_offset;
915 if (zram_bvec_rw(zram, &bv, index, offset,
916 op_is_write(bio_op(bio))) < 0)
919 bv.bv_len = bvec.bv_len - max_transfer_size;
920 bv.bv_offset += max_transfer_size;
921 if (zram_bvec_rw(zram, &bv, index + 1, 0,
922 op_is_write(bio_op(bio))) < 0)
925 if (zram_bvec_rw(zram, &bvec, index, offset,
926 op_is_write(bio_op(bio))) < 0)
929 update_position(&index, &offset, &bvec);
940 * Handler function for all zram I/O requests.
942 static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio)
944 struct zram *zram = queue->queuedata;
946 if (unlikely(!zram_meta_get(zram)))
949 blk_queue_split(queue, &bio, queue->bio_split);
951 if (!valid_io_request(zram, bio->bi_iter.bi_sector,
952 bio->bi_iter.bi_size)) {
953 atomic64_inc(&zram->stats.invalid_io);
957 __zram_make_request(zram, bio);
959 return BLK_QC_T_NONE;
964 return BLK_QC_T_NONE;
967 static void zram_slot_free_notify(struct block_device *bdev,
971 struct zram_meta *meta;
973 zram = bdev->bd_disk->private_data;
976 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
977 zram_free_page(zram, index);
978 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
979 atomic64_inc(&zram->stats.notify_free);
982 static int zram_rw_page(struct block_device *bdev, sector_t sector,
983 struct page *page, bool is_write)
985 int offset, err = -EIO;
990 zram = bdev->bd_disk->private_data;
991 if (unlikely(!zram_meta_get(zram)))
994 if (!valid_io_request(zram, sector, PAGE_SIZE)) {
995 atomic64_inc(&zram->stats.invalid_io);
1000 index = sector >> SECTORS_PER_PAGE_SHIFT;
1001 offset = sector & (SECTORS_PER_PAGE - 1) << SECTOR_SHIFT;
1004 bv.bv_len = PAGE_SIZE;
1007 err = zram_bvec_rw(zram, &bv, index, offset, is_write);
1009 zram_meta_put(zram);
1012 * If I/O fails, just return error(ie, non-zero) without
1013 * calling page_endio.
1014 * It causes resubmit the I/O with bio request by upper functions
1015 * of rw_page(e.g., swap_readpage, __swap_writepage) and
1016 * bio->bi_end_io does things to handle the error
1017 * (e.g., SetPageError, set_page_dirty and extra works).
1020 page_endio(page, is_write, 0);
1024 static void zram_reset_device(struct zram *zram)
1026 struct zram_meta *meta;
1030 down_write(&zram->init_lock);
1032 zram->limit_pages = 0;
1034 if (!init_done(zram)) {
1035 up_write(&zram->init_lock);
1041 disksize = zram->disksize;
1043 * Refcount will go down to 0 eventually and r/w handler
1044 * cannot handle further I/O so it will bail out by
1045 * check zram_meta_get.
1047 zram_meta_put(zram);
1049 * We want to free zram_meta in process context to avoid
1050 * deadlock between reclaim path and any other locks.
1052 wait_event(zram->io_done, atomic_read(&zram->refcount) == 0);
1055 memset(&zram->stats, 0, sizeof(zram->stats));
1058 set_capacity(zram->disk, 0);
1059 part_stat_set_all(&zram->disk->part0, 0);
1061 up_write(&zram->init_lock);
1062 /* I/O operation under all of CPU are done so let's free */
1063 zram_meta_free(meta, disksize);
1064 zcomp_destroy(comp);
1067 static ssize_t disksize_store(struct device *dev,
1068 struct device_attribute *attr, const char *buf, size_t len)
1072 struct zram_meta *meta;
1073 struct zram *zram = dev_to_zram(dev);
1076 disksize = memparse(buf, NULL);
1080 disksize = PAGE_ALIGN(disksize);
1081 meta = zram_meta_alloc(zram->disk->disk_name, disksize);
1085 comp = zcomp_create(zram->compressor);
1087 pr_err("Cannot initialise %s compressing backend\n",
1089 err = PTR_ERR(comp);
1093 down_write(&zram->init_lock);
1094 if (init_done(zram)) {
1095 pr_info("Cannot change disksize for initialized device\n");
1097 goto out_destroy_comp;
1100 init_waitqueue_head(&zram->io_done);
1101 atomic_set(&zram->refcount, 1);
1104 zram->disksize = disksize;
1105 set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
1106 zram_revalidate_disk(zram);
1107 up_write(&zram->init_lock);
1112 up_write(&zram->init_lock);
1113 zcomp_destroy(comp);
1115 zram_meta_free(meta, disksize);
1119 static ssize_t reset_store(struct device *dev,
1120 struct device_attribute *attr, const char *buf, size_t len)
1123 unsigned short do_reset;
1125 struct block_device *bdev;
1127 ret = kstrtou16(buf, 10, &do_reset);
1134 zram = dev_to_zram(dev);
1135 bdev = bdget_disk(zram->disk, 0);
1139 mutex_lock(&bdev->bd_mutex);
1140 /* Do not reset an active device or claimed device */
1141 if (bdev->bd_openers || zram->claim) {
1142 mutex_unlock(&bdev->bd_mutex);
1147 /* From now on, anyone can't open /dev/zram[0-9] */
1149 mutex_unlock(&bdev->bd_mutex);
1151 /* Make sure all the pending I/O are finished */
1153 zram_reset_device(zram);
1154 zram_revalidate_disk(zram);
1157 mutex_lock(&bdev->bd_mutex);
1158 zram->claim = false;
1159 mutex_unlock(&bdev->bd_mutex);
1164 static int zram_open(struct block_device *bdev, fmode_t mode)
1169 WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
1171 zram = bdev->bd_disk->private_data;
1172 /* zram was claimed to reset so open request fails */
1179 static const struct block_device_operations zram_devops = {
1181 .swap_slot_free_notify = zram_slot_free_notify,
1182 .rw_page = zram_rw_page,
1183 .owner = THIS_MODULE
1186 static DEVICE_ATTR_WO(compact);
1187 static DEVICE_ATTR_RW(disksize);
1188 static DEVICE_ATTR_RO(initstate);
1189 static DEVICE_ATTR_WO(reset);
1190 static DEVICE_ATTR_RO(orig_data_size);
1191 static DEVICE_ATTR_RO(mem_used_total);
1192 static DEVICE_ATTR_RW(mem_limit);
1193 static DEVICE_ATTR_RW(mem_used_max);
1194 static DEVICE_ATTR_RW(max_comp_streams);
1195 static DEVICE_ATTR_RW(comp_algorithm);
1197 static struct attribute *zram_disk_attrs[] = {
1198 &dev_attr_disksize.attr,
1199 &dev_attr_initstate.attr,
1200 &dev_attr_reset.attr,
1201 &dev_attr_num_reads.attr,
1202 &dev_attr_num_writes.attr,
1203 &dev_attr_failed_reads.attr,
1204 &dev_attr_failed_writes.attr,
1205 &dev_attr_compact.attr,
1206 &dev_attr_invalid_io.attr,
1207 &dev_attr_notify_free.attr,
1208 &dev_attr_zero_pages.attr,
1209 &dev_attr_orig_data_size.attr,
1210 &dev_attr_compr_data_size.attr,
1211 &dev_attr_mem_used_total.attr,
1212 &dev_attr_mem_limit.attr,
1213 &dev_attr_mem_used_max.attr,
1214 &dev_attr_max_comp_streams.attr,
1215 &dev_attr_comp_algorithm.attr,
1216 &dev_attr_io_stat.attr,
1217 &dev_attr_mm_stat.attr,
1218 &dev_attr_debug_stat.attr,
1222 static struct attribute_group zram_disk_attr_group = {
1223 .attrs = zram_disk_attrs,
1226 static const struct attribute_group *zram_disk_attr_groups[] = {
1227 &zram_disk_attr_group,
1232 * Allocate and initialize new zram device. the function returns
1233 * '>= 0' device_id upon success, and negative value otherwise.
1235 static int zram_add(void)
1238 struct request_queue *queue;
1241 zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1245 ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1250 init_rwsem(&zram->init_lock);
1252 queue = blk_alloc_queue(GFP_KERNEL);
1254 pr_err("Error allocating disk queue for device %d\n",
1260 blk_queue_make_request(queue, zram_make_request);
1262 /* gendisk structure */
1263 zram->disk = alloc_disk(1);
1265 pr_err("Error allocating disk structure for device %d\n",
1268 goto out_free_queue;
1271 zram->disk->major = zram_major;
1272 zram->disk->first_minor = device_id;
1273 zram->disk->fops = &zram_devops;
1274 zram->disk->queue = queue;
1275 zram->disk->queue->queuedata = zram;
1276 zram->disk->private_data = zram;
1277 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1279 /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1280 set_capacity(zram->disk, 0);
1281 /* zram devices sort of resembles non-rotational disks */
1282 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zram->disk->queue);
1283 queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1285 * To ensure that we always get PAGE_SIZE aligned
1286 * and n*PAGE_SIZED sized I/O requests.
1288 blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1289 blk_queue_logical_block_size(zram->disk->queue,
1290 ZRAM_LOGICAL_BLOCK_SIZE);
1291 blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1292 blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1293 zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1294 zram->disk->queue->limits.max_sectors = SECTORS_PER_PAGE;
1295 zram->disk->queue->limits.chunk_sectors = 0;
1296 blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1298 * zram_bio_discard() will clear all logical blocks if logical block
1299 * size is identical with physical block size(PAGE_SIZE). But if it is
1300 * different, we will skip discarding some parts of logical blocks in
1301 * the part of the request range which isn't aligned to physical block
1302 * size. So we can't ensure that all discarded logical blocks are
1305 if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1306 zram->disk->queue->limits.discard_zeroes_data = 1;
1308 zram->disk->queue->limits.discard_zeroes_data = 0;
1309 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, zram->disk->queue);
1311 disk_to_dev(zram->disk)->groups = zram_disk_attr_groups;
1312 add_disk(zram->disk);
1314 strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1317 pr_info("Added device: %s\n", zram->disk->disk_name);
1321 blk_cleanup_queue(queue);
1323 idr_remove(&zram_index_idr, device_id);
1329 static int zram_remove(struct zram *zram)
1331 struct block_device *bdev;
1333 bdev = bdget_disk(zram->disk, 0);
1337 mutex_lock(&bdev->bd_mutex);
1338 if (bdev->bd_openers || zram->claim) {
1339 mutex_unlock(&bdev->bd_mutex);
1345 mutex_unlock(&bdev->bd_mutex);
1347 /* Make sure all the pending I/O are finished */
1349 zram_reset_device(zram);
1352 pr_info("Removed device: %s\n", zram->disk->disk_name);
1354 blk_cleanup_queue(zram->disk->queue);
1355 del_gendisk(zram->disk);
1356 put_disk(zram->disk);
1361 /* zram-control sysfs attributes */
1362 static ssize_t hot_add_show(struct class *class,
1363 struct class_attribute *attr,
1368 mutex_lock(&zram_index_mutex);
1370 mutex_unlock(&zram_index_mutex);
1374 return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
1377 static ssize_t hot_remove_store(struct class *class,
1378 struct class_attribute *attr,
1385 /* dev_id is gendisk->first_minor, which is `int' */
1386 ret = kstrtoint(buf, 10, &dev_id);
1392 mutex_lock(&zram_index_mutex);
1394 zram = idr_find(&zram_index_idr, dev_id);
1396 ret = zram_remove(zram);
1398 idr_remove(&zram_index_idr, dev_id);
1403 mutex_unlock(&zram_index_mutex);
1404 return ret ? ret : count;
1408 * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
1409 * sense that reading from this file does alter the state of your system -- it
1410 * creates a new un-initialized zram device and returns back this device's
1411 * device_id (or an error code if it fails to create a new device).
1413 static struct class_attribute zram_control_class_attrs[] = {
1414 __ATTR(hot_add, 0400, hot_add_show, NULL),
1415 __ATTR_WO(hot_remove),
1419 static struct class zram_control_class = {
1420 .name = "zram-control",
1421 .owner = THIS_MODULE,
1422 .class_attrs = zram_control_class_attrs,
1425 static int zram_remove_cb(int id, void *ptr, void *data)
1431 static void destroy_devices(void)
1433 class_unregister(&zram_control_class);
1434 idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
1435 idr_destroy(&zram_index_idr);
1436 unregister_blkdev(zram_major, "zram");
1439 static int __init zram_init(void)
1443 ret = class_register(&zram_control_class);
1445 pr_err("Unable to register zram-control class\n");
1449 zram_major = register_blkdev(0, "zram");
1450 if (zram_major <= 0) {
1451 pr_err("Unable to get major number\n");
1452 class_unregister(&zram_control_class);
1456 while (num_devices != 0) {
1457 mutex_lock(&zram_index_mutex);
1459 mutex_unlock(&zram_index_mutex);
1472 static void __exit zram_exit(void)
1477 module_init(zram_init);
1478 module_exit(zram_exit);
1480 module_param(num_devices, uint, 0);
1481 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
1483 MODULE_LICENSE("Dual BSD/GPL");
1484 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
1485 MODULE_DESCRIPTION("Compressed RAM Block Device");