1 /*
2 * Compressed RAM block device
3 *
4 * Copyright (C) 2008, 2009, 2010 Nitin Gupta
5 * 2012, 2013 Minchan Kim
6 *
7 * This code is released using a dual license strategy: BSD/GPL
8 * You can choose the licence that better fits your requirements.
9 *
10 * Released under the terms of 3-clause BSD License
11 * Released under the terms of GNU General Public License Version 2.0
12 *
13 */
14
15 #define KMSG_COMPONENT "zram"
16 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
17
18 #include <linux/module.h>
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/bitops.h>
22 #include <linux/blkdev.h>
23 #include <linux/buffer_head.h>
24 #include <linux/device.h>
25 #include <linux/highmem.h>
26 #include <linux/slab.h>
27 #include <linux/backing-dev.h>
28 #include <linux/string.h>
29 #include <linux/vmalloc.h>
30 #include <linux/err.h>
31 #include <linux/idr.h>
32 #include <linux/sysfs.h>
33 #include <linux/debugfs.h>
34 #include <linux/cpuhotplug.h>
35 #include <linux/part_stat.h>
36
37 #include "zram_drv.h"
38
39 static DEFINE_IDR(zram_index_idr);
40 /* idr index must be protected */
41 static DEFINE_MUTEX(zram_index_mutex);
42
43 static int zram_major;
44 static const char *default_compressor = CONFIG_ZRAM_DEF_COMP;
45
46 /* Module params (documentation at end) */
47 static unsigned int num_devices = 1;
48 /*
49 * Pages that compress to sizes equals or greater than this are stored
50 * uncompressed in memory.
51 */
52 static size_t huge_class_size;
53
54 static const struct block_device_operations zram_devops;
55
56 static void zram_free_page(struct zram *zram, size_t index);
57 static int zram_read_page(struct zram *zram, struct page *page, u32 index,
58 struct bio *parent);
59
zram_slot_trylock(struct zram * zram,u32 index)60 static int zram_slot_trylock(struct zram *zram, u32 index)
61 {
62 return bit_spin_trylock(ZRAM_LOCK, &zram->table[index].flags);
63 }
64
zram_slot_lock(struct zram * zram,u32 index)65 static void zram_slot_lock(struct zram *zram, u32 index)
66 {
67 bit_spin_lock(ZRAM_LOCK, &zram->table[index].flags);
68 }
69
zram_slot_unlock(struct zram * zram,u32 index)70 static void zram_slot_unlock(struct zram *zram, u32 index)
71 {
72 bit_spin_unlock(ZRAM_LOCK, &zram->table[index].flags);
73 }
74
init_done(struct zram * zram)75 static inline bool init_done(struct zram *zram)
76 {
77 return zram->disksize;
78 }
79
dev_to_zram(struct device * dev)80 static inline struct zram *dev_to_zram(struct device *dev)
81 {
82 return (struct zram *)dev_to_disk(dev)->private_data;
83 }
84
zram_get_handle(struct zram * zram,u32 index)85 static unsigned long zram_get_handle(struct zram *zram, u32 index)
86 {
87 return zram->table[index].handle;
88 }
89
zram_set_handle(struct zram * zram,u32 index,unsigned long handle)90 static void zram_set_handle(struct zram *zram, u32 index, unsigned long handle)
91 {
92 zram->table[index].handle = handle;
93 }
94
95 /* flag operations require table entry bit_spin_lock() being held */
zram_test_flag(struct zram * zram,u32 index,enum zram_pageflags flag)96 static bool zram_test_flag(struct zram *zram, u32 index,
97 enum zram_pageflags flag)
98 {
99 return zram->table[index].flags & BIT(flag);
100 }
101
zram_set_flag(struct zram * zram,u32 index,enum zram_pageflags flag)102 static void zram_set_flag(struct zram *zram, u32 index,
103 enum zram_pageflags flag)
104 {
105 zram->table[index].flags |= BIT(flag);
106 }
107
zram_clear_flag(struct zram * zram,u32 index,enum zram_pageflags flag)108 static void zram_clear_flag(struct zram *zram, u32 index,
109 enum zram_pageflags flag)
110 {
111 zram->table[index].flags &= ~BIT(flag);
112 }
113
zram_set_element(struct zram * zram,u32 index,unsigned long element)114 static inline void zram_set_element(struct zram *zram, u32 index,
115 unsigned long element)
116 {
117 zram->table[index].element = element;
118 }
119
zram_get_element(struct zram * zram,u32 index)120 static unsigned long zram_get_element(struct zram *zram, u32 index)
121 {
122 return zram->table[index].element;
123 }
124
zram_get_obj_size(struct zram * zram,u32 index)125 static size_t zram_get_obj_size(struct zram *zram, u32 index)
126 {
127 return zram->table[index].flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
128 }
129
zram_set_obj_size(struct zram * zram,u32 index,size_t size)130 static void zram_set_obj_size(struct zram *zram,
131 u32 index, size_t size)
132 {
133 unsigned long flags = zram->table[index].flags >> ZRAM_FLAG_SHIFT;
134
135 zram->table[index].flags = (flags << ZRAM_FLAG_SHIFT) | size;
136 }
137
zram_allocated(struct zram * zram,u32 index)138 static inline bool zram_allocated(struct zram *zram, u32 index)
139 {
140 return zram_get_obj_size(zram, index) ||
141 zram_test_flag(zram, index, ZRAM_SAME) ||
142 zram_test_flag(zram, index, ZRAM_WB);
143 }
144
145 #if PAGE_SIZE != 4096
is_partial_io(struct bio_vec * bvec)146 static inline bool is_partial_io(struct bio_vec *bvec)
147 {
148 return bvec->bv_len != PAGE_SIZE;
149 }
150 #define ZRAM_PARTIAL_IO 1
151 #else
is_partial_io(struct bio_vec * bvec)152 static inline bool is_partial_io(struct bio_vec *bvec)
153 {
154 return false;
155 }
156 #endif
157
zram_set_priority(struct zram * zram,u32 index,u32 prio)158 static inline void zram_set_priority(struct zram *zram, u32 index, u32 prio)
159 {
160 prio &= ZRAM_COMP_PRIORITY_MASK;
161 /*
162 * Clear previous priority value first, in case if we recompress
163 * further an already recompressed page
164 */
165 zram->table[index].flags &= ~(ZRAM_COMP_PRIORITY_MASK <<
166 ZRAM_COMP_PRIORITY_BIT1);
167 zram->table[index].flags |= (prio << ZRAM_COMP_PRIORITY_BIT1);
168 }
169
zram_get_priority(struct zram * zram,u32 index)170 static inline u32 zram_get_priority(struct zram *zram, u32 index)
171 {
172 u32 prio = zram->table[index].flags >> ZRAM_COMP_PRIORITY_BIT1;
173
174 return prio & ZRAM_COMP_PRIORITY_MASK;
175 }
176
zram_accessed(struct zram * zram,u32 index)177 static void zram_accessed(struct zram *zram, u32 index)
178 {
179 zram_clear_flag(zram, index, ZRAM_IDLE);
180 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
181 zram->table[index].ac_time = ktime_get_boottime();
182 #endif
183 }
184
update_used_max(struct zram * zram,const unsigned long pages)185 static inline void update_used_max(struct zram *zram,
186 const unsigned long pages)
187 {
188 unsigned long cur_max = atomic_long_read(&zram->stats.max_used_pages);
189
190 do {
191 if (cur_max >= pages)
192 return;
193 } while (!atomic_long_try_cmpxchg(&zram->stats.max_used_pages,
194 &cur_max, pages));
195 }
196
zram_fill_page(void * ptr,unsigned long len,unsigned long value)197 static inline void zram_fill_page(void *ptr, unsigned long len,
198 unsigned long value)
199 {
200 WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
201 memset_l(ptr, value, len / sizeof(unsigned long));
202 }
203
page_same_filled(void * ptr,unsigned long * element)204 static bool page_same_filled(void *ptr, unsigned long *element)
205 {
206 unsigned long *page;
207 unsigned long val;
208 unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
209
210 page = (unsigned long *)ptr;
211 val = page[0];
212
213 if (val != page[last_pos])
214 return false;
215
216 for (pos = 1; pos < last_pos; pos++) {
217 if (val != page[pos])
218 return false;
219 }
220
221 *element = val;
222
223 return true;
224 }
225
initstate_show(struct device * dev,struct device_attribute * attr,char * buf)226 static ssize_t initstate_show(struct device *dev,
227 struct device_attribute *attr, char *buf)
228 {
229 u32 val;
230 struct zram *zram = dev_to_zram(dev);
231
232 down_read(&zram->init_lock);
233 val = init_done(zram);
234 up_read(&zram->init_lock);
235
236 return scnprintf(buf, PAGE_SIZE, "%u\n", val);
237 }
238
disksize_show(struct device * dev,struct device_attribute * attr,char * buf)239 static ssize_t disksize_show(struct device *dev,
240 struct device_attribute *attr, char *buf)
241 {
242 struct zram *zram = dev_to_zram(dev);
243
244 return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
245 }
246
mem_limit_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)247 static ssize_t mem_limit_store(struct device *dev,
248 struct device_attribute *attr, const char *buf, size_t len)
249 {
250 u64 limit;
251 char *tmp;
252 struct zram *zram = dev_to_zram(dev);
253
254 limit = memparse(buf, &tmp);
255 if (buf == tmp) /* no chars parsed, invalid input */
256 return -EINVAL;
257
258 down_write(&zram->init_lock);
259 zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
260 up_write(&zram->init_lock);
261
262 return len;
263 }
264
mem_used_max_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)265 static ssize_t mem_used_max_store(struct device *dev,
266 struct device_attribute *attr, const char *buf, size_t len)
267 {
268 int err;
269 unsigned long val;
270 struct zram *zram = dev_to_zram(dev);
271
272 err = kstrtoul(buf, 10, &val);
273 if (err || val != 0)
274 return -EINVAL;
275
276 down_read(&zram->init_lock);
277 if (init_done(zram)) {
278 atomic_long_set(&zram->stats.max_used_pages,
279 zs_get_total_pages(zram->mem_pool));
280 }
281 up_read(&zram->init_lock);
282
283 return len;
284 }
285
286 /*
287 * Mark all pages which are older than or equal to cutoff as IDLE.
288 * Callers should hold the zram init lock in read mode
289 */
mark_idle(struct zram * zram,ktime_t cutoff)290 static void mark_idle(struct zram *zram, ktime_t cutoff)
291 {
292 int is_idle = 1;
293 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
294 int index;
295
296 for (index = 0; index < nr_pages; index++) {
297 /*
298 * Do not mark ZRAM_UNDER_WB slot as ZRAM_IDLE to close race.
299 * See the comment in writeback_store.
300 *
301 * Also do not mark ZRAM_SAME slots as ZRAM_IDLE, because no
302 * post-processing (recompress, writeback) happens to the
303 * ZRAM_SAME slot.
304 *
305 * And ZRAM_WB slots simply cannot be ZRAM_IDLE.
306 */
307 zram_slot_lock(zram, index);
308 if (!zram_allocated(zram, index) ||
309 zram_test_flag(zram, index, ZRAM_WB) ||
310 zram_test_flag(zram, index, ZRAM_UNDER_WB) ||
311 zram_test_flag(zram, index, ZRAM_SAME)) {
312 zram_slot_unlock(zram, index);
313 continue;
314 }
315
316 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
317 is_idle = !cutoff ||
318 ktime_after(cutoff, zram->table[index].ac_time);
319 #endif
320 if (is_idle)
321 zram_set_flag(zram, index, ZRAM_IDLE);
322 else
323 zram_clear_flag(zram, index, ZRAM_IDLE);
324 zram_slot_unlock(zram, index);
325 }
326 }
327
idle_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)328 static ssize_t idle_store(struct device *dev,
329 struct device_attribute *attr, const char *buf, size_t len)
330 {
331 struct zram *zram = dev_to_zram(dev);
332 ktime_t cutoff_time = 0;
333 ssize_t rv = -EINVAL;
334
335 if (!sysfs_streq(buf, "all")) {
336 /*
337 * If it did not parse as 'all' try to treat it as an integer
338 * when we have memory tracking enabled.
339 */
340 u64 age_sec;
341
342 if (IS_ENABLED(CONFIG_ZRAM_TRACK_ENTRY_ACTIME) && !kstrtoull(buf, 0, &age_sec))
343 cutoff_time = ktime_sub(ktime_get_boottime(),
344 ns_to_ktime(age_sec * NSEC_PER_SEC));
345 else
346 goto out;
347 }
348
349 down_read(&zram->init_lock);
350 if (!init_done(zram))
351 goto out_unlock;
352
353 /*
354 * A cutoff_time of 0 marks everything as idle, this is the
355 * "all" behavior.
356 */
357 mark_idle(zram, cutoff_time);
358 rv = len;
359
360 out_unlock:
361 up_read(&zram->init_lock);
362 out:
363 return rv;
364 }
365
366 #ifdef CONFIG_ZRAM_WRITEBACK
writeback_limit_enable_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)367 static ssize_t writeback_limit_enable_store(struct device *dev,
368 struct device_attribute *attr, const char *buf, size_t len)
369 {
370 struct zram *zram = dev_to_zram(dev);
371 u64 val;
372 ssize_t ret = -EINVAL;
373
374 if (kstrtoull(buf, 10, &val))
375 return ret;
376
377 down_read(&zram->init_lock);
378 spin_lock(&zram->wb_limit_lock);
379 zram->wb_limit_enable = val;
380 spin_unlock(&zram->wb_limit_lock);
381 up_read(&zram->init_lock);
382 ret = len;
383
384 return ret;
385 }
386
writeback_limit_enable_show(struct device * dev,struct device_attribute * attr,char * buf)387 static ssize_t writeback_limit_enable_show(struct device *dev,
388 struct device_attribute *attr, char *buf)
389 {
390 bool val;
391 struct zram *zram = dev_to_zram(dev);
392
393 down_read(&zram->init_lock);
394 spin_lock(&zram->wb_limit_lock);
395 val = zram->wb_limit_enable;
396 spin_unlock(&zram->wb_limit_lock);
397 up_read(&zram->init_lock);
398
399 return scnprintf(buf, PAGE_SIZE, "%d\n", val);
400 }
401
writeback_limit_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)402 static ssize_t writeback_limit_store(struct device *dev,
403 struct device_attribute *attr, const char *buf, size_t len)
404 {
405 struct zram *zram = dev_to_zram(dev);
406 u64 val;
407 ssize_t ret = -EINVAL;
408
409 if (kstrtoull(buf, 10, &val))
410 return ret;
411
412 down_read(&zram->init_lock);
413 spin_lock(&zram->wb_limit_lock);
414 zram->bd_wb_limit = val;
415 spin_unlock(&zram->wb_limit_lock);
416 up_read(&zram->init_lock);
417 ret = len;
418
419 return ret;
420 }
421
writeback_limit_show(struct device * dev,struct device_attribute * attr,char * buf)422 static ssize_t writeback_limit_show(struct device *dev,
423 struct device_attribute *attr, char *buf)
424 {
425 u64 val;
426 struct zram *zram = dev_to_zram(dev);
427
428 down_read(&zram->init_lock);
429 spin_lock(&zram->wb_limit_lock);
430 val = zram->bd_wb_limit;
431 spin_unlock(&zram->wb_limit_lock);
432 up_read(&zram->init_lock);
433
434 return scnprintf(buf, PAGE_SIZE, "%llu\n", val);
435 }
436
reset_bdev(struct zram * zram)437 static void reset_bdev(struct zram *zram)
438 {
439 struct block_device *bdev;
440
441 if (!zram->backing_dev)
442 return;
443
444 bdev = zram->bdev;
445 blkdev_put(bdev, zram);
446 /* hope filp_close flush all of IO */
447 filp_close(zram->backing_dev, NULL);
448 zram->backing_dev = NULL;
449 zram->bdev = NULL;
450 zram->disk->fops = &zram_devops;
451 kvfree(zram->bitmap);
452 zram->bitmap = NULL;
453 }
454
backing_dev_show(struct device * dev,struct device_attribute * attr,char * buf)455 static ssize_t backing_dev_show(struct device *dev,
456 struct device_attribute *attr, char *buf)
457 {
458 struct file *file;
459 struct zram *zram = dev_to_zram(dev);
460 char *p;
461 ssize_t ret;
462
463 down_read(&zram->init_lock);
464 file = zram->backing_dev;
465 if (!file) {
466 memcpy(buf, "none\n", 5);
467 up_read(&zram->init_lock);
468 return 5;
469 }
470
471 p = file_path(file, buf, PAGE_SIZE - 1);
472 if (IS_ERR(p)) {
473 ret = PTR_ERR(p);
474 goto out;
475 }
476
477 ret = strlen(p);
478 memmove(buf, p, ret);
479 buf[ret++] = '\n';
480 out:
481 up_read(&zram->init_lock);
482 return ret;
483 }
484
backing_dev_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)485 static ssize_t backing_dev_store(struct device *dev,
486 struct device_attribute *attr, const char *buf, size_t len)
487 {
488 char *file_name;
489 size_t sz;
490 struct file *backing_dev = NULL;
491 struct inode *inode;
492 struct address_space *mapping;
493 unsigned int bitmap_sz;
494 unsigned long nr_pages, *bitmap = NULL;
495 struct block_device *bdev = NULL;
496 int err;
497 struct zram *zram = dev_to_zram(dev);
498
499 file_name = kmalloc(PATH_MAX, GFP_KERNEL);
500 if (!file_name)
501 return -ENOMEM;
502
503 down_write(&zram->init_lock);
504 if (init_done(zram)) {
505 pr_info("Can't setup backing device for initialized device\n");
506 err = -EBUSY;
507 goto out;
508 }
509
510 strscpy(file_name, buf, PATH_MAX);
511 /* ignore trailing newline */
512 sz = strlen(file_name);
513 if (sz > 0 && file_name[sz - 1] == '\n')
514 file_name[sz - 1] = 0x00;
515
516 backing_dev = filp_open(file_name, O_RDWR|O_LARGEFILE, 0);
517 if (IS_ERR(backing_dev)) {
518 err = PTR_ERR(backing_dev);
519 backing_dev = NULL;
520 goto out;
521 }
522
523 mapping = backing_dev->f_mapping;
524 inode = mapping->host;
525
526 /* Support only block device in this moment */
527 if (!S_ISBLK(inode->i_mode)) {
528 err = -ENOTBLK;
529 goto out;
530 }
531
532 bdev = blkdev_get_by_dev(inode->i_rdev, BLK_OPEN_READ | BLK_OPEN_WRITE,
533 zram, NULL);
534 if (IS_ERR(bdev)) {
535 err = PTR_ERR(bdev);
536 bdev = NULL;
537 goto out;
538 }
539
540 nr_pages = i_size_read(inode) >> PAGE_SHIFT;
541 /* Refuse to use zero sized device (also prevents self reference) */
542 if (!nr_pages) {
543 err = -EINVAL;
544 goto out;
545 }
546
547 bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
548 bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
549 if (!bitmap) {
550 err = -ENOMEM;
551 goto out;
552 }
553
554 reset_bdev(zram);
555
556 zram->bdev = bdev;
557 zram->backing_dev = backing_dev;
558 zram->bitmap = bitmap;
559 zram->nr_pages = nr_pages;
560 up_write(&zram->init_lock);
561
562 pr_info("setup backing device %s\n", file_name);
563 kfree(file_name);
564
565 return len;
566 out:
567 kvfree(bitmap);
568
569 if (bdev)
570 blkdev_put(bdev, zram);
571
572 if (backing_dev)
573 filp_close(backing_dev, NULL);
574
575 up_write(&zram->init_lock);
576
577 kfree(file_name);
578
579 return err;
580 }
581
alloc_block_bdev(struct zram * zram)582 static unsigned long alloc_block_bdev(struct zram *zram)
583 {
584 unsigned long blk_idx = 1;
585 retry:
586 /* skip 0 bit to confuse zram.handle = 0 */
587 blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, blk_idx);
588 if (blk_idx == zram->nr_pages)
589 return 0;
590
591 if (test_and_set_bit(blk_idx, zram->bitmap))
592 goto retry;
593
594 atomic64_inc(&zram->stats.bd_count);
595 return blk_idx;
596 }
597
free_block_bdev(struct zram * zram,unsigned long blk_idx)598 static void free_block_bdev(struct zram *zram, unsigned long blk_idx)
599 {
600 int was_set;
601
602 was_set = test_and_clear_bit(blk_idx, zram->bitmap);
603 WARN_ON_ONCE(!was_set);
604 atomic64_dec(&zram->stats.bd_count);
605 }
606
read_from_bdev_async(struct zram * zram,struct page * page,unsigned long entry,struct bio * parent)607 static void read_from_bdev_async(struct zram *zram, struct page *page,
608 unsigned long entry, struct bio *parent)
609 {
610 struct bio *bio;
611
612 bio = bio_alloc(zram->bdev, 1, parent->bi_opf, GFP_NOIO);
613 bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
614 __bio_add_page(bio, page, PAGE_SIZE, 0);
615 bio_chain(bio, parent);
616 submit_bio(bio);
617 }
618
619 #define PAGE_WB_SIG "page_index="
620
621 #define PAGE_WRITEBACK 0
622 #define HUGE_WRITEBACK (1<<0)
623 #define IDLE_WRITEBACK (1<<1)
624 #define INCOMPRESSIBLE_WRITEBACK (1<<2)
625
writeback_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)626 static ssize_t writeback_store(struct device *dev,
627 struct device_attribute *attr, const char *buf, size_t len)
628 {
629 struct zram *zram = dev_to_zram(dev);
630 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
631 unsigned long index = 0;
632 struct bio bio;
633 struct bio_vec bio_vec;
634 struct page *page;
635 ssize_t ret = len;
636 int mode, err;
637 unsigned long blk_idx = 0;
638
639 if (sysfs_streq(buf, "idle"))
640 mode = IDLE_WRITEBACK;
641 else if (sysfs_streq(buf, "huge"))
642 mode = HUGE_WRITEBACK;
643 else if (sysfs_streq(buf, "huge_idle"))
644 mode = IDLE_WRITEBACK | HUGE_WRITEBACK;
645 else if (sysfs_streq(buf, "incompressible"))
646 mode = INCOMPRESSIBLE_WRITEBACK;
647 else {
648 if (strncmp(buf, PAGE_WB_SIG, sizeof(PAGE_WB_SIG) - 1))
649 return -EINVAL;
650
651 if (kstrtol(buf + sizeof(PAGE_WB_SIG) - 1, 10, &index) ||
652 index >= nr_pages)
653 return -EINVAL;
654
655 nr_pages = 1;
656 mode = PAGE_WRITEBACK;
657 }
658
659 down_read(&zram->init_lock);
660 if (!init_done(zram)) {
661 ret = -EINVAL;
662 goto release_init_lock;
663 }
664
665 if (!zram->backing_dev) {
666 ret = -ENODEV;
667 goto release_init_lock;
668 }
669
670 page = alloc_page(GFP_KERNEL);
671 if (!page) {
672 ret = -ENOMEM;
673 goto release_init_lock;
674 }
675
676 for (; nr_pages != 0; index++, nr_pages--) {
677 spin_lock(&zram->wb_limit_lock);
678 if (zram->wb_limit_enable && !zram->bd_wb_limit) {
679 spin_unlock(&zram->wb_limit_lock);
680 ret = -EIO;
681 break;
682 }
683 spin_unlock(&zram->wb_limit_lock);
684
685 if (!blk_idx) {
686 blk_idx = alloc_block_bdev(zram);
687 if (!blk_idx) {
688 ret = -ENOSPC;
689 break;
690 }
691 }
692
693 zram_slot_lock(zram, index);
694 if (!zram_allocated(zram, index))
695 goto next;
696
697 if (zram_test_flag(zram, index, ZRAM_WB) ||
698 zram_test_flag(zram, index, ZRAM_SAME) ||
699 zram_test_flag(zram, index, ZRAM_UNDER_WB))
700 goto next;
701
702 if (mode & IDLE_WRITEBACK &&
703 !zram_test_flag(zram, index, ZRAM_IDLE))
704 goto next;
705 if (mode & HUGE_WRITEBACK &&
706 !zram_test_flag(zram, index, ZRAM_HUGE))
707 goto next;
708 if (mode & INCOMPRESSIBLE_WRITEBACK &&
709 !zram_test_flag(zram, index, ZRAM_INCOMPRESSIBLE))
710 goto next;
711
712 /*
713 * Clearing ZRAM_UNDER_WB is duty of caller.
714 * IOW, zram_free_page never clear it.
715 */
716 zram_set_flag(zram, index, ZRAM_UNDER_WB);
717 /* Need for hugepage writeback racing */
718 zram_set_flag(zram, index, ZRAM_IDLE);
719 zram_slot_unlock(zram, index);
720 if (zram_read_page(zram, page, index, NULL)) {
721 zram_slot_lock(zram, index);
722 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
723 zram_clear_flag(zram, index, ZRAM_IDLE);
724 zram_slot_unlock(zram, index);
725 continue;
726 }
727
728 bio_init(&bio, zram->bdev, &bio_vec, 1,
729 REQ_OP_WRITE | REQ_SYNC);
730 bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
731 __bio_add_page(&bio, page, PAGE_SIZE, 0);
732
733 /*
734 * XXX: A single page IO would be inefficient for write
735 * but it would be not bad as starter.
736 */
737 err = submit_bio_wait(&bio);
738 if (err) {
739 zram_slot_lock(zram, index);
740 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
741 zram_clear_flag(zram, index, ZRAM_IDLE);
742 zram_slot_unlock(zram, index);
743 /*
744 * BIO errors are not fatal, we continue and simply
745 * attempt to writeback the remaining objects (pages).
746 * At the same time we need to signal user-space that
747 * some writes (at least one, but also could be all of
748 * them) were not successful and we do so by returning
749 * the most recent BIO error.
750 */
751 ret = err;
752 continue;
753 }
754
755 atomic64_inc(&zram->stats.bd_writes);
756 /*
757 * We released zram_slot_lock so need to check if the slot was
758 * changed. If there is freeing for the slot, we can catch it
759 * easily by zram_allocated.
760 * A subtle case is the slot is freed/reallocated/marked as
761 * ZRAM_IDLE again. To close the race, idle_store doesn't
762 * mark ZRAM_IDLE once it found the slot was ZRAM_UNDER_WB.
763 * Thus, we could close the race by checking ZRAM_IDLE bit.
764 */
765 zram_slot_lock(zram, index);
766 if (!zram_allocated(zram, index) ||
767 !zram_test_flag(zram, index, ZRAM_IDLE)) {
768 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
769 zram_clear_flag(zram, index, ZRAM_IDLE);
770 goto next;
771 }
772
773 zram_free_page(zram, index);
774 zram_clear_flag(zram, index, ZRAM_UNDER_WB);
775 zram_set_flag(zram, index, ZRAM_WB);
776 zram_set_element(zram, index, blk_idx);
777 blk_idx = 0;
778 atomic64_inc(&zram->stats.pages_stored);
779 spin_lock(&zram->wb_limit_lock);
780 if (zram->wb_limit_enable && zram->bd_wb_limit > 0)
781 zram->bd_wb_limit -= 1UL << (PAGE_SHIFT - 12);
782 spin_unlock(&zram->wb_limit_lock);
783 next:
784 zram_slot_unlock(zram, index);
785 }
786
787 if (blk_idx)
788 free_block_bdev(zram, blk_idx);
789 __free_page(page);
790 release_init_lock:
791 up_read(&zram->init_lock);
792
793 return ret;
794 }
795
796 struct zram_work {
797 struct work_struct work;
798 struct zram *zram;
799 unsigned long entry;
800 struct page *page;
801 int error;
802 };
803
zram_sync_read(struct work_struct * work)804 static void zram_sync_read(struct work_struct *work)
805 {
806 struct zram_work *zw = container_of(work, struct zram_work, work);
807 struct bio_vec bv;
808 struct bio bio;
809
810 bio_init(&bio, zw->zram->bdev, &bv, 1, REQ_OP_READ);
811 bio.bi_iter.bi_sector = zw->entry * (PAGE_SIZE >> 9);
812 __bio_add_page(&bio, zw->page, PAGE_SIZE, 0);
813 zw->error = submit_bio_wait(&bio);
814 }
815
816 /*
817 * Block layer want one ->submit_bio to be active at a time, so if we use
818 * chained IO with parent IO in same context, it's a deadlock. To avoid that,
819 * use a worker thread context.
820 */
read_from_bdev_sync(struct zram * zram,struct page * page,unsigned long entry)821 static int read_from_bdev_sync(struct zram *zram, struct page *page,
822 unsigned long entry)
823 {
824 struct zram_work work;
825
826 work.page = page;
827 work.zram = zram;
828 work.entry = entry;
829
830 INIT_WORK_ONSTACK(&work.work, zram_sync_read);
831 queue_work(system_unbound_wq, &work.work);
832 flush_work(&work.work);
833 destroy_work_on_stack(&work.work);
834
835 return work.error;
836 }
837
read_from_bdev(struct zram * zram,struct page * page,unsigned long entry,struct bio * parent)838 static int read_from_bdev(struct zram *zram, struct page *page,
839 unsigned long entry, struct bio *parent)
840 {
841 atomic64_inc(&zram->stats.bd_reads);
842 if (!parent) {
843 if (WARN_ON_ONCE(!IS_ENABLED(ZRAM_PARTIAL_IO)))
844 return -EIO;
845 return read_from_bdev_sync(zram, page, entry);
846 }
847 read_from_bdev_async(zram, page, entry, parent);
848 return 0;
849 }
850 #else
reset_bdev(struct zram * zram)851 static inline void reset_bdev(struct zram *zram) {};
read_from_bdev(struct zram * zram,struct page * page,unsigned long entry,struct bio * parent)852 static int read_from_bdev(struct zram *zram, struct page *page,
853 unsigned long entry, struct bio *parent)
854 {
855 return -EIO;
856 }
857
free_block_bdev(struct zram * zram,unsigned long blk_idx)858 static void free_block_bdev(struct zram *zram, unsigned long blk_idx) {};
859 #endif
860
861 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
862
863 static struct dentry *zram_debugfs_root;
864
zram_debugfs_create(void)865 static void zram_debugfs_create(void)
866 {
867 zram_debugfs_root = debugfs_create_dir("zram", NULL);
868 }
869
zram_debugfs_destroy(void)870 static void zram_debugfs_destroy(void)
871 {
872 debugfs_remove_recursive(zram_debugfs_root);
873 }
874
read_block_state(struct file * file,char __user * buf,size_t count,loff_t * ppos)875 static ssize_t read_block_state(struct file *file, char __user *buf,
876 size_t count, loff_t *ppos)
877 {
878 char *kbuf;
879 ssize_t index, written = 0;
880 struct zram *zram = file->private_data;
881 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
882 struct timespec64 ts;
883
884 kbuf = kvmalloc(count, GFP_KERNEL);
885 if (!kbuf)
886 return -ENOMEM;
887
888 down_read(&zram->init_lock);
889 if (!init_done(zram)) {
890 up_read(&zram->init_lock);
891 kvfree(kbuf);
892 return -EINVAL;
893 }
894
895 for (index = *ppos; index < nr_pages; index++) {
896 int copied;
897
898 zram_slot_lock(zram, index);
899 if (!zram_allocated(zram, index))
900 goto next;
901
902 ts = ktime_to_timespec64(zram->table[index].ac_time);
903 copied = snprintf(kbuf + written, count,
904 "%12zd %12lld.%06lu %c%c%c%c%c%c\n",
905 index, (s64)ts.tv_sec,
906 ts.tv_nsec / NSEC_PER_USEC,
907 zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
908 zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
909 zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
910 zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
911 zram_get_priority(zram, index) ? 'r' : '.',
912 zram_test_flag(zram, index,
913 ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
914
915 if (count <= copied) {
916 zram_slot_unlock(zram, index);
917 break;
918 }
919 written += copied;
920 count -= copied;
921 next:
922 zram_slot_unlock(zram, index);
923 *ppos += 1;
924 }
925
926 up_read(&zram->init_lock);
927 if (copy_to_user(buf, kbuf, written))
928 written = -EFAULT;
929 kvfree(kbuf);
930
931 return written;
932 }
933
934 static const struct file_operations proc_zram_block_state_op = {
935 .open = simple_open,
936 .read = read_block_state,
937 .llseek = default_llseek,
938 };
939
zram_debugfs_register(struct zram * zram)940 static void zram_debugfs_register(struct zram *zram)
941 {
942 if (!zram_debugfs_root)
943 return;
944
945 zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
946 zram_debugfs_root);
947 debugfs_create_file("block_state", 0400, zram->debugfs_dir,
948 zram, &proc_zram_block_state_op);
949 }
950
zram_debugfs_unregister(struct zram * zram)951 static void zram_debugfs_unregister(struct zram *zram)
952 {
953 debugfs_remove_recursive(zram->debugfs_dir);
954 }
955 #else
zram_debugfs_create(void)956 static void zram_debugfs_create(void) {};
zram_debugfs_destroy(void)957 static void zram_debugfs_destroy(void) {};
zram_debugfs_register(struct zram * zram)958 static void zram_debugfs_register(struct zram *zram) {};
zram_debugfs_unregister(struct zram * zram)959 static void zram_debugfs_unregister(struct zram *zram) {};
960 #endif
961
962 /*
963 * We switched to per-cpu streams and this attr is not needed anymore.
964 * However, we will keep it around for some time, because:
965 * a) we may revert per-cpu streams in the future
966 * b) it's visible to user space and we need to follow our 2 years
967 * retirement rule; but we already have a number of 'soon to be
968 * altered' attrs, so max_comp_streams need to wait for the next
969 * layoff cycle.
970 */
max_comp_streams_show(struct device * dev,struct device_attribute * attr,char * buf)971 static ssize_t max_comp_streams_show(struct device *dev,
972 struct device_attribute *attr, char *buf)
973 {
974 return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
975 }
976
max_comp_streams_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)977 static ssize_t max_comp_streams_store(struct device *dev,
978 struct device_attribute *attr, const char *buf, size_t len)
979 {
980 return len;
981 }
982
comp_algorithm_set(struct zram * zram,u32 prio,const char * alg)983 static void comp_algorithm_set(struct zram *zram, u32 prio, const char *alg)
984 {
985 /* Do not free statically defined compression algorithms */
986 if (zram->comp_algs[prio] != default_compressor)
987 kfree(zram->comp_algs[prio]);
988
989 zram->comp_algs[prio] = alg;
990 }
991
__comp_algorithm_show(struct zram * zram,u32 prio,char * buf)992 static ssize_t __comp_algorithm_show(struct zram *zram, u32 prio, char *buf)
993 {
994 ssize_t sz;
995
996 down_read(&zram->init_lock);
997 sz = zcomp_available_show(zram->comp_algs[prio], buf);
998 up_read(&zram->init_lock);
999
1000 return sz;
1001 }
1002
__comp_algorithm_store(struct zram * zram,u32 prio,const char * buf)1003 static int __comp_algorithm_store(struct zram *zram, u32 prio, const char *buf)
1004 {
1005 char *compressor;
1006 size_t sz;
1007
1008 sz = strlen(buf);
1009 if (sz >= CRYPTO_MAX_ALG_NAME)
1010 return -E2BIG;
1011
1012 compressor = kstrdup(buf, GFP_KERNEL);
1013 if (!compressor)
1014 return -ENOMEM;
1015
1016 /* ignore trailing newline */
1017 if (sz > 0 && compressor[sz - 1] == '\n')
1018 compressor[sz - 1] = 0x00;
1019
1020 if (!zcomp_available_algorithm(compressor)) {
1021 kfree(compressor);
1022 return -EINVAL;
1023 }
1024
1025 down_write(&zram->init_lock);
1026 if (init_done(zram)) {
1027 up_write(&zram->init_lock);
1028 kfree(compressor);
1029 pr_info("Can't change algorithm for initialized device\n");
1030 return -EBUSY;
1031 }
1032
1033 comp_algorithm_set(zram, prio, compressor);
1034 up_write(&zram->init_lock);
1035 return 0;
1036 }
1037
comp_algorithm_show(struct device * dev,struct device_attribute * attr,char * buf)1038 static ssize_t comp_algorithm_show(struct device *dev,
1039 struct device_attribute *attr,
1040 char *buf)
1041 {
1042 struct zram *zram = dev_to_zram(dev);
1043
1044 return __comp_algorithm_show(zram, ZRAM_PRIMARY_COMP, buf);
1045 }
1046
comp_algorithm_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1047 static ssize_t comp_algorithm_store(struct device *dev,
1048 struct device_attribute *attr,
1049 const char *buf,
1050 size_t len)
1051 {
1052 struct zram *zram = dev_to_zram(dev);
1053 int ret;
1054
1055 ret = __comp_algorithm_store(zram, ZRAM_PRIMARY_COMP, buf);
1056 return ret ? ret : len;
1057 }
1058
1059 #ifdef CONFIG_ZRAM_MULTI_COMP
recomp_algorithm_show(struct device * dev,struct device_attribute * attr,char * buf)1060 static ssize_t recomp_algorithm_show(struct device *dev,
1061 struct device_attribute *attr,
1062 char *buf)
1063 {
1064 struct zram *zram = dev_to_zram(dev);
1065 ssize_t sz = 0;
1066 u32 prio;
1067
1068 for (prio = ZRAM_SECONDARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
1069 if (!zram->comp_algs[prio])
1070 continue;
1071
1072 sz += scnprintf(buf + sz, PAGE_SIZE - sz - 2, "#%d: ", prio);
1073 sz += __comp_algorithm_show(zram, prio, buf + sz);
1074 }
1075
1076 return sz;
1077 }
1078
recomp_algorithm_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1079 static ssize_t recomp_algorithm_store(struct device *dev,
1080 struct device_attribute *attr,
1081 const char *buf,
1082 size_t len)
1083 {
1084 struct zram *zram = dev_to_zram(dev);
1085 int prio = ZRAM_SECONDARY_COMP;
1086 char *args, *param, *val;
1087 char *alg = NULL;
1088 int ret;
1089
1090 args = skip_spaces(buf);
1091 while (*args) {
1092 args = next_arg(args, ¶m, &val);
1093
1094 if (!val || !*val)
1095 return -EINVAL;
1096
1097 if (!strcmp(param, "algo")) {
1098 alg = val;
1099 continue;
1100 }
1101
1102 if (!strcmp(param, "priority")) {
1103 ret = kstrtoint(val, 10, &prio);
1104 if (ret)
1105 return ret;
1106 continue;
1107 }
1108 }
1109
1110 if (!alg)
1111 return -EINVAL;
1112
1113 if (prio < ZRAM_SECONDARY_COMP || prio >= ZRAM_MAX_COMPS)
1114 return -EINVAL;
1115
1116 ret = __comp_algorithm_store(zram, prio, alg);
1117 return ret ? ret : len;
1118 }
1119 #endif
1120
compact_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1121 static ssize_t compact_store(struct device *dev,
1122 struct device_attribute *attr, const char *buf, size_t len)
1123 {
1124 struct zram *zram = dev_to_zram(dev);
1125
1126 down_read(&zram->init_lock);
1127 if (!init_done(zram)) {
1128 up_read(&zram->init_lock);
1129 return -EINVAL;
1130 }
1131
1132 zs_compact(zram->mem_pool);
1133 up_read(&zram->init_lock);
1134
1135 return len;
1136 }
1137
io_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1138 static ssize_t io_stat_show(struct device *dev,
1139 struct device_attribute *attr, char *buf)
1140 {
1141 struct zram *zram = dev_to_zram(dev);
1142 ssize_t ret;
1143
1144 down_read(&zram->init_lock);
1145 ret = scnprintf(buf, PAGE_SIZE,
1146 "%8llu %8llu 0 %8llu\n",
1147 (u64)atomic64_read(&zram->stats.failed_reads),
1148 (u64)atomic64_read(&zram->stats.failed_writes),
1149 (u64)atomic64_read(&zram->stats.notify_free));
1150 up_read(&zram->init_lock);
1151
1152 return ret;
1153 }
1154
mm_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1155 static ssize_t mm_stat_show(struct device *dev,
1156 struct device_attribute *attr, char *buf)
1157 {
1158 struct zram *zram = dev_to_zram(dev);
1159 struct zs_pool_stats pool_stats;
1160 u64 orig_size, mem_used = 0;
1161 long max_used;
1162 ssize_t ret;
1163
1164 memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1165
1166 down_read(&zram->init_lock);
1167 if (init_done(zram)) {
1168 mem_used = zs_get_total_pages(zram->mem_pool);
1169 zs_pool_stats(zram->mem_pool, &pool_stats);
1170 }
1171
1172 orig_size = atomic64_read(&zram->stats.pages_stored);
1173 max_used = atomic_long_read(&zram->stats.max_used_pages);
1174
1175 ret = scnprintf(buf, PAGE_SIZE,
1176 "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu %8llu\n",
1177 orig_size << PAGE_SHIFT,
1178 (u64)atomic64_read(&zram->stats.compr_data_size),
1179 mem_used << PAGE_SHIFT,
1180 zram->limit_pages << PAGE_SHIFT,
1181 max_used << PAGE_SHIFT,
1182 (u64)atomic64_read(&zram->stats.same_pages),
1183 atomic_long_read(&pool_stats.pages_compacted),
1184 (u64)atomic64_read(&zram->stats.huge_pages),
1185 (u64)atomic64_read(&zram->stats.huge_pages_since));
1186 up_read(&zram->init_lock);
1187
1188 return ret;
1189 }
1190
1191 #ifdef CONFIG_ZRAM_WRITEBACK
1192 #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
bd_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1193 static ssize_t bd_stat_show(struct device *dev,
1194 struct device_attribute *attr, char *buf)
1195 {
1196 struct zram *zram = dev_to_zram(dev);
1197 ssize_t ret;
1198
1199 down_read(&zram->init_lock);
1200 ret = scnprintf(buf, PAGE_SIZE,
1201 "%8llu %8llu %8llu\n",
1202 FOUR_K((u64)atomic64_read(&zram->stats.bd_count)),
1203 FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)),
1204 FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)));
1205 up_read(&zram->init_lock);
1206
1207 return ret;
1208 }
1209 #endif
1210
debug_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1211 static ssize_t debug_stat_show(struct device *dev,
1212 struct device_attribute *attr, char *buf)
1213 {
1214 int version = 1;
1215 struct zram *zram = dev_to_zram(dev);
1216 ssize_t ret;
1217
1218 down_read(&zram->init_lock);
1219 ret = scnprintf(buf, PAGE_SIZE,
1220 "version: %d\n%8llu %8llu\n",
1221 version,
1222 (u64)atomic64_read(&zram->stats.writestall),
1223 (u64)atomic64_read(&zram->stats.miss_free));
1224 up_read(&zram->init_lock);
1225
1226 return ret;
1227 }
1228
1229 static DEVICE_ATTR_RO(io_stat);
1230 static DEVICE_ATTR_RO(mm_stat);
1231 #ifdef CONFIG_ZRAM_WRITEBACK
1232 static DEVICE_ATTR_RO(bd_stat);
1233 #endif
1234 static DEVICE_ATTR_RO(debug_stat);
1235
zram_meta_free(struct zram * zram,u64 disksize)1236 static void zram_meta_free(struct zram *zram, u64 disksize)
1237 {
1238 size_t num_pages = disksize >> PAGE_SHIFT;
1239 size_t index;
1240
1241 if (!zram->table)
1242 return;
1243
1244 /* Free all pages that are still in this zram device */
1245 for (index = 0; index < num_pages; index++)
1246 zram_free_page(zram, index);
1247
1248 zs_destroy_pool(zram->mem_pool);
1249 vfree(zram->table);
1250 zram->table = NULL;
1251 }
1252
zram_meta_alloc(struct zram * zram,u64 disksize)1253 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
1254 {
1255 size_t num_pages;
1256
1257 num_pages = disksize >> PAGE_SHIFT;
1258 zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
1259 if (!zram->table)
1260 return false;
1261
1262 zram->mem_pool = zs_create_pool(zram->disk->disk_name);
1263 if (!zram->mem_pool) {
1264 vfree(zram->table);
1265 zram->table = NULL;
1266 return false;
1267 }
1268
1269 if (!huge_class_size)
1270 huge_class_size = zs_huge_class_size(zram->mem_pool);
1271 return true;
1272 }
1273
1274 /*
1275 * To protect concurrent access to the same index entry,
1276 * caller should hold this table index entry's bit_spinlock to
1277 * indicate this index entry is accessing.
1278 */
zram_free_page(struct zram * zram,size_t index)1279 static void zram_free_page(struct zram *zram, size_t index)
1280 {
1281 unsigned long handle;
1282
1283 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
1284 zram->table[index].ac_time = 0;
1285 #endif
1286 if (zram_test_flag(zram, index, ZRAM_IDLE))
1287 zram_clear_flag(zram, index, ZRAM_IDLE);
1288
1289 if (zram_test_flag(zram, index, ZRAM_HUGE)) {
1290 zram_clear_flag(zram, index, ZRAM_HUGE);
1291 atomic64_dec(&zram->stats.huge_pages);
1292 }
1293
1294 if (zram_test_flag(zram, index, ZRAM_INCOMPRESSIBLE))
1295 zram_clear_flag(zram, index, ZRAM_INCOMPRESSIBLE);
1296
1297 zram_set_priority(zram, index, 0);
1298
1299 if (zram_test_flag(zram, index, ZRAM_WB)) {
1300 zram_clear_flag(zram, index, ZRAM_WB);
1301 free_block_bdev(zram, zram_get_element(zram, index));
1302 goto out;
1303 }
1304
1305 /*
1306 * No memory is allocated for same element filled pages.
1307 * Simply clear same page flag.
1308 */
1309 if (zram_test_flag(zram, index, ZRAM_SAME)) {
1310 zram_clear_flag(zram, index, ZRAM_SAME);
1311 atomic64_dec(&zram->stats.same_pages);
1312 goto out;
1313 }
1314
1315 handle = zram_get_handle(zram, index);
1316 if (!handle)
1317 return;
1318
1319 zs_free(zram->mem_pool, handle);
1320
1321 atomic64_sub(zram_get_obj_size(zram, index),
1322 &zram->stats.compr_data_size);
1323 out:
1324 atomic64_dec(&zram->stats.pages_stored);
1325 zram_set_handle(zram, index, 0);
1326 zram_set_obj_size(zram, index, 0);
1327 WARN_ON_ONCE(zram->table[index].flags &
1328 ~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB));
1329 }
1330
1331 /*
1332 * Reads (decompresses if needed) a page from zspool (zsmalloc).
1333 * Corresponding ZRAM slot should be locked.
1334 */
zram_read_from_zspool(struct zram * zram,struct page * page,u32 index)1335 static int zram_read_from_zspool(struct zram *zram, struct page *page,
1336 u32 index)
1337 {
1338 struct zcomp_strm *zstrm;
1339 unsigned long handle;
1340 unsigned int size;
1341 void *src, *dst;
1342 u32 prio;
1343 int ret;
1344
1345 handle = zram_get_handle(zram, index);
1346 if (!handle || zram_test_flag(zram, index, ZRAM_SAME)) {
1347 unsigned long value;
1348 void *mem;
1349
1350 value = handle ? zram_get_element(zram, index) : 0;
1351 mem = kmap_atomic(page);
1352 zram_fill_page(mem, PAGE_SIZE, value);
1353 kunmap_atomic(mem);
1354 return 0;
1355 }
1356
1357 size = zram_get_obj_size(zram, index);
1358
1359 if (size != PAGE_SIZE) {
1360 prio = zram_get_priority(zram, index);
1361 zstrm = zcomp_stream_get(zram->comps[prio]);
1362 }
1363
1364 src = zs_map_object(zram->mem_pool, handle, ZS_MM_RO);
1365 if (size == PAGE_SIZE) {
1366 dst = kmap_atomic(page);
1367 memcpy(dst, src, PAGE_SIZE);
1368 kunmap_atomic(dst);
1369 ret = 0;
1370 } else {
1371 dst = kmap_atomic(page);
1372 ret = zcomp_decompress(zstrm, src, size, dst);
1373 kunmap_atomic(dst);
1374 zcomp_stream_put(zram->comps[prio]);
1375 }
1376 zs_unmap_object(zram->mem_pool, handle);
1377 return ret;
1378 }
1379
zram_read_page(struct zram * zram,struct page * page,u32 index,struct bio * parent)1380 static int zram_read_page(struct zram *zram, struct page *page, u32 index,
1381 struct bio *parent)
1382 {
1383 int ret;
1384
1385 zram_slot_lock(zram, index);
1386 if (!zram_test_flag(zram, index, ZRAM_WB)) {
1387 /* Slot should be locked through out the function call */
1388 ret = zram_read_from_zspool(zram, page, index);
1389 zram_slot_unlock(zram, index);
1390 } else {
1391 /*
1392 * The slot should be unlocked before reading from the backing
1393 * device.
1394 */
1395 zram_slot_unlock(zram, index);
1396
1397 ret = read_from_bdev(zram, page, zram_get_element(zram, index),
1398 parent);
1399 }
1400
1401 /* Should NEVER happen. Return bio error if it does. */
1402 if (WARN_ON(ret < 0))
1403 pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
1404
1405 return ret;
1406 }
1407
1408 /*
1409 * Use a temporary buffer to decompress the page, as the decompressor
1410 * always expects a full page for the output.
1411 */
zram_bvec_read_partial(struct zram * zram,struct bio_vec * bvec,u32 index,int offset)1412 static int zram_bvec_read_partial(struct zram *zram, struct bio_vec *bvec,
1413 u32 index, int offset)
1414 {
1415 struct page *page = alloc_page(GFP_NOIO);
1416 int ret;
1417
1418 if (!page)
1419 return -ENOMEM;
1420 ret = zram_read_page(zram, page, index, NULL);
1421 if (likely(!ret))
1422 memcpy_to_bvec(bvec, page_address(page) + offset);
1423 __free_page(page);
1424 return ret;
1425 }
1426
zram_bvec_read(struct zram * zram,struct bio_vec * bvec,u32 index,int offset,struct bio * bio)1427 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
1428 u32 index, int offset, struct bio *bio)
1429 {
1430 if (is_partial_io(bvec))
1431 return zram_bvec_read_partial(zram, bvec, index, offset);
1432 return zram_read_page(zram, bvec->bv_page, index, bio);
1433 }
1434
zram_write_page(struct zram * zram,struct page * page,u32 index)1435 static int zram_write_page(struct zram *zram, struct page *page, u32 index)
1436 {
1437 int ret = 0;
1438 unsigned long alloced_pages;
1439 unsigned long handle = -ENOMEM;
1440 unsigned int comp_len = 0;
1441 void *src, *dst, *mem;
1442 struct zcomp_strm *zstrm;
1443 unsigned long element = 0;
1444 enum zram_pageflags flags = 0;
1445
1446 mem = kmap_atomic(page);
1447 if (page_same_filled(mem, &element)) {
1448 kunmap_atomic(mem);
1449 /* Free memory associated with this sector now. */
1450 flags = ZRAM_SAME;
1451 atomic64_inc(&zram->stats.same_pages);
1452 goto out;
1453 }
1454 kunmap_atomic(mem);
1455
1456 compress_again:
1457 zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
1458 src = kmap_atomic(page);
1459 ret = zcomp_compress(zstrm, src, &comp_len);
1460 kunmap_atomic(src);
1461
1462 if (unlikely(ret)) {
1463 zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1464 pr_err("Compression failed! err=%d\n", ret);
1465 zs_free(zram->mem_pool, handle);
1466 return ret;
1467 }
1468
1469 if (comp_len >= huge_class_size)
1470 comp_len = PAGE_SIZE;
1471 /*
1472 * handle allocation has 2 paths:
1473 * a) fast path is executed with preemption disabled (for
1474 * per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
1475 * since we can't sleep;
1476 * b) slow path enables preemption and attempts to allocate
1477 * the page with __GFP_DIRECT_RECLAIM bit set. we have to
1478 * put per-cpu compression stream and, thus, to re-do
1479 * the compression once handle is allocated.
1480 *
1481 * if we have a 'non-null' handle here then we are coming
1482 * from the slow path and handle has already been allocated.
1483 */
1484 if (IS_ERR_VALUE(handle))
1485 handle = zs_malloc(zram->mem_pool, comp_len,
1486 __GFP_KSWAPD_RECLAIM |
1487 __GFP_NOWARN |
1488 __GFP_HIGHMEM |
1489 __GFP_MOVABLE);
1490 if (IS_ERR_VALUE(handle)) {
1491 zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1492 atomic64_inc(&zram->stats.writestall);
1493 handle = zs_malloc(zram->mem_pool, comp_len,
1494 GFP_NOIO | __GFP_HIGHMEM |
1495 __GFP_MOVABLE);
1496 if (IS_ERR_VALUE(handle))
1497 return PTR_ERR((void *)handle);
1498
1499 if (comp_len != PAGE_SIZE)
1500 goto compress_again;
1501 /*
1502 * If the page is not compressible, you need to acquire the
1503 * lock and execute the code below. The zcomp_stream_get()
1504 * call is needed to disable the cpu hotplug and grab the
1505 * zstrm buffer back. It is necessary that the dereferencing
1506 * of the zstrm variable below occurs correctly.
1507 */
1508 zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
1509 }
1510
1511 alloced_pages = zs_get_total_pages(zram->mem_pool);
1512 update_used_max(zram, alloced_pages);
1513
1514 if (zram->limit_pages && alloced_pages > zram->limit_pages) {
1515 zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1516 zs_free(zram->mem_pool, handle);
1517 return -ENOMEM;
1518 }
1519
1520 dst = zs_map_object(zram->mem_pool, handle, ZS_MM_WO);
1521
1522 src = zstrm->buffer;
1523 if (comp_len == PAGE_SIZE)
1524 src = kmap_atomic(page);
1525 memcpy(dst, src, comp_len);
1526 if (comp_len == PAGE_SIZE)
1527 kunmap_atomic(src);
1528
1529 zcomp_stream_put(zram->comps[ZRAM_PRIMARY_COMP]);
1530 zs_unmap_object(zram->mem_pool, handle);
1531 atomic64_add(comp_len, &zram->stats.compr_data_size);
1532 out:
1533 /*
1534 * Free memory associated with this sector
1535 * before overwriting unused sectors.
1536 */
1537 zram_slot_lock(zram, index);
1538 zram_free_page(zram, index);
1539
1540 if (comp_len == PAGE_SIZE) {
1541 zram_set_flag(zram, index, ZRAM_HUGE);
1542 atomic64_inc(&zram->stats.huge_pages);
1543 atomic64_inc(&zram->stats.huge_pages_since);
1544 }
1545
1546 if (flags) {
1547 zram_set_flag(zram, index, flags);
1548 zram_set_element(zram, index, element);
1549 } else {
1550 zram_set_handle(zram, index, handle);
1551 zram_set_obj_size(zram, index, comp_len);
1552 }
1553 zram_slot_unlock(zram, index);
1554
1555 /* Update stats */
1556 atomic64_inc(&zram->stats.pages_stored);
1557 return ret;
1558 }
1559
1560 /*
1561 * This is a partial IO. Read the full page before writing the changes.
1562 */
zram_bvec_write_partial(struct zram * zram,struct bio_vec * bvec,u32 index,int offset,struct bio * bio)1563 static int zram_bvec_write_partial(struct zram *zram, struct bio_vec *bvec,
1564 u32 index, int offset, struct bio *bio)
1565 {
1566 struct page *page = alloc_page(GFP_NOIO);
1567 int ret;
1568
1569 if (!page)
1570 return -ENOMEM;
1571
1572 ret = zram_read_page(zram, page, index, bio);
1573 if (!ret) {
1574 memcpy_from_bvec(page_address(page) + offset, bvec);
1575 ret = zram_write_page(zram, page, index);
1576 }
1577 __free_page(page);
1578 return ret;
1579 }
1580
zram_bvec_write(struct zram * zram,struct bio_vec * bvec,u32 index,int offset,struct bio * bio)1581 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
1582 u32 index, int offset, struct bio *bio)
1583 {
1584 if (is_partial_io(bvec))
1585 return zram_bvec_write_partial(zram, bvec, index, offset, bio);
1586 return zram_write_page(zram, bvec->bv_page, index);
1587 }
1588
1589 #ifdef CONFIG_ZRAM_MULTI_COMP
1590 /*
1591 * This function will decompress (unless it's ZRAM_HUGE) the page and then
1592 * attempt to compress it using provided compression algorithm priority
1593 * (which is potentially more effective).
1594 *
1595 * Corresponding ZRAM slot should be locked.
1596 */
zram_recompress(struct zram * zram,u32 index,struct page * page,u32 threshold,u32 prio,u32 prio_max)1597 static int zram_recompress(struct zram *zram, u32 index, struct page *page,
1598 u32 threshold, u32 prio, u32 prio_max)
1599 {
1600 struct zcomp_strm *zstrm = NULL;
1601 unsigned long handle_old;
1602 unsigned long handle_new;
1603 unsigned int comp_len_old;
1604 unsigned int comp_len_new;
1605 unsigned int class_index_old;
1606 unsigned int class_index_new;
1607 u32 num_recomps = 0;
1608 void *src, *dst;
1609 int ret;
1610
1611 handle_old = zram_get_handle(zram, index);
1612 if (!handle_old)
1613 return -EINVAL;
1614
1615 comp_len_old = zram_get_obj_size(zram, index);
1616 /*
1617 * Do not recompress objects that are already "small enough".
1618 */
1619 if (comp_len_old < threshold)
1620 return 0;
1621
1622 ret = zram_read_from_zspool(zram, page, index);
1623 if (ret)
1624 return ret;
1625
1626 /*
1627 * We touched this entry so mark it as non-IDLE. This makes sure that
1628 * we don't preserve IDLE flag and don't incorrectly pick this entry
1629 * for different post-processing type (e.g. writeback).
1630 */
1631 zram_clear_flag(zram, index, ZRAM_IDLE);
1632
1633 class_index_old = zs_lookup_class_index(zram->mem_pool, comp_len_old);
1634 /*
1635 * Iterate the secondary comp algorithms list (in order of priority)
1636 * and try to recompress the page.
1637 */
1638 for (; prio < prio_max; prio++) {
1639 if (!zram->comps[prio])
1640 continue;
1641
1642 /*
1643 * Skip if the object is already re-compressed with a higher
1644 * priority algorithm (or same algorithm).
1645 */
1646 if (prio <= zram_get_priority(zram, index))
1647 continue;
1648
1649 num_recomps++;
1650 zstrm = zcomp_stream_get(zram->comps[prio]);
1651 src = kmap_atomic(page);
1652 ret = zcomp_compress(zstrm, src, &comp_len_new);
1653 kunmap_atomic(src);
1654
1655 if (ret) {
1656 zcomp_stream_put(zram->comps[prio]);
1657 return ret;
1658 }
1659
1660 class_index_new = zs_lookup_class_index(zram->mem_pool,
1661 comp_len_new);
1662
1663 /* Continue until we make progress */
1664 if (class_index_new >= class_index_old ||
1665 (threshold && comp_len_new >= threshold)) {
1666 zcomp_stream_put(zram->comps[prio]);
1667 continue;
1668 }
1669
1670 /* Recompression was successful so break out */
1671 break;
1672 }
1673
1674 /*
1675 * We did not try to recompress, e.g. when we have only one
1676 * secondary algorithm and the page is already recompressed
1677 * using that algorithm
1678 */
1679 if (!zstrm)
1680 return 0;
1681
1682 if (class_index_new >= class_index_old) {
1683 /*
1684 * Secondary algorithms failed to re-compress the page
1685 * in a way that would save memory, mark the object as
1686 * incompressible so that we will not try to compress
1687 * it again.
1688 *
1689 * We need to make sure that all secondary algorithms have
1690 * failed, so we test if the number of recompressions matches
1691 * the number of active secondary algorithms.
1692 */
1693 if (num_recomps == zram->num_active_comps - 1)
1694 zram_set_flag(zram, index, ZRAM_INCOMPRESSIBLE);
1695 return 0;
1696 }
1697
1698 /* Successful recompression but above threshold */
1699 if (threshold && comp_len_new >= threshold)
1700 return 0;
1701
1702 /*
1703 * No direct reclaim (slow path) for handle allocation and no
1704 * re-compression attempt (unlike in zram_write_bvec()) since
1705 * we already have stored that object in zsmalloc. If we cannot
1706 * alloc memory for recompressed object then we bail out and
1707 * simply keep the old (existing) object in zsmalloc.
1708 */
1709 handle_new = zs_malloc(zram->mem_pool, comp_len_new,
1710 __GFP_KSWAPD_RECLAIM |
1711 __GFP_NOWARN |
1712 __GFP_HIGHMEM |
1713 __GFP_MOVABLE);
1714 if (IS_ERR_VALUE(handle_new)) {
1715 zcomp_stream_put(zram->comps[prio]);
1716 return PTR_ERR((void *)handle_new);
1717 }
1718
1719 dst = zs_map_object(zram->mem_pool, handle_new, ZS_MM_WO);
1720 memcpy(dst, zstrm->buffer, comp_len_new);
1721 zcomp_stream_put(zram->comps[prio]);
1722
1723 zs_unmap_object(zram->mem_pool, handle_new);
1724
1725 zram_free_page(zram, index);
1726 zram_set_handle(zram, index, handle_new);
1727 zram_set_obj_size(zram, index, comp_len_new);
1728 zram_set_priority(zram, index, prio);
1729
1730 atomic64_add(comp_len_new, &zram->stats.compr_data_size);
1731 atomic64_inc(&zram->stats.pages_stored);
1732
1733 return 0;
1734 }
1735
1736 #define RECOMPRESS_IDLE (1 << 0)
1737 #define RECOMPRESS_HUGE (1 << 1)
1738
recompress_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1739 static ssize_t recompress_store(struct device *dev,
1740 struct device_attribute *attr,
1741 const char *buf, size_t len)
1742 {
1743 u32 prio = ZRAM_SECONDARY_COMP, prio_max = ZRAM_MAX_COMPS;
1744 struct zram *zram = dev_to_zram(dev);
1745 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
1746 char *args, *param, *val, *algo = NULL;
1747 u32 mode = 0, threshold = 0;
1748 unsigned long index;
1749 struct page *page;
1750 ssize_t ret;
1751
1752 args = skip_spaces(buf);
1753 while (*args) {
1754 args = next_arg(args, ¶m, &val);
1755
1756 if (!val || !*val)
1757 return -EINVAL;
1758
1759 if (!strcmp(param, "type")) {
1760 if (!strcmp(val, "idle"))
1761 mode = RECOMPRESS_IDLE;
1762 if (!strcmp(val, "huge"))
1763 mode = RECOMPRESS_HUGE;
1764 if (!strcmp(val, "huge_idle"))
1765 mode = RECOMPRESS_IDLE | RECOMPRESS_HUGE;
1766 continue;
1767 }
1768
1769 if (!strcmp(param, "threshold")) {
1770 /*
1771 * We will re-compress only idle objects equal or
1772 * greater in size than watermark.
1773 */
1774 ret = kstrtouint(val, 10, &threshold);
1775 if (ret)
1776 return ret;
1777 continue;
1778 }
1779
1780 if (!strcmp(param, "algo")) {
1781 algo = val;
1782 continue;
1783 }
1784 }
1785
1786 if (threshold >= huge_class_size)
1787 return -EINVAL;
1788
1789 down_read(&zram->init_lock);
1790 if (!init_done(zram)) {
1791 ret = -EINVAL;
1792 goto release_init_lock;
1793 }
1794
1795 if (algo) {
1796 bool found = false;
1797
1798 for (; prio < ZRAM_MAX_COMPS; prio++) {
1799 if (!zram->comp_algs[prio])
1800 continue;
1801
1802 if (!strcmp(zram->comp_algs[prio], algo)) {
1803 prio_max = min(prio + 1, ZRAM_MAX_COMPS);
1804 found = true;
1805 break;
1806 }
1807 }
1808
1809 if (!found) {
1810 ret = -EINVAL;
1811 goto release_init_lock;
1812 }
1813 }
1814
1815 page = alloc_page(GFP_KERNEL);
1816 if (!page) {
1817 ret = -ENOMEM;
1818 goto release_init_lock;
1819 }
1820
1821 ret = len;
1822 for (index = 0; index < nr_pages; index++) {
1823 int err = 0;
1824
1825 zram_slot_lock(zram, index);
1826
1827 if (!zram_allocated(zram, index))
1828 goto next;
1829
1830 if (mode & RECOMPRESS_IDLE &&
1831 !zram_test_flag(zram, index, ZRAM_IDLE))
1832 goto next;
1833
1834 if (mode & RECOMPRESS_HUGE &&
1835 !zram_test_flag(zram, index, ZRAM_HUGE))
1836 goto next;
1837
1838 if (zram_test_flag(zram, index, ZRAM_WB) ||
1839 zram_test_flag(zram, index, ZRAM_UNDER_WB) ||
1840 zram_test_flag(zram, index, ZRAM_SAME) ||
1841 zram_test_flag(zram, index, ZRAM_INCOMPRESSIBLE))
1842 goto next;
1843
1844 err = zram_recompress(zram, index, page, threshold,
1845 prio, prio_max);
1846 next:
1847 zram_slot_unlock(zram, index);
1848 if (err) {
1849 ret = err;
1850 break;
1851 }
1852
1853 cond_resched();
1854 }
1855
1856 __free_page(page);
1857
1858 release_init_lock:
1859 up_read(&zram->init_lock);
1860 return ret;
1861 }
1862 #endif
1863
zram_bio_discard(struct zram * zram,struct bio * bio)1864 static void zram_bio_discard(struct zram *zram, struct bio *bio)
1865 {
1866 size_t n = bio->bi_iter.bi_size;
1867 u32 index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1868 u32 offset = (bio->bi_iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
1869 SECTOR_SHIFT;
1870
1871 /*
1872 * zram manages data in physical block size units. Because logical block
1873 * size isn't identical with physical block size on some arch, we
1874 * could get a discard request pointing to a specific offset within a
1875 * certain physical block. Although we can handle this request by
1876 * reading that physiclal block and decompressing and partially zeroing
1877 * and re-compressing and then re-storing it, this isn't reasonable
1878 * because our intent with a discard request is to save memory. So
1879 * skipping this logical block is appropriate here.
1880 */
1881 if (offset) {
1882 if (n <= (PAGE_SIZE - offset))
1883 return;
1884
1885 n -= (PAGE_SIZE - offset);
1886 index++;
1887 }
1888
1889 while (n >= PAGE_SIZE) {
1890 zram_slot_lock(zram, index);
1891 zram_free_page(zram, index);
1892 zram_slot_unlock(zram, index);
1893 atomic64_inc(&zram->stats.notify_free);
1894 index++;
1895 n -= PAGE_SIZE;
1896 }
1897
1898 bio_endio(bio);
1899 }
1900
zram_bio_read(struct zram * zram,struct bio * bio)1901 static void zram_bio_read(struct zram *zram, struct bio *bio)
1902 {
1903 unsigned long start_time = bio_start_io_acct(bio);
1904 struct bvec_iter iter = bio->bi_iter;
1905
1906 do {
1907 u32 index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1908 u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
1909 SECTOR_SHIFT;
1910 struct bio_vec bv = bio_iter_iovec(bio, iter);
1911
1912 bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
1913
1914 if (zram_bvec_read(zram, &bv, index, offset, bio) < 0) {
1915 atomic64_inc(&zram->stats.failed_reads);
1916 bio->bi_status = BLK_STS_IOERR;
1917 break;
1918 }
1919 flush_dcache_page(bv.bv_page);
1920
1921 zram_slot_lock(zram, index);
1922 zram_accessed(zram, index);
1923 zram_slot_unlock(zram, index);
1924
1925 bio_advance_iter_single(bio, &iter, bv.bv_len);
1926 } while (iter.bi_size);
1927
1928 bio_end_io_acct(bio, start_time);
1929 bio_endio(bio);
1930 }
1931
zram_bio_write(struct zram * zram,struct bio * bio)1932 static void zram_bio_write(struct zram *zram, struct bio *bio)
1933 {
1934 unsigned long start_time = bio_start_io_acct(bio);
1935 struct bvec_iter iter = bio->bi_iter;
1936
1937 do {
1938 u32 index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
1939 u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
1940 SECTOR_SHIFT;
1941 struct bio_vec bv = bio_iter_iovec(bio, iter);
1942
1943 bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
1944
1945 if (zram_bvec_write(zram, &bv, index, offset, bio) < 0) {
1946 atomic64_inc(&zram->stats.failed_writes);
1947 bio->bi_status = BLK_STS_IOERR;
1948 break;
1949 }
1950
1951 zram_slot_lock(zram, index);
1952 zram_accessed(zram, index);
1953 zram_slot_unlock(zram, index);
1954
1955 bio_advance_iter_single(bio, &iter, bv.bv_len);
1956 } while (iter.bi_size);
1957
1958 bio_end_io_acct(bio, start_time);
1959 bio_endio(bio);
1960 }
1961
1962 /*
1963 * Handler function for all zram I/O requests.
1964 */
zram_submit_bio(struct bio * bio)1965 static void zram_submit_bio(struct bio *bio)
1966 {
1967 struct zram *zram = bio->bi_bdev->bd_disk->private_data;
1968
1969 switch (bio_op(bio)) {
1970 case REQ_OP_READ:
1971 zram_bio_read(zram, bio);
1972 break;
1973 case REQ_OP_WRITE:
1974 zram_bio_write(zram, bio);
1975 break;
1976 case REQ_OP_DISCARD:
1977 case REQ_OP_WRITE_ZEROES:
1978 zram_bio_discard(zram, bio);
1979 break;
1980 default:
1981 WARN_ON_ONCE(1);
1982 bio_endio(bio);
1983 }
1984 }
1985
zram_slot_free_notify(struct block_device * bdev,unsigned long index)1986 static void zram_slot_free_notify(struct block_device *bdev,
1987 unsigned long index)
1988 {
1989 struct zram *zram;
1990
1991 zram = bdev->bd_disk->private_data;
1992
1993 atomic64_inc(&zram->stats.notify_free);
1994 if (!zram_slot_trylock(zram, index)) {
1995 atomic64_inc(&zram->stats.miss_free);
1996 return;
1997 }
1998
1999 zram_free_page(zram, index);
2000 zram_slot_unlock(zram, index);
2001 }
2002
zram_destroy_comps(struct zram * zram)2003 static void zram_destroy_comps(struct zram *zram)
2004 {
2005 u32 prio;
2006
2007 for (prio = 0; prio < ZRAM_MAX_COMPS; prio++) {
2008 struct zcomp *comp = zram->comps[prio];
2009
2010 zram->comps[prio] = NULL;
2011 if (!comp)
2012 continue;
2013 zcomp_destroy(comp);
2014 zram->num_active_comps--;
2015 }
2016
2017 for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
2018 /* Do not free statically defined compression algorithms */
2019 if (zram->comp_algs[prio] != default_compressor)
2020 kfree(zram->comp_algs[prio]);
2021 zram->comp_algs[prio] = NULL;
2022 }
2023 }
2024
zram_reset_device(struct zram * zram)2025 static void zram_reset_device(struct zram *zram)
2026 {
2027 down_write(&zram->init_lock);
2028
2029 zram->limit_pages = 0;
2030
2031 set_capacity_and_notify(zram->disk, 0);
2032 part_stat_set_all(zram->disk->part0, 0);
2033
2034 /* I/O operation under all of CPU are done so let's free */
2035 zram_meta_free(zram, zram->disksize);
2036 zram->disksize = 0;
2037 zram_destroy_comps(zram);
2038 memset(&zram->stats, 0, sizeof(zram->stats));
2039 reset_bdev(zram);
2040
2041 comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
2042 up_write(&zram->init_lock);
2043 }
2044
disksize_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)2045 static ssize_t disksize_store(struct device *dev,
2046 struct device_attribute *attr, const char *buf, size_t len)
2047 {
2048 u64 disksize;
2049 struct zcomp *comp;
2050 struct zram *zram = dev_to_zram(dev);
2051 int err;
2052 u32 prio;
2053
2054 disksize = memparse(buf, NULL);
2055 if (!disksize)
2056 return -EINVAL;
2057
2058 down_write(&zram->init_lock);
2059 if (init_done(zram)) {
2060 pr_info("Cannot change disksize for initialized device\n");
2061 err = -EBUSY;
2062 goto out_unlock;
2063 }
2064
2065 disksize = PAGE_ALIGN(disksize);
2066 if (!zram_meta_alloc(zram, disksize)) {
2067 err = -ENOMEM;
2068 goto out_unlock;
2069 }
2070
2071 for (prio = 0; prio < ZRAM_MAX_COMPS; prio++) {
2072 if (!zram->comp_algs[prio])
2073 continue;
2074
2075 comp = zcomp_create(zram->comp_algs[prio]);
2076 if (IS_ERR(comp)) {
2077 pr_err("Cannot initialise %s compressing backend\n",
2078 zram->comp_algs[prio]);
2079 err = PTR_ERR(comp);
2080 goto out_free_comps;
2081 }
2082
2083 zram->comps[prio] = comp;
2084 zram->num_active_comps++;
2085 }
2086 zram->disksize = disksize;
2087 set_capacity_and_notify(zram->disk, zram->disksize >> SECTOR_SHIFT);
2088 up_write(&zram->init_lock);
2089
2090 return len;
2091
2092 out_free_comps:
2093 zram_destroy_comps(zram);
2094 zram_meta_free(zram, disksize);
2095 out_unlock:
2096 up_write(&zram->init_lock);
2097 return err;
2098 }
2099
reset_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)2100 static ssize_t reset_store(struct device *dev,
2101 struct device_attribute *attr, const char *buf, size_t len)
2102 {
2103 int ret;
2104 unsigned short do_reset;
2105 struct zram *zram;
2106 struct gendisk *disk;
2107
2108 ret = kstrtou16(buf, 10, &do_reset);
2109 if (ret)
2110 return ret;
2111
2112 if (!do_reset)
2113 return -EINVAL;
2114
2115 zram = dev_to_zram(dev);
2116 disk = zram->disk;
2117
2118 mutex_lock(&disk->open_mutex);
2119 /* Do not reset an active device or claimed device */
2120 if (disk_openers(disk) || zram->claim) {
2121 mutex_unlock(&disk->open_mutex);
2122 return -EBUSY;
2123 }
2124
2125 /* From now on, anyone can't open /dev/zram[0-9] */
2126 zram->claim = true;
2127 mutex_unlock(&disk->open_mutex);
2128
2129 /* Make sure all the pending I/O are finished */
2130 sync_blockdev(disk->part0);
2131 zram_reset_device(zram);
2132
2133 mutex_lock(&disk->open_mutex);
2134 zram->claim = false;
2135 mutex_unlock(&disk->open_mutex);
2136
2137 return len;
2138 }
2139
zram_open(struct gendisk * disk,blk_mode_t mode)2140 static int zram_open(struct gendisk *disk, blk_mode_t mode)
2141 {
2142 struct zram *zram = disk->private_data;
2143
2144 WARN_ON(!mutex_is_locked(&disk->open_mutex));
2145
2146 /* zram was claimed to reset so open request fails */
2147 if (zram->claim)
2148 return -EBUSY;
2149 return 0;
2150 }
2151
2152 static const struct block_device_operations zram_devops = {
2153 .open = zram_open,
2154 .submit_bio = zram_submit_bio,
2155 .swap_slot_free_notify = zram_slot_free_notify,
2156 .owner = THIS_MODULE
2157 };
2158
2159 static DEVICE_ATTR_WO(compact);
2160 static DEVICE_ATTR_RW(disksize);
2161 static DEVICE_ATTR_RO(initstate);
2162 static DEVICE_ATTR_WO(reset);
2163 static DEVICE_ATTR_WO(mem_limit);
2164 static DEVICE_ATTR_WO(mem_used_max);
2165 static DEVICE_ATTR_WO(idle);
2166 static DEVICE_ATTR_RW(max_comp_streams);
2167 static DEVICE_ATTR_RW(comp_algorithm);
2168 #ifdef CONFIG_ZRAM_WRITEBACK
2169 static DEVICE_ATTR_RW(backing_dev);
2170 static DEVICE_ATTR_WO(writeback);
2171 static DEVICE_ATTR_RW(writeback_limit);
2172 static DEVICE_ATTR_RW(writeback_limit_enable);
2173 #endif
2174 #ifdef CONFIG_ZRAM_MULTI_COMP
2175 static DEVICE_ATTR_RW(recomp_algorithm);
2176 static DEVICE_ATTR_WO(recompress);
2177 #endif
2178
2179 static struct attribute *zram_disk_attrs[] = {
2180 &dev_attr_disksize.attr,
2181 &dev_attr_initstate.attr,
2182 &dev_attr_reset.attr,
2183 &dev_attr_compact.attr,
2184 &dev_attr_mem_limit.attr,
2185 &dev_attr_mem_used_max.attr,
2186 &dev_attr_idle.attr,
2187 &dev_attr_max_comp_streams.attr,
2188 &dev_attr_comp_algorithm.attr,
2189 #ifdef CONFIG_ZRAM_WRITEBACK
2190 &dev_attr_backing_dev.attr,
2191 &dev_attr_writeback.attr,
2192 &dev_attr_writeback_limit.attr,
2193 &dev_attr_writeback_limit_enable.attr,
2194 #endif
2195 &dev_attr_io_stat.attr,
2196 &dev_attr_mm_stat.attr,
2197 #ifdef CONFIG_ZRAM_WRITEBACK
2198 &dev_attr_bd_stat.attr,
2199 #endif
2200 &dev_attr_debug_stat.attr,
2201 #ifdef CONFIG_ZRAM_MULTI_COMP
2202 &dev_attr_recomp_algorithm.attr,
2203 &dev_attr_recompress.attr,
2204 #endif
2205 NULL,
2206 };
2207
2208 ATTRIBUTE_GROUPS(zram_disk);
2209
2210 /*
2211 * Allocate and initialize new zram device. the function returns
2212 * '>= 0' device_id upon success, and negative value otherwise.
2213 */
zram_add(void)2214 static int zram_add(void)
2215 {
2216 struct zram *zram;
2217 int ret, device_id;
2218
2219 zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
2220 if (!zram)
2221 return -ENOMEM;
2222
2223 ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
2224 if (ret < 0)
2225 goto out_free_dev;
2226 device_id = ret;
2227
2228 init_rwsem(&zram->init_lock);
2229 #ifdef CONFIG_ZRAM_WRITEBACK
2230 spin_lock_init(&zram->wb_limit_lock);
2231 #endif
2232
2233 /* gendisk structure */
2234 zram->disk = blk_alloc_disk(NUMA_NO_NODE);
2235 if (!zram->disk) {
2236 pr_err("Error allocating disk structure for device %d\n",
2237 device_id);
2238 ret = -ENOMEM;
2239 goto out_free_idr;
2240 }
2241
2242 zram->disk->major = zram_major;
2243 zram->disk->first_minor = device_id;
2244 zram->disk->minors = 1;
2245 zram->disk->flags |= GENHD_FL_NO_PART;
2246 zram->disk->fops = &zram_devops;
2247 zram->disk->private_data = zram;
2248 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
2249
2250 /* Actual capacity set using sysfs (/sys/block/zram<id>/disksize */
2251 set_capacity(zram->disk, 0);
2252 /* zram devices sort of resembles non-rotational disks */
2253 blk_queue_flag_set(QUEUE_FLAG_NONROT, zram->disk->queue);
2254 blk_queue_flag_set(QUEUE_FLAG_SYNCHRONOUS, zram->disk->queue);
2255
2256 /*
2257 * To ensure that we always get PAGE_SIZE aligned
2258 * and n*PAGE_SIZED sized I/O requests.
2259 */
2260 blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
2261 blk_queue_logical_block_size(zram->disk->queue,
2262 ZRAM_LOGICAL_BLOCK_SIZE);
2263 blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
2264 blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
2265 zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
2266 blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
2267
2268 /*
2269 * zram_bio_discard() will clear all logical blocks if logical block
2270 * size is identical with physical block size(PAGE_SIZE). But if it is
2271 * different, we will skip discarding some parts of logical blocks in
2272 * the part of the request range which isn't aligned to physical block
2273 * size. So we can't ensure that all discarded logical blocks are
2274 * zeroed.
2275 */
2276 if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
2277 blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
2278
2279 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, zram->disk->queue);
2280 ret = device_add_disk(NULL, zram->disk, zram_disk_groups);
2281 if (ret)
2282 goto out_cleanup_disk;
2283
2284 comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
2285
2286 zram_debugfs_register(zram);
2287 pr_info("Added device: %s\n", zram->disk->disk_name);
2288 return device_id;
2289
2290 out_cleanup_disk:
2291 put_disk(zram->disk);
2292 out_free_idr:
2293 idr_remove(&zram_index_idr, device_id);
2294 out_free_dev:
2295 kfree(zram);
2296 return ret;
2297 }
2298
zram_remove(struct zram * zram)2299 static int zram_remove(struct zram *zram)
2300 {
2301 bool claimed;
2302
2303 mutex_lock(&zram->disk->open_mutex);
2304 if (disk_openers(zram->disk)) {
2305 mutex_unlock(&zram->disk->open_mutex);
2306 return -EBUSY;
2307 }
2308
2309 claimed = zram->claim;
2310 if (!claimed)
2311 zram->claim = true;
2312 mutex_unlock(&zram->disk->open_mutex);
2313
2314 zram_debugfs_unregister(zram);
2315
2316 if (claimed) {
2317 /*
2318 * If we were claimed by reset_store(), del_gendisk() will
2319 * wait until reset_store() is done, so nothing need to do.
2320 */
2321 ;
2322 } else {
2323 /* Make sure all the pending I/O are finished */
2324 sync_blockdev(zram->disk->part0);
2325 zram_reset_device(zram);
2326 }
2327
2328 pr_info("Removed device: %s\n", zram->disk->disk_name);
2329
2330 del_gendisk(zram->disk);
2331
2332 /* del_gendisk drains pending reset_store */
2333 WARN_ON_ONCE(claimed && zram->claim);
2334
2335 /*
2336 * disksize_store() may be called in between zram_reset_device()
2337 * and del_gendisk(), so run the last reset to avoid leaking
2338 * anything allocated with disksize_store()
2339 */
2340 zram_reset_device(zram);
2341
2342 put_disk(zram->disk);
2343 kfree(zram);
2344 return 0;
2345 }
2346
2347 /* zram-control sysfs attributes */
2348
2349 /*
2350 * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
2351 * sense that reading from this file does alter the state of your system -- it
2352 * creates a new un-initialized zram device and returns back this device's
2353 * device_id (or an error code if it fails to create a new device).
2354 */
hot_add_show(const struct class * class,const struct class_attribute * attr,char * buf)2355 static ssize_t hot_add_show(const struct class *class,
2356 const struct class_attribute *attr,
2357 char *buf)
2358 {
2359 int ret;
2360
2361 mutex_lock(&zram_index_mutex);
2362 ret = zram_add();
2363 mutex_unlock(&zram_index_mutex);
2364
2365 if (ret < 0)
2366 return ret;
2367 return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
2368 }
2369 /* This attribute must be set to 0400, so CLASS_ATTR_RO() can not be used */
2370 static struct class_attribute class_attr_hot_add =
2371 __ATTR(hot_add, 0400, hot_add_show, NULL);
2372
hot_remove_store(const struct class * class,const struct class_attribute * attr,const char * buf,size_t count)2373 static ssize_t hot_remove_store(const struct class *class,
2374 const struct class_attribute *attr,
2375 const char *buf,
2376 size_t count)
2377 {
2378 struct zram *zram;
2379 int ret, dev_id;
2380
2381 /* dev_id is gendisk->first_minor, which is `int' */
2382 ret = kstrtoint(buf, 10, &dev_id);
2383 if (ret)
2384 return ret;
2385 if (dev_id < 0)
2386 return -EINVAL;
2387
2388 mutex_lock(&zram_index_mutex);
2389
2390 zram = idr_find(&zram_index_idr, dev_id);
2391 if (zram) {
2392 ret = zram_remove(zram);
2393 if (!ret)
2394 idr_remove(&zram_index_idr, dev_id);
2395 } else {
2396 ret = -ENODEV;
2397 }
2398
2399 mutex_unlock(&zram_index_mutex);
2400 return ret ? ret : count;
2401 }
2402 static CLASS_ATTR_WO(hot_remove);
2403
2404 static struct attribute *zram_control_class_attrs[] = {
2405 &class_attr_hot_add.attr,
2406 &class_attr_hot_remove.attr,
2407 NULL,
2408 };
2409 ATTRIBUTE_GROUPS(zram_control_class);
2410
2411 static struct class zram_control_class = {
2412 .name = "zram-control",
2413 .class_groups = zram_control_class_groups,
2414 };
2415
zram_remove_cb(int id,void * ptr,void * data)2416 static int zram_remove_cb(int id, void *ptr, void *data)
2417 {
2418 WARN_ON_ONCE(zram_remove(ptr));
2419 return 0;
2420 }
2421
destroy_devices(void)2422 static void destroy_devices(void)
2423 {
2424 class_unregister(&zram_control_class);
2425 idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
2426 zram_debugfs_destroy();
2427 idr_destroy(&zram_index_idr);
2428 unregister_blkdev(zram_major, "zram");
2429 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2430 }
2431
zram_init(void)2432 static int __init zram_init(void)
2433 {
2434 int ret;
2435
2436 BUILD_BUG_ON(__NR_ZRAM_PAGEFLAGS > BITS_PER_LONG);
2437
2438 ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
2439 zcomp_cpu_up_prepare, zcomp_cpu_dead);
2440 if (ret < 0)
2441 return ret;
2442
2443 ret = class_register(&zram_control_class);
2444 if (ret) {
2445 pr_err("Unable to register zram-control class\n");
2446 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2447 return ret;
2448 }
2449
2450 zram_debugfs_create();
2451 zram_major = register_blkdev(0, "zram");
2452 if (zram_major <= 0) {
2453 pr_err("Unable to get major number\n");
2454 class_unregister(&zram_control_class);
2455 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
2456 return -EBUSY;
2457 }
2458
2459 while (num_devices != 0) {
2460 mutex_lock(&zram_index_mutex);
2461 ret = zram_add();
2462 mutex_unlock(&zram_index_mutex);
2463 if (ret < 0)
2464 goto out_error;
2465 num_devices--;
2466 }
2467
2468 return 0;
2469
2470 out_error:
2471 destroy_devices();
2472 return ret;
2473 }
2474
zram_exit(void)2475 static void __exit zram_exit(void)
2476 {
2477 destroy_devices();
2478 }
2479
2480 module_init(zram_init);
2481 module_exit(zram_exit);
2482
2483 module_param(num_devices, uint, 0);
2484 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
2485
2486 MODULE_LICENSE("Dual BSD/GPL");
2487 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2488 MODULE_DESCRIPTION("Compressed RAM Block Device");
2489