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/string.h>
29 #include <linux/vmalloc.h>
30 #include <linux/err.h>
31 #include <linux/idr.h>
32 #include <linux/sysfs.h>
33 #include <linux/cpuhotplug.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;
116 * Check if request is within bounds and aligned on zram logical blocks.
118 static inline bool valid_io_request(struct zram *zram,
119 sector_t start, unsigned int size)
123 /* unaligned request */
124 if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
126 if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
129 end = start + (size >> SECTOR_SHIFT);
130 bound = zram->disksize >> SECTOR_SHIFT;
131 /* out of range range */
132 if (unlikely(start >= bound || end > bound || start > end))
135 /* I/O request is valid */
139 static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
141 if (*offset + bvec->bv_len >= PAGE_SIZE)
143 *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
146 static inline void update_used_max(struct zram *zram,
147 const unsigned long pages)
149 unsigned long old_max, cur_max;
151 old_max = atomic_long_read(&zram->stats.max_used_pages);
156 old_max = atomic_long_cmpxchg(
157 &zram->stats.max_used_pages, cur_max, pages);
158 } while (old_max != cur_max);
161 static bool page_zero_filled(void *ptr)
166 page = (unsigned long *)ptr;
168 for (pos = 0; pos != PAGE_SIZE / sizeof(*page); pos++) {
176 static void handle_zero_page(struct bio_vec *bvec)
178 struct page *page = bvec->bv_page;
181 user_mem = kmap_atomic(page);
182 if (is_partial_io(bvec))
183 memset(user_mem + bvec->bv_offset, 0, bvec->bv_len);
185 clear_page(user_mem);
186 kunmap_atomic(user_mem);
188 flush_dcache_page(page);
191 static ssize_t initstate_show(struct device *dev,
192 struct device_attribute *attr, char *buf)
195 struct zram *zram = dev_to_zram(dev);
197 down_read(&zram->init_lock);
198 val = init_done(zram);
199 up_read(&zram->init_lock);
201 return scnprintf(buf, PAGE_SIZE, "%u\n", val);
204 static ssize_t disksize_show(struct device *dev,
205 struct device_attribute *attr, char *buf)
207 struct zram *zram = dev_to_zram(dev);
209 return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
212 static ssize_t orig_data_size_show(struct device *dev,
213 struct device_attribute *attr, char *buf)
215 struct zram *zram = dev_to_zram(dev);
217 deprecated_attr_warn("orig_data_size");
218 return scnprintf(buf, PAGE_SIZE, "%llu\n",
219 (u64)(atomic64_read(&zram->stats.pages_stored)) << PAGE_SHIFT);
222 static ssize_t mem_used_total_show(struct device *dev,
223 struct device_attribute *attr, char *buf)
226 struct zram *zram = dev_to_zram(dev);
228 deprecated_attr_warn("mem_used_total");
229 down_read(&zram->init_lock);
230 if (init_done(zram)) {
231 struct zram_meta *meta = zram->meta;
232 val = zs_get_total_pages(meta->mem_pool);
234 up_read(&zram->init_lock);
236 return scnprintf(buf, PAGE_SIZE, "%llu\n", val << PAGE_SHIFT);
239 static ssize_t mem_limit_show(struct device *dev,
240 struct device_attribute *attr, char *buf)
243 struct zram *zram = dev_to_zram(dev);
245 deprecated_attr_warn("mem_limit");
246 down_read(&zram->init_lock);
247 val = zram->limit_pages;
248 up_read(&zram->init_lock);
250 return scnprintf(buf, PAGE_SIZE, "%llu\n", val << PAGE_SHIFT);
253 static ssize_t mem_limit_store(struct device *dev,
254 struct device_attribute *attr, const char *buf, size_t len)
258 struct zram *zram = dev_to_zram(dev);
260 limit = memparse(buf, &tmp);
261 if (buf == tmp) /* no chars parsed, invalid input */
264 down_write(&zram->init_lock);
265 zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
266 up_write(&zram->init_lock);
271 static ssize_t mem_used_max_show(struct device *dev,
272 struct device_attribute *attr, char *buf)
275 struct zram *zram = dev_to_zram(dev);
277 deprecated_attr_warn("mem_used_max");
278 down_read(&zram->init_lock);
280 val = atomic_long_read(&zram->stats.max_used_pages);
281 up_read(&zram->init_lock);
283 return scnprintf(buf, PAGE_SIZE, "%llu\n", val << PAGE_SHIFT);
286 static ssize_t mem_used_max_store(struct device *dev,
287 struct device_attribute *attr, const char *buf, size_t len)
291 struct zram *zram = dev_to_zram(dev);
293 err = kstrtoul(buf, 10, &val);
297 down_read(&zram->init_lock);
298 if (init_done(zram)) {
299 struct zram_meta *meta = zram->meta;
300 atomic_long_set(&zram->stats.max_used_pages,
301 zs_get_total_pages(meta->mem_pool));
303 up_read(&zram->init_lock);
309 * We switched to per-cpu streams and this attr is not needed anymore.
310 * However, we will keep it around for some time, because:
311 * a) we may revert per-cpu streams in the future
312 * b) it's visible to user space and we need to follow our 2 years
313 * retirement rule; but we already have a number of 'soon to be
314 * altered' attrs, so max_comp_streams need to wait for the next
317 static ssize_t max_comp_streams_show(struct device *dev,
318 struct device_attribute *attr, char *buf)
320 return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
323 static ssize_t max_comp_streams_store(struct device *dev,
324 struct device_attribute *attr, const char *buf, size_t len)
329 static ssize_t comp_algorithm_show(struct device *dev,
330 struct device_attribute *attr, char *buf)
333 struct zram *zram = dev_to_zram(dev);
335 down_read(&zram->init_lock);
336 sz = zcomp_available_show(zram->compressor, buf);
337 up_read(&zram->init_lock);
342 static ssize_t comp_algorithm_store(struct device *dev,
343 struct device_attribute *attr, const char *buf, size_t len)
345 struct zram *zram = dev_to_zram(dev);
346 char compressor[CRYPTO_MAX_ALG_NAME];
349 strlcpy(compressor, buf, sizeof(compressor));
350 /* ignore trailing newline */
351 sz = strlen(compressor);
352 if (sz > 0 && compressor[sz - 1] == '\n')
353 compressor[sz - 1] = 0x00;
355 if (!zcomp_available_algorithm(compressor))
358 down_write(&zram->init_lock);
359 if (init_done(zram)) {
360 up_write(&zram->init_lock);
361 pr_info("Can't change algorithm for initialized device\n");
365 strlcpy(zram->compressor, compressor, sizeof(compressor));
366 up_write(&zram->init_lock);
370 static ssize_t compact_store(struct device *dev,
371 struct device_attribute *attr, const char *buf, size_t len)
373 struct zram *zram = dev_to_zram(dev);
374 struct zram_meta *meta;
376 down_read(&zram->init_lock);
377 if (!init_done(zram)) {
378 up_read(&zram->init_lock);
383 zs_compact(meta->mem_pool);
384 up_read(&zram->init_lock);
389 static ssize_t io_stat_show(struct device *dev,
390 struct device_attribute *attr, char *buf)
392 struct zram *zram = dev_to_zram(dev);
395 down_read(&zram->init_lock);
396 ret = scnprintf(buf, PAGE_SIZE,
397 "%8llu %8llu %8llu %8llu\n",
398 (u64)atomic64_read(&zram->stats.failed_reads),
399 (u64)atomic64_read(&zram->stats.failed_writes),
400 (u64)atomic64_read(&zram->stats.invalid_io),
401 (u64)atomic64_read(&zram->stats.notify_free));
402 up_read(&zram->init_lock);
407 static ssize_t mm_stat_show(struct device *dev,
408 struct device_attribute *attr, char *buf)
410 struct zram *zram = dev_to_zram(dev);
411 struct zs_pool_stats pool_stats;
412 u64 orig_size, mem_used = 0;
416 memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
418 down_read(&zram->init_lock);
419 if (init_done(zram)) {
420 mem_used = zs_get_total_pages(zram->meta->mem_pool);
421 zs_pool_stats(zram->meta->mem_pool, &pool_stats);
424 orig_size = atomic64_read(&zram->stats.pages_stored);
425 max_used = atomic_long_read(&zram->stats.max_used_pages);
427 ret = scnprintf(buf, PAGE_SIZE,
428 "%8llu %8llu %8llu %8lu %8ld %8llu %8lu\n",
429 orig_size << PAGE_SHIFT,
430 (u64)atomic64_read(&zram->stats.compr_data_size),
431 mem_used << PAGE_SHIFT,
432 zram->limit_pages << PAGE_SHIFT,
433 max_used << PAGE_SHIFT,
434 (u64)atomic64_read(&zram->stats.zero_pages),
435 pool_stats.pages_compacted);
436 up_read(&zram->init_lock);
441 static ssize_t debug_stat_show(struct device *dev,
442 struct device_attribute *attr, char *buf)
445 struct zram *zram = dev_to_zram(dev);
448 down_read(&zram->init_lock);
449 ret = scnprintf(buf, PAGE_SIZE,
450 "version: %d\n%8llu\n",
452 (u64)atomic64_read(&zram->stats.writestall));
453 up_read(&zram->init_lock);
458 static DEVICE_ATTR_RO(io_stat);
459 static DEVICE_ATTR_RO(mm_stat);
460 static DEVICE_ATTR_RO(debug_stat);
461 ZRAM_ATTR_RO(num_reads);
462 ZRAM_ATTR_RO(num_writes);
463 ZRAM_ATTR_RO(failed_reads);
464 ZRAM_ATTR_RO(failed_writes);
465 ZRAM_ATTR_RO(invalid_io);
466 ZRAM_ATTR_RO(notify_free);
467 ZRAM_ATTR_RO(zero_pages);
468 ZRAM_ATTR_RO(compr_data_size);
470 static inline bool zram_meta_get(struct zram *zram)
472 if (atomic_inc_not_zero(&zram->refcount))
477 static inline void zram_meta_put(struct zram *zram)
479 atomic_dec(&zram->refcount);
482 static void zram_meta_free(struct zram_meta *meta, u64 disksize)
484 size_t num_pages = disksize >> PAGE_SHIFT;
487 /* Free all pages that are still in this zram device */
488 for (index = 0; index < num_pages; index++) {
489 unsigned long handle = meta->table[index].handle;
494 zs_free(meta->mem_pool, handle);
497 zs_destroy_pool(meta->mem_pool);
502 static struct zram_meta *zram_meta_alloc(char *pool_name, u64 disksize)
505 struct zram_meta *meta = kmalloc(sizeof(*meta), GFP_KERNEL);
510 num_pages = disksize >> PAGE_SHIFT;
511 meta->table = vzalloc(num_pages * sizeof(*meta->table));
513 pr_err("Error allocating zram address table\n");
517 meta->mem_pool = zs_create_pool(pool_name);
518 if (!meta->mem_pool) {
519 pr_err("Error creating memory pool\n");
532 * To protect concurrent access to the same index entry,
533 * caller should hold this table index entry's bit_spinlock to
534 * indicate this index entry is accessing.
536 static void zram_free_page(struct zram *zram, size_t index)
538 struct zram_meta *meta = zram->meta;
539 unsigned long handle = meta->table[index].handle;
541 if (unlikely(!handle)) {
543 * No memory is allocated for zero filled pages.
544 * Simply clear zero page flag.
546 if (zram_test_flag(meta, index, ZRAM_ZERO)) {
547 zram_clear_flag(meta, index, ZRAM_ZERO);
548 atomic64_dec(&zram->stats.zero_pages);
553 zs_free(meta->mem_pool, handle);
555 atomic64_sub(zram_get_obj_size(meta, index),
556 &zram->stats.compr_data_size);
557 atomic64_dec(&zram->stats.pages_stored);
559 meta->table[index].handle = 0;
560 zram_set_obj_size(meta, index, 0);
563 static int zram_decompress_page(struct zram *zram, char *mem, u32 index)
567 struct zram_meta *meta = zram->meta;
568 unsigned long handle;
571 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
572 handle = meta->table[index].handle;
573 size = zram_get_obj_size(meta, index);
575 if (!handle || zram_test_flag(meta, index, ZRAM_ZERO)) {
576 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
581 cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_RO);
582 if (size == PAGE_SIZE) {
583 copy_page(mem, cmem);
585 struct zcomp_strm *zstrm = zcomp_stream_get(zram->comp);
587 ret = zcomp_decompress(zstrm, cmem, size, mem);
588 zcomp_stream_put(zram->comp);
590 zs_unmap_object(meta->mem_pool, handle);
591 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
593 /* Should NEVER happen. Return bio error if it does. */
595 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
602 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
603 u32 index, int offset)
607 unsigned char *user_mem, *uncmem = NULL;
608 struct zram_meta *meta = zram->meta;
609 page = bvec->bv_page;
611 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
612 if (unlikely(!meta->table[index].handle) ||
613 zram_test_flag(meta, index, ZRAM_ZERO)) {
614 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
615 handle_zero_page(bvec);
618 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
620 if (is_partial_io(bvec))
621 /* Use a temporary buffer to decompress the page */
622 uncmem = kmalloc(PAGE_SIZE, GFP_NOIO);
624 user_mem = kmap_atomic(page);
625 if (!is_partial_io(bvec))
629 pr_err("Unable to allocate temp memory\n");
634 ret = zram_decompress_page(zram, uncmem, index);
635 /* Should NEVER happen. Return bio error if it does. */
639 if (is_partial_io(bvec))
640 memcpy(user_mem + bvec->bv_offset, uncmem + offset,
643 flush_dcache_page(page);
646 kunmap_atomic(user_mem);
647 if (is_partial_io(bvec))
652 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec, u32 index,
657 unsigned long handle = 0;
659 unsigned char *user_mem, *cmem, *src, *uncmem = NULL;
660 struct zram_meta *meta = zram->meta;
661 struct zcomp_strm *zstrm = NULL;
662 unsigned long alloced_pages;
664 page = bvec->bv_page;
665 if (is_partial_io(bvec)) {
667 * This is a partial IO. We need to read the full page
668 * before to write the changes.
670 uncmem = kmalloc(PAGE_SIZE, GFP_NOIO);
675 ret = zram_decompress_page(zram, uncmem, index);
681 user_mem = kmap_atomic(page);
682 if (is_partial_io(bvec)) {
683 memcpy(uncmem + offset, user_mem + bvec->bv_offset,
685 kunmap_atomic(user_mem);
691 if (page_zero_filled(uncmem)) {
693 kunmap_atomic(user_mem);
694 /* Free memory associated with this sector now. */
695 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
696 zram_free_page(zram, index);
697 zram_set_flag(meta, index, ZRAM_ZERO);
698 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
700 atomic64_inc(&zram->stats.zero_pages);
705 zstrm = zcomp_stream_get(zram->comp);
706 ret = zcomp_compress(zstrm, uncmem, &clen);
707 if (!is_partial_io(bvec)) {
708 kunmap_atomic(user_mem);
714 pr_err("Compression failed! err=%d\n", ret);
719 if (unlikely(clen > max_zpage_size)) {
721 if (is_partial_io(bvec))
726 * handle allocation has 2 paths:
727 * a) fast path is executed with preemption disabled (for
728 * per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
729 * since we can't sleep;
730 * b) slow path enables preemption and attempts to allocate
731 * the page with __GFP_DIRECT_RECLAIM bit set. we have to
732 * put per-cpu compression stream and, thus, to re-do
733 * the compression once handle is allocated.
735 * if we have a 'non-null' handle here then we are coming
736 * from the slow path and handle has already been allocated.
739 handle = zs_malloc(meta->mem_pool, clen,
740 __GFP_KSWAPD_RECLAIM |
745 zcomp_stream_put(zram->comp);
748 atomic64_inc(&zram->stats.writestall);
750 handle = zs_malloc(meta->mem_pool, clen,
751 GFP_NOIO | __GFP_HIGHMEM |
756 pr_err("Error allocating memory for compressed page: %u, size=%u\n",
762 alloced_pages = zs_get_total_pages(meta->mem_pool);
763 update_used_max(zram, alloced_pages);
765 if (zram->limit_pages && alloced_pages > zram->limit_pages) {
766 zs_free(meta->mem_pool, handle);
771 cmem = zs_map_object(meta->mem_pool, handle, ZS_MM_WO);
773 if ((clen == PAGE_SIZE) && !is_partial_io(bvec)) {
774 src = kmap_atomic(page);
775 copy_page(cmem, src);
778 memcpy(cmem, src, clen);
781 zcomp_stream_put(zram->comp);
783 zs_unmap_object(meta->mem_pool, handle);
786 * Free memory associated with this sector
787 * before overwriting unused sectors.
789 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
790 zram_free_page(zram, index);
792 meta->table[index].handle = handle;
793 zram_set_obj_size(meta, index, clen);
794 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
797 atomic64_add(clen, &zram->stats.compr_data_size);
798 atomic64_inc(&zram->stats.pages_stored);
801 zcomp_stream_put(zram->comp);
802 if (is_partial_io(bvec))
808 * zram_bio_discard - handler on discard request
809 * @index: physical block index in PAGE_SIZE units
810 * @offset: byte offset within physical block
812 static void zram_bio_discard(struct zram *zram, u32 index,
813 int offset, struct bio *bio)
815 size_t n = bio->bi_iter.bi_size;
816 struct zram_meta *meta = zram->meta;
819 * zram manages data in physical block size units. Because logical block
820 * size isn't identical with physical block size on some arch, we
821 * could get a discard request pointing to a specific offset within a
822 * certain physical block. Although we can handle this request by
823 * reading that physiclal block and decompressing and partially zeroing
824 * and re-compressing and then re-storing it, this isn't reasonable
825 * because our intent with a discard request is to save memory. So
826 * skipping this logical block is appropriate here.
829 if (n <= (PAGE_SIZE - offset))
832 n -= (PAGE_SIZE - offset);
836 while (n >= PAGE_SIZE) {
837 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
838 zram_free_page(zram, index);
839 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
840 atomic64_inc(&zram->stats.notify_free);
846 static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
847 int offset, bool is_write)
849 unsigned long start_time = jiffies;
850 int rw_acct = is_write ? REQ_OP_WRITE : REQ_OP_READ;
853 generic_start_io_acct(rw_acct, bvec->bv_len >> SECTOR_SHIFT,
857 atomic64_inc(&zram->stats.num_reads);
858 ret = zram_bvec_read(zram, bvec, index, offset);
860 atomic64_inc(&zram->stats.num_writes);
861 ret = zram_bvec_write(zram, bvec, index, offset);
864 generic_end_io_acct(rw_acct, &zram->disk->part0, start_time);
868 atomic64_inc(&zram->stats.failed_reads);
870 atomic64_inc(&zram->stats.failed_writes);
876 static void __zram_make_request(struct zram *zram, struct bio *bio)
881 struct bvec_iter iter;
883 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
884 offset = (bio->bi_iter.bi_sector &
885 (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
887 if (unlikely(bio_op(bio) == REQ_OP_DISCARD)) {
888 zram_bio_discard(zram, index, offset, bio);
893 bio_for_each_segment(bvec, bio, iter) {
894 int max_transfer_size = PAGE_SIZE - offset;
896 if (bvec.bv_len > max_transfer_size) {
898 * zram_bvec_rw() can only make operation on a single
899 * zram page. Split the bio vector.
903 bv.bv_page = bvec.bv_page;
904 bv.bv_len = max_transfer_size;
905 bv.bv_offset = bvec.bv_offset;
907 if (zram_bvec_rw(zram, &bv, index, offset,
908 op_is_write(bio_op(bio))) < 0)
911 bv.bv_len = bvec.bv_len - max_transfer_size;
912 bv.bv_offset += max_transfer_size;
913 if (zram_bvec_rw(zram, &bv, index + 1, 0,
914 op_is_write(bio_op(bio))) < 0)
917 if (zram_bvec_rw(zram, &bvec, index, offset,
918 op_is_write(bio_op(bio))) < 0)
921 update_position(&index, &offset, &bvec);
932 * Handler function for all zram I/O requests.
934 static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio)
936 struct zram *zram = queue->queuedata;
938 if (unlikely(!zram_meta_get(zram)))
941 blk_queue_split(queue, &bio, queue->bio_split);
943 if (!valid_io_request(zram, bio->bi_iter.bi_sector,
944 bio->bi_iter.bi_size)) {
945 atomic64_inc(&zram->stats.invalid_io);
949 __zram_make_request(zram, bio);
951 return BLK_QC_T_NONE;
956 return BLK_QC_T_NONE;
959 static void zram_slot_free_notify(struct block_device *bdev,
963 struct zram_meta *meta;
965 zram = bdev->bd_disk->private_data;
968 bit_spin_lock(ZRAM_ACCESS, &meta->table[index].value);
969 zram_free_page(zram, index);
970 bit_spin_unlock(ZRAM_ACCESS, &meta->table[index].value);
971 atomic64_inc(&zram->stats.notify_free);
974 static int zram_rw_page(struct block_device *bdev, sector_t sector,
975 struct page *page, bool is_write)
977 int offset, err = -EIO;
982 zram = bdev->bd_disk->private_data;
983 if (unlikely(!zram_meta_get(zram)))
986 if (!valid_io_request(zram, sector, PAGE_SIZE)) {
987 atomic64_inc(&zram->stats.invalid_io);
992 index = sector >> SECTORS_PER_PAGE_SHIFT;
993 offset = sector & (SECTORS_PER_PAGE - 1) << SECTOR_SHIFT;
996 bv.bv_len = PAGE_SIZE;
999 err = zram_bvec_rw(zram, &bv, index, offset, is_write);
1001 zram_meta_put(zram);
1004 * If I/O fails, just return error(ie, non-zero) without
1005 * calling page_endio.
1006 * It causes resubmit the I/O with bio request by upper functions
1007 * of rw_page(e.g., swap_readpage, __swap_writepage) and
1008 * bio->bi_end_io does things to handle the error
1009 * (e.g., SetPageError, set_page_dirty and extra works).
1012 page_endio(page, is_write, 0);
1016 static void zram_reset_device(struct zram *zram)
1018 struct zram_meta *meta;
1022 down_write(&zram->init_lock);
1024 zram->limit_pages = 0;
1026 if (!init_done(zram)) {
1027 up_write(&zram->init_lock);
1033 disksize = zram->disksize;
1035 * Refcount will go down to 0 eventually and r/w handler
1036 * cannot handle further I/O so it will bail out by
1037 * check zram_meta_get.
1039 zram_meta_put(zram);
1041 * We want to free zram_meta in process context to avoid
1042 * deadlock between reclaim path and any other locks.
1044 wait_event(zram->io_done, atomic_read(&zram->refcount) == 0);
1047 memset(&zram->stats, 0, sizeof(zram->stats));
1050 set_capacity(zram->disk, 0);
1051 part_stat_set_all(&zram->disk->part0, 0);
1053 up_write(&zram->init_lock);
1054 /* I/O operation under all of CPU are done so let's free */
1055 zram_meta_free(meta, disksize);
1056 zcomp_destroy(comp);
1059 static ssize_t disksize_store(struct device *dev,
1060 struct device_attribute *attr, const char *buf, size_t len)
1064 struct zram_meta *meta;
1065 struct zram *zram = dev_to_zram(dev);
1068 disksize = memparse(buf, NULL);
1072 disksize = PAGE_ALIGN(disksize);
1073 meta = zram_meta_alloc(zram->disk->disk_name, disksize);
1077 comp = zcomp_create(zram->compressor);
1079 pr_err("Cannot initialise %s compressing backend\n",
1081 err = PTR_ERR(comp);
1085 down_write(&zram->init_lock);
1086 if (init_done(zram)) {
1087 pr_info("Cannot change disksize for initialized device\n");
1089 goto out_destroy_comp;
1092 init_waitqueue_head(&zram->io_done);
1093 atomic_set(&zram->refcount, 1);
1096 zram->disksize = disksize;
1097 set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
1098 up_write(&zram->init_lock);
1101 * Revalidate disk out of the init_lock to avoid lockdep splat.
1102 * It's okay because disk's capacity is protected by init_lock
1103 * so that revalidate_disk always sees up-to-date capacity.
1105 revalidate_disk(zram->disk);
1110 up_write(&zram->init_lock);
1111 zcomp_destroy(comp);
1113 zram_meta_free(meta, disksize);
1117 static ssize_t reset_store(struct device *dev,
1118 struct device_attribute *attr, const char *buf, size_t len)
1121 unsigned short do_reset;
1123 struct block_device *bdev;
1125 ret = kstrtou16(buf, 10, &do_reset);
1132 zram = dev_to_zram(dev);
1133 bdev = bdget_disk(zram->disk, 0);
1137 mutex_lock(&bdev->bd_mutex);
1138 /* Do not reset an active device or claimed device */
1139 if (bdev->bd_openers || zram->claim) {
1140 mutex_unlock(&bdev->bd_mutex);
1145 /* From now on, anyone can't open /dev/zram[0-9] */
1147 mutex_unlock(&bdev->bd_mutex);
1149 /* Make sure all the pending I/O are finished */
1151 zram_reset_device(zram);
1152 revalidate_disk(zram->disk);
1155 mutex_lock(&bdev->bd_mutex);
1156 zram->claim = false;
1157 mutex_unlock(&bdev->bd_mutex);
1162 static int zram_open(struct block_device *bdev, fmode_t mode)
1167 WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
1169 zram = bdev->bd_disk->private_data;
1170 /* zram was claimed to reset so open request fails */
1177 static const struct block_device_operations zram_devops = {
1179 .swap_slot_free_notify = zram_slot_free_notify,
1180 .rw_page = zram_rw_page,
1181 .owner = THIS_MODULE
1184 static DEVICE_ATTR_WO(compact);
1185 static DEVICE_ATTR_RW(disksize);
1186 static DEVICE_ATTR_RO(initstate);
1187 static DEVICE_ATTR_WO(reset);
1188 static DEVICE_ATTR_RO(orig_data_size);
1189 static DEVICE_ATTR_RO(mem_used_total);
1190 static DEVICE_ATTR_RW(mem_limit);
1191 static DEVICE_ATTR_RW(mem_used_max);
1192 static DEVICE_ATTR_RW(max_comp_streams);
1193 static DEVICE_ATTR_RW(comp_algorithm);
1195 static struct attribute *zram_disk_attrs[] = {
1196 &dev_attr_disksize.attr,
1197 &dev_attr_initstate.attr,
1198 &dev_attr_reset.attr,
1199 &dev_attr_num_reads.attr,
1200 &dev_attr_num_writes.attr,
1201 &dev_attr_failed_reads.attr,
1202 &dev_attr_failed_writes.attr,
1203 &dev_attr_compact.attr,
1204 &dev_attr_invalid_io.attr,
1205 &dev_attr_notify_free.attr,
1206 &dev_attr_zero_pages.attr,
1207 &dev_attr_orig_data_size.attr,
1208 &dev_attr_compr_data_size.attr,
1209 &dev_attr_mem_used_total.attr,
1210 &dev_attr_mem_limit.attr,
1211 &dev_attr_mem_used_max.attr,
1212 &dev_attr_max_comp_streams.attr,
1213 &dev_attr_comp_algorithm.attr,
1214 &dev_attr_io_stat.attr,
1215 &dev_attr_mm_stat.attr,
1216 &dev_attr_debug_stat.attr,
1220 static struct attribute_group zram_disk_attr_group = {
1221 .attrs = zram_disk_attrs,
1225 * Allocate and initialize new zram device. the function returns
1226 * '>= 0' device_id upon success, and negative value otherwise.
1228 static int zram_add(void)
1231 struct request_queue *queue;
1234 zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
1238 ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
1243 init_rwsem(&zram->init_lock);
1245 queue = blk_alloc_queue(GFP_KERNEL);
1247 pr_err("Error allocating disk queue for device %d\n",
1253 blk_queue_make_request(queue, zram_make_request);
1255 /* gendisk structure */
1256 zram->disk = alloc_disk(1);
1258 pr_err("Error allocating disk structure for device %d\n",
1261 goto out_free_queue;
1264 zram->disk->major = zram_major;
1265 zram->disk->first_minor = device_id;
1266 zram->disk->fops = &zram_devops;
1267 zram->disk->queue = queue;
1268 zram->disk->queue->queuedata = zram;
1269 zram->disk->private_data = zram;
1270 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
1272 /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
1273 set_capacity(zram->disk, 0);
1274 /* zram devices sort of resembles non-rotational disks */
1275 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zram->disk->queue);
1276 queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
1278 * To ensure that we always get PAGE_SIZE aligned
1279 * and n*PAGE_SIZED sized I/O requests.
1281 blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
1282 blk_queue_logical_block_size(zram->disk->queue,
1283 ZRAM_LOGICAL_BLOCK_SIZE);
1284 blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
1285 blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
1286 zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
1287 blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
1289 * zram_bio_discard() will clear all logical blocks if logical block
1290 * size is identical with physical block size(PAGE_SIZE). But if it is
1291 * different, we will skip discarding some parts of logical blocks in
1292 * the part of the request range which isn't aligned to physical block
1293 * size. So we can't ensure that all discarded logical blocks are
1296 if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
1297 zram->disk->queue->limits.discard_zeroes_data = 1;
1299 zram->disk->queue->limits.discard_zeroes_data = 0;
1300 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, zram->disk->queue);
1302 add_disk(zram->disk);
1304 ret = sysfs_create_group(&disk_to_dev(zram->disk)->kobj,
1305 &zram_disk_attr_group);
1307 pr_err("Error creating sysfs group for device %d\n",
1311 strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
1314 pr_info("Added device: %s\n", zram->disk->disk_name);
1318 del_gendisk(zram->disk);
1319 put_disk(zram->disk);
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);
1348 * Remove sysfs first, so no one will perform a disksize
1349 * store while we destroy the devices. This also helps during
1350 * hot_remove -- zram_reset_device() is the last holder of
1351 * ->init_lock, no later/concurrent disksize_store() or any
1352 * other sysfs handlers are possible.
1354 sysfs_remove_group(&disk_to_dev(zram->disk)->kobj,
1355 &zram_disk_attr_group);
1357 /* Make sure all the pending I/O are finished */
1359 zram_reset_device(zram);
1362 pr_info("Removed device: %s\n", zram->disk->disk_name);
1364 blk_cleanup_queue(zram->disk->queue);
1365 del_gendisk(zram->disk);
1366 put_disk(zram->disk);
1371 /* zram-control sysfs attributes */
1372 static ssize_t hot_add_show(struct class *class,
1373 struct class_attribute *attr,
1378 mutex_lock(&zram_index_mutex);
1380 mutex_unlock(&zram_index_mutex);
1384 return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
1387 static ssize_t hot_remove_store(struct class *class,
1388 struct class_attribute *attr,
1395 /* dev_id is gendisk->first_minor, which is `int' */
1396 ret = kstrtoint(buf, 10, &dev_id);
1402 mutex_lock(&zram_index_mutex);
1404 zram = idr_find(&zram_index_idr, dev_id);
1406 ret = zram_remove(zram);
1408 idr_remove(&zram_index_idr, dev_id);
1413 mutex_unlock(&zram_index_mutex);
1414 return ret ? ret : count;
1418 * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
1419 * sense that reading from this file does alter the state of your system -- it
1420 * creates a new un-initialized zram device and returns back this device's
1421 * device_id (or an error code if it fails to create a new device).
1423 static struct class_attribute zram_control_class_attrs[] = {
1424 __ATTR(hot_add, 0400, hot_add_show, NULL),
1425 __ATTR_WO(hot_remove),
1429 static struct class zram_control_class = {
1430 .name = "zram-control",
1431 .owner = THIS_MODULE,
1432 .class_attrs = zram_control_class_attrs,
1435 static int zram_remove_cb(int id, void *ptr, void *data)
1441 static void destroy_devices(void)
1443 class_unregister(&zram_control_class);
1444 idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
1445 idr_destroy(&zram_index_idr);
1446 unregister_blkdev(zram_major, "zram");
1447 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1450 static int __init zram_init(void)
1454 ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
1455 zcomp_cpu_up_prepare, zcomp_cpu_dead);
1459 ret = class_register(&zram_control_class);
1461 pr_err("Unable to register zram-control class\n");
1462 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1466 zram_major = register_blkdev(0, "zram");
1467 if (zram_major <= 0) {
1468 pr_err("Unable to get major number\n");
1469 class_unregister(&zram_control_class);
1470 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
1474 while (num_devices != 0) {
1475 mutex_lock(&zram_index_mutex);
1477 mutex_unlock(&zram_index_mutex);
1490 static void __exit zram_exit(void)
1495 module_init(zram_init);
1496 module_exit(zram_exit);
1498 module_param(num_devices, uint, 0);
1499 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
1501 MODULE_LICENSE("Dual BSD/GPL");
1502 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
1503 MODULE_DESCRIPTION("Compressed RAM Block Device");