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 pr_fmt(fmt) "zram: " fmt
16
17 #include <linux/module.h>
18 #include <linux/kernel.h>
19 #include <linux/bio.h>
20 #include <linux/bitops.h>
21 #include <linux/blkdev.h>
22 #include <linux/buffer_head.h>
23 #include <linux/device.h>
24 #include <linux/highmem.h>
25 #include <linux/slab.h>
26 #include <linux/backing-dev.h>
27 #include <linux/string.h>
28 #include <linux/vmalloc.h>
29 #include <linux/err.h>
30 #include <linux/idr.h>
31 #include <linux/sysfs.h>
32 #include <linux/debugfs.h>
33 #include <linux/cpuhotplug.h>
34 #include <linux/part_stat.h>
35 #include <linux/kernel_read_file.h>
36 #include <linux/rcupdate.h>
37
38 #include "zram_drv.h"
39
40 static DEFINE_IDR(zram_index_idr);
41 /* idr index must be protected */
42 static DEFINE_MUTEX(zram_index_mutex);
43
44 static int zram_major;
45 static const char *default_compressor = CONFIG_ZRAM_DEF_COMP;
46
47 #define ZRAM_MAX_ALGO_NAME_SZ 128
48
49 /* Module params (documentation at end) */
50 static unsigned int num_devices = 1;
51 /*
52 * Pages that compress to sizes equals or greater than this are stored
53 * uncompressed in memory.
54 */
55 static size_t huge_class_size;
56
57 static const struct block_device_operations zram_devops;
58
59 static void slot_free(struct zram *zram, unsigned long index);
60
61 /*
62 * entry locking rules:
63 *
64 * 1) Lock is exclusive
65 *
66 * 2) lock() function can sleep waiting for the lock
67 *
68 * 3) Lock owner can sleep
69 *
70 * 4) Use TRY lock variant when in atomic context
71 * - must check return value and handle locking failers
72 */
slot_trylock(struct zram * zram,unsigned long index)73 static __must_check bool slot_trylock(struct zram *zram, unsigned long index)
74 {
75 unsigned long *lock = &zram->table[index].__lock;
76
77 if (!test_and_set_bit_lock(ZRAM_ENTRY_LOCK_BIT, lock)) {
78 mutex_acquire(&zram->table_lock_map, 0, 1, _RET_IP_);
79 lock_acquired(&zram->table_lock_map, _RET_IP_);
80 return true;
81 }
82
83 return false;
84 }
85
slot_lock(struct zram * zram,unsigned long index)86 static void slot_lock(struct zram *zram, unsigned long index)
87 {
88 unsigned long *lock = &zram->table[index].__lock;
89
90 mutex_acquire(&zram->table_lock_map, 0, 0, _RET_IP_);
91 wait_on_bit_lock(lock, ZRAM_ENTRY_LOCK_BIT, TASK_UNINTERRUPTIBLE);
92 lock_acquired(&zram->table_lock_map, _RET_IP_);
93 }
94
slot_unlock(struct zram * zram,unsigned long index)95 static void slot_unlock(struct zram *zram, unsigned long index)
96 {
97 unsigned long *lock = &zram->table[index].__lock;
98
99 mutex_release(&zram->table_lock_map, _RET_IP_);
100 clear_and_wake_up_bit(ZRAM_ENTRY_LOCK_BIT, lock);
101 }
102
init_done(struct zram * zram)103 static inline bool init_done(struct zram *zram)
104 {
105 return zram->disksize;
106 }
107
dev_to_zram(struct device * dev)108 static inline struct zram *dev_to_zram(struct device *dev)
109 {
110 return (struct zram *)dev_to_disk(dev)->private_data;
111 }
112
get_slot_handle(struct zram * zram,unsigned long index)113 static unsigned long get_slot_handle(struct zram *zram, unsigned long index)
114 {
115 return zram->table[index].handle;
116 }
117
set_slot_handle(struct zram * zram,unsigned long index,unsigned long handle)118 static void set_slot_handle(struct zram *zram, unsigned long index,
119 unsigned long handle)
120 {
121 zram->table[index].handle = handle;
122 }
123
test_slot_flag(struct zram * zram,unsigned long index,enum zram_pageflags flag)124 static bool test_slot_flag(struct zram *zram, unsigned long index,
125 enum zram_pageflags flag)
126 {
127 return zram->table[index].attr.flags & BIT(flag);
128 }
129
set_slot_flag(struct zram * zram,unsigned long index,enum zram_pageflags flag)130 static void set_slot_flag(struct zram *zram, unsigned long index,
131 enum zram_pageflags flag)
132 {
133 zram->table[index].attr.flags |= BIT(flag);
134 }
135
clear_slot_flag(struct zram * zram,unsigned long index,enum zram_pageflags flag)136 static void clear_slot_flag(struct zram *zram, unsigned long index,
137 enum zram_pageflags flag)
138 {
139 zram->table[index].attr.flags &= ~BIT(flag);
140 }
141
get_slot_size(struct zram * zram,unsigned long index)142 static size_t get_slot_size(struct zram *zram, unsigned long index)
143 {
144 return zram->table[index].attr.flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
145 }
146
set_slot_size(struct zram * zram,unsigned long index,size_t size)147 static void set_slot_size(struct zram *zram, unsigned long index, size_t size)
148 {
149 unsigned long flags = zram->table[index].attr.flags >> ZRAM_FLAG_SHIFT;
150
151 zram->table[index].attr.flags = (flags << ZRAM_FLAG_SHIFT) | size;
152 }
153
slot_allocated(struct zram * zram,unsigned long index)154 static inline bool slot_allocated(struct zram *zram, unsigned long index)
155 {
156 return get_slot_size(zram, index) ||
157 test_slot_flag(zram, index, ZRAM_SAME) ||
158 test_slot_flag(zram, index, ZRAM_WB);
159 }
160
set_slot_comp_priority(struct zram * zram,unsigned long index,u32 prio)161 static inline void set_slot_comp_priority(struct zram *zram,
162 unsigned long index, u32 prio)
163 {
164 prio &= ZRAM_COMP_PRIORITY_MASK;
165 /*
166 * Clear previous priority value first, in case if we recompress
167 * further an already recompressed page
168 */
169 zram->table[index].attr.flags &= ~(ZRAM_COMP_PRIORITY_MASK <<
170 ZRAM_COMP_PRIORITY_BIT1);
171 zram->table[index].attr.flags |= (prio << ZRAM_COMP_PRIORITY_BIT1);
172 }
173
get_slot_comp_priority(struct zram * zram,unsigned long index)174 static inline u32 get_slot_comp_priority(struct zram *zram, unsigned long index)
175 {
176 u32 prio = zram->table[index].attr.flags >> ZRAM_COMP_PRIORITY_BIT1;
177
178 return prio & ZRAM_COMP_PRIORITY_MASK;
179 }
180
mark_slot_accessed(struct zram * zram,unsigned long index)181 static void mark_slot_accessed(struct zram *zram, unsigned long index)
182 {
183 clear_slot_flag(zram, index, ZRAM_IDLE);
184 clear_slot_flag(zram, index, ZRAM_PP_SLOT);
185 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
186 zram->table[index].attr.ac_time = (u32)ktime_get_boottime_seconds();
187 #endif
188 }
189
update_used_max(struct zram * zram,const unsigned long pages)190 static inline void update_used_max(struct zram *zram, const unsigned long pages)
191 {
192 unsigned long cur_max = atomic_long_read(&zram->stats.max_used_pages);
193
194 do {
195 if (cur_max >= pages)
196 return;
197 } while (!atomic_long_try_cmpxchg(&zram->stats.max_used_pages,
198 &cur_max, pages));
199 }
200
zram_can_store_page(struct zram * zram)201 static bool zram_can_store_page(struct zram *zram)
202 {
203 unsigned long alloced_pages;
204
205 alloced_pages = zs_get_total_pages(zram->mem_pool);
206 update_used_max(zram, alloced_pages);
207
208 return !zram->limit_pages || alloced_pages <= zram->limit_pages;
209 }
210
211 #if PAGE_SIZE != 4096
is_partial_io(struct bio_vec * bvec)212 static inline bool is_partial_io(struct bio_vec *bvec)
213 {
214 return bvec->bv_len != PAGE_SIZE;
215 }
216 #define ZRAM_PARTIAL_IO 1
217 #else
is_partial_io(struct bio_vec * bvec)218 static inline bool is_partial_io(struct bio_vec *bvec)
219 {
220 return false;
221 }
222 #endif
223
224 #if defined CONFIG_ZRAM_WRITEBACK || defined CONFIG_ZRAM_MULTI_COMP
225 struct zram_pp_slot {
226 unsigned long index;
227 struct list_head entry;
228 };
229
230 /*
231 * A post-processing bucket is, essentially, a size class, this defines
232 * the range (in bytes) of pp-slots sizes in particular bucket.
233 */
234 #define PP_BUCKET_SIZE_RANGE 64
235 #define NUM_PP_BUCKETS ((PAGE_SIZE / PP_BUCKET_SIZE_RANGE) + 1)
236
237 struct zram_pp_ctl {
238 struct list_head pp_buckets[NUM_PP_BUCKETS];
239 };
240
init_pp_ctl(void)241 static struct zram_pp_ctl *init_pp_ctl(void)
242 {
243 struct zram_pp_ctl *ctl;
244 u32 idx;
245
246 ctl = kmalloc_obj(*ctl);
247 if (!ctl)
248 return NULL;
249
250 for (idx = 0; idx < NUM_PP_BUCKETS; idx++)
251 INIT_LIST_HEAD(&ctl->pp_buckets[idx]);
252 return ctl;
253 }
254
release_pp_slot(struct zram * zram,struct zram_pp_slot * pps)255 static void release_pp_slot(struct zram *zram, struct zram_pp_slot *pps)
256 {
257 list_del_init(&pps->entry);
258
259 slot_lock(zram, pps->index);
260 clear_slot_flag(zram, pps->index, ZRAM_PP_SLOT);
261 slot_unlock(zram, pps->index);
262
263 kfree(pps);
264 }
265
release_pp_ctl(struct zram * zram,struct zram_pp_ctl * ctl)266 static void release_pp_ctl(struct zram *zram, struct zram_pp_ctl *ctl)
267 {
268 u32 idx;
269
270 if (!ctl)
271 return;
272
273 for (idx = 0; idx < NUM_PP_BUCKETS; idx++) {
274 while (!list_empty(&ctl->pp_buckets[idx])) {
275 struct zram_pp_slot *pps;
276
277 pps = list_first_entry(&ctl->pp_buckets[idx],
278 struct zram_pp_slot,
279 entry);
280 release_pp_slot(zram, pps);
281 }
282 }
283
284 kfree(ctl);
285 }
286
place_pp_slot(struct zram * zram,struct zram_pp_ctl * ctl,unsigned long index)287 static bool place_pp_slot(struct zram *zram, struct zram_pp_ctl *ctl,
288 unsigned long index)
289 {
290 struct zram_pp_slot *pps;
291 u32 bid;
292
293 pps = kmalloc_obj(*pps, GFP_NOIO | __GFP_NOWARN);
294 if (!pps)
295 return false;
296
297 INIT_LIST_HEAD(&pps->entry);
298 pps->index = index;
299
300 bid = get_slot_size(zram, pps->index) / PP_BUCKET_SIZE_RANGE;
301 list_add(&pps->entry, &ctl->pp_buckets[bid]);
302
303 set_slot_flag(zram, pps->index, ZRAM_PP_SLOT);
304 return true;
305 }
306
select_pp_slot(struct zram_pp_ctl * ctl)307 static struct zram_pp_slot *select_pp_slot(struct zram_pp_ctl *ctl)
308 {
309 struct zram_pp_slot *pps = NULL;
310 s32 idx = NUM_PP_BUCKETS - 1;
311
312 /* The higher the bucket id the more optimal slot post-processing is */
313 while (idx >= 0) {
314 pps = list_first_entry_or_null(&ctl->pp_buckets[idx],
315 struct zram_pp_slot,
316 entry);
317 if (pps)
318 break;
319
320 idx--;
321 }
322 return pps;
323 }
324 #endif
325
zram_fill_page(void * ptr,unsigned long len,unsigned long value)326 static inline void zram_fill_page(void *ptr, unsigned long len,
327 unsigned long value)
328 {
329 WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
330 memset_l(ptr, value, len / sizeof(unsigned long));
331 }
332
page_same_filled(void * ptr,unsigned long * element)333 static bool page_same_filled(void *ptr, unsigned long *element)
334 {
335 unsigned long *page;
336 unsigned long val;
337 unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
338
339 page = (unsigned long *)ptr;
340 val = page[0];
341
342 if (val != page[last_pos])
343 return false;
344
345 for (pos = 1; pos < last_pos; pos++) {
346 if (val != page[pos])
347 return false;
348 }
349
350 *element = val;
351
352 return true;
353 }
354
initstate_show(struct device * dev,struct device_attribute * attr,char * buf)355 static ssize_t initstate_show(struct device *dev, struct device_attribute *attr,
356 char *buf)
357 {
358 u32 val;
359 struct zram *zram = dev_to_zram(dev);
360
361 guard(rwsem_read)(&zram->dev_lock);
362 val = init_done(zram);
363
364 return sysfs_emit(buf, "%u\n", val);
365 }
366
disksize_show(struct device * dev,struct device_attribute * attr,char * buf)367 static ssize_t disksize_show(struct device *dev,
368 struct device_attribute *attr, char *buf)
369 {
370 struct zram *zram = dev_to_zram(dev);
371
372 return sysfs_emit(buf, "%llu\n", zram->disksize);
373 }
374
mem_limit_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)375 static ssize_t mem_limit_store(struct device *dev,
376 struct device_attribute *attr, const char *buf,
377 size_t len)
378 {
379 u64 limit;
380 char *tmp;
381 struct zram *zram = dev_to_zram(dev);
382
383 limit = memparse(buf, &tmp);
384 if (buf == tmp) /* no chars parsed, invalid input */
385 return -EINVAL;
386
387 guard(rwsem_write)(&zram->dev_lock);
388 zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
389
390 return len;
391 }
392
mem_used_max_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)393 static ssize_t mem_used_max_store(struct device *dev,
394 struct device_attribute *attr,
395 const char *buf, size_t len)
396 {
397 int err;
398 unsigned long val;
399 struct zram *zram = dev_to_zram(dev);
400
401 err = kstrtoul(buf, 10, &val);
402 if (err || val != 0)
403 return -EINVAL;
404
405 guard(rwsem_read)(&zram->dev_lock);
406 if (init_done(zram)) {
407 atomic_long_set(&zram->stats.max_used_pages,
408 zs_get_total_pages(zram->mem_pool));
409 }
410
411 return len;
412 }
413
414 /*
415 * Mark all pages which are older than or equal to cutoff as IDLE.
416 * Callers should hold the zram init lock in read mode
417 */
mark_idle(struct zram * zram,ktime_t cutoff)418 static void mark_idle(struct zram *zram, ktime_t cutoff)
419 {
420 int is_idle = 1;
421 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
422 unsigned long index;
423
424 for (index = 0; index < nr_pages; index++) {
425 /*
426 * Do not mark ZRAM_SAME slots as ZRAM_IDLE, because no
427 * post-processing (recompress, writeback) happens to the
428 * ZRAM_SAME slot.
429 *
430 * And ZRAM_WB slots simply cannot be ZRAM_IDLE.
431 */
432 slot_lock(zram, index);
433 if (!slot_allocated(zram, index) ||
434 test_slot_flag(zram, index, ZRAM_WB) ||
435 test_slot_flag(zram, index, ZRAM_SAME)) {
436 slot_unlock(zram, index);
437 continue;
438 }
439
440 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
441 is_idle = !cutoff ||
442 ktime_after(cutoff, zram->table[index].attr.ac_time);
443 #endif
444 if (is_idle)
445 set_slot_flag(zram, index, ZRAM_IDLE);
446 else
447 clear_slot_flag(zram, index, ZRAM_IDLE);
448 slot_unlock(zram, index);
449 }
450 }
451
idle_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)452 static ssize_t idle_store(struct device *dev, struct device_attribute *attr,
453 const char *buf, size_t len)
454 {
455 struct zram *zram = dev_to_zram(dev);
456 ktime_t cutoff = 0;
457
458 if (!sysfs_streq(buf, "all")) {
459 /*
460 * If it did not parse as 'all' try to treat it as an integer
461 * when we have memory tracking enabled.
462 */
463 u32 age_sec;
464
465 if (IS_ENABLED(CONFIG_ZRAM_TRACK_ENTRY_ACTIME) &&
466 !kstrtouint(buf, 0, &age_sec))
467 cutoff = ktime_sub((u32)ktime_get_boottime_seconds(),
468 age_sec);
469 else
470 return -EINVAL;
471 }
472
473 guard(rwsem_read)(&zram->dev_lock);
474 if (!init_done(zram))
475 return -EINVAL;
476
477 /*
478 * A cutoff of 0 marks everything as idle, this is the
479 * "all" behavior.
480 */
481 mark_idle(zram, cutoff);
482 return len;
483 }
484
485 #ifdef CONFIG_ZRAM_WRITEBACK
486 #define INVALID_BDEV_BLOCK (~0UL)
487
488 static int read_from_zspool_raw(struct zram *zram, struct page *page,
489 unsigned long index);
490 static int read_from_zspool(struct zram *zram, struct page *page,
491 unsigned long index);
492
493 struct zram_wb_ctl {
494 /* idle list is accessed only by the writeback task, no concurency */
495 struct list_head idle_reqs;
496 /* done list is accessed concurrently, protect by done_lock */
497 struct list_head done_reqs;
498 wait_queue_head_t done_wait;
499 spinlock_t done_lock;
500 atomic_t num_inflight;
501 struct rcu_head rcu;
502 };
503
504 struct zram_wb_req {
505 unsigned long blk_idx;
506 struct page *page;
507 struct zram_pp_slot *pps;
508 struct bio_vec bio_vec;
509 struct bio bio;
510
511 struct list_head entry;
512 };
513
514 struct zram_rb_req {
515 struct work_struct work;
516 struct zram *zram;
517 struct page *page;
518 /* The read bio for backing device */
519 struct bio *bio;
520 unsigned long blk_idx;
521 union {
522 /* The original bio to complete (async read) */
523 struct bio *parent;
524 /* error status (sync read) */
525 int error;
526 };
527 unsigned long index;
528 };
529
530 #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
bd_stat_show(struct device * dev,struct device_attribute * attr,char * buf)531 static ssize_t bd_stat_show(struct device *dev, struct device_attribute *attr,
532 char *buf)
533 {
534 struct zram *zram = dev_to_zram(dev);
535 ssize_t ret;
536
537 guard(rwsem_read)(&zram->dev_lock);
538 ret = sysfs_emit(buf,
539 "%8llu %8llu %8llu\n",
540 FOUR_K((u64)atomic64_read(&zram->stats.bd_count)),
541 FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)),
542 FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)));
543
544 return ret;
545 }
546
compressed_writeback_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)547 static ssize_t compressed_writeback_store(struct device *dev,
548 struct device_attribute *attr,
549 const char *buf, size_t len)
550 {
551 struct zram *zram = dev_to_zram(dev);
552 bool val;
553
554 if (kstrtobool(buf, &val))
555 return -EINVAL;
556
557 guard(rwsem_write)(&zram->dev_lock);
558 if (init_done(zram)) {
559 return -EBUSY;
560 }
561
562 zram->compressed_wb = val;
563
564 return len;
565 }
566
compressed_writeback_show(struct device * dev,struct device_attribute * attr,char * buf)567 static ssize_t compressed_writeback_show(struct device *dev,
568 struct device_attribute *attr,
569 char *buf)
570 {
571 bool val;
572 struct zram *zram = dev_to_zram(dev);
573
574 guard(rwsem_read)(&zram->dev_lock);
575 val = zram->compressed_wb;
576
577 return sysfs_emit(buf, "%d\n", val);
578 }
579
writeback_limit_enable_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)580 static ssize_t writeback_limit_enable_store(struct device *dev,
581 struct device_attribute *attr,
582 const char *buf, size_t len)
583 {
584 struct zram *zram = dev_to_zram(dev);
585 u64 val;
586
587 if (kstrtoull(buf, 10, &val))
588 return -EINVAL;
589
590 guard(rwsem_write)(&zram->dev_lock);
591 zram->wb_limit_enable = val;
592
593 return len;
594 }
595
writeback_limit_enable_show(struct device * dev,struct device_attribute * attr,char * buf)596 static ssize_t writeback_limit_enable_show(struct device *dev,
597 struct device_attribute *attr,
598 char *buf)
599 {
600 bool val;
601 struct zram *zram = dev_to_zram(dev);
602
603 guard(rwsem_read)(&zram->dev_lock);
604 val = zram->wb_limit_enable;
605
606 return sysfs_emit(buf, "%d\n", val);
607 }
608
writeback_limit_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)609 static ssize_t writeback_limit_store(struct device *dev,
610 struct device_attribute *attr,
611 const char *buf, size_t len)
612 {
613 struct zram *zram = dev_to_zram(dev);
614 u64 val;
615
616 if (kstrtoull(buf, 10, &val))
617 return -EINVAL;
618
619 /*
620 * When the page size is greater than 4KB, if bd_wb_limit is set to
621 * a value that is not page - size aligned, it will cause value
622 * wrapping. For example, when the page size is set to 16KB and
623 * bd_wb_limit is set to 3, a single write - back operation will
624 * cause bd_wb_limit to become -1. Even more terrifying is that
625 * bd_wb_limit is an unsigned number.
626 */
627 val = rounddown(val, PAGE_SIZE / 4096);
628
629 guard(rwsem_write)(&zram->dev_lock);
630 zram->bd_wb_limit = val;
631
632 return len;
633 }
634
writeback_limit_show(struct device * dev,struct device_attribute * attr,char * buf)635 static ssize_t writeback_limit_show(struct device *dev,
636 struct device_attribute *attr, char *buf)
637 {
638 u64 val;
639 struct zram *zram = dev_to_zram(dev);
640
641 guard(rwsem_read)(&zram->dev_lock);
642 val = zram->bd_wb_limit;
643
644 return sysfs_emit(buf, "%llu\n", val);
645 }
646
writeback_batch_size_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)647 static ssize_t writeback_batch_size_store(struct device *dev,
648 struct device_attribute *attr,
649 const char *buf, size_t len)
650 {
651 struct zram *zram = dev_to_zram(dev);
652 u32 val;
653
654 if (kstrtouint(buf, 10, &val))
655 return -EINVAL;
656
657 if (!val)
658 return -EINVAL;
659
660 guard(rwsem_write)(&zram->dev_lock);
661 zram->wb_batch_size = val;
662
663 return len;
664 }
665
writeback_batch_size_show(struct device * dev,struct device_attribute * attr,char * buf)666 static ssize_t writeback_batch_size_show(struct device *dev,
667 struct device_attribute *attr,
668 char *buf)
669 {
670 u32 val;
671 struct zram *zram = dev_to_zram(dev);
672
673 guard(rwsem_read)(&zram->dev_lock);
674 val = zram->wb_batch_size;
675
676 return sysfs_emit(buf, "%u\n", val);
677 }
678
reset_bdev(struct zram * zram)679 static void reset_bdev(struct zram *zram)
680 {
681 if (!zram->backing_dev)
682 return;
683
684 /* hope filp_close flush all of IO */
685 filp_close(zram->backing_dev, NULL);
686 zram->backing_dev = NULL;
687 zram->bdev = NULL;
688 zram->disk->fops = &zram_devops;
689 kvfree(zram->bitmap);
690 zram->bitmap = NULL;
691 }
692
backing_dev_show(struct device * dev,struct device_attribute * attr,char * buf)693 static ssize_t backing_dev_show(struct device *dev,
694 struct device_attribute *attr, char *buf)
695 {
696 struct file *file;
697 struct zram *zram = dev_to_zram(dev);
698 char *p;
699 ssize_t ret;
700
701 guard(rwsem_read)(&zram->dev_lock);
702 file = zram->backing_dev;
703 if (!file) {
704 memcpy(buf, "none\n", 5);
705 return 5;
706 }
707
708 p = file_path(file, buf, PAGE_SIZE - 1);
709 if (IS_ERR(p))
710 return PTR_ERR(p);
711
712 ret = strlen(p);
713 memmove(buf, p, ret);
714 buf[ret++] = '\n';
715 return ret;
716 }
717
backing_dev_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)718 static ssize_t backing_dev_store(struct device *dev,
719 struct device_attribute *attr, const char *buf,
720 size_t len)
721 {
722 char *file_name;
723 size_t sz;
724 struct file *backing_dev = NULL;
725 struct inode *inode;
726 unsigned int bitmap_sz;
727 unsigned long nr_pages, *bitmap = NULL;
728 int err;
729 struct zram *zram = dev_to_zram(dev);
730
731 file_name = kmalloc(PATH_MAX, GFP_KERNEL);
732 if (!file_name)
733 return -ENOMEM;
734
735 guard(rwsem_write)(&zram->dev_lock);
736 if (init_done(zram)) {
737 pr_info("Can't setup backing device for initialized device\n");
738 err = -EBUSY;
739 goto out;
740 }
741
742 strscpy(file_name, buf, PATH_MAX);
743 /* ignore trailing newline */
744 sz = strlen(file_name);
745 if (sz > 0 && file_name[sz - 1] == '\n')
746 file_name[sz - 1] = 0x00;
747
748 backing_dev = filp_open(file_name, O_RDWR | O_LARGEFILE | O_EXCL, 0);
749 if (IS_ERR(backing_dev)) {
750 err = PTR_ERR(backing_dev);
751 backing_dev = NULL;
752 goto out;
753 }
754
755 inode = backing_dev->f_mapping->host;
756
757 /* Support only block device in this moment */
758 if (!S_ISBLK(inode->i_mode)) {
759 err = -ENOTBLK;
760 goto out;
761 }
762
763 nr_pages = i_size_read(inode) >> PAGE_SHIFT;
764 /* Refuse to use zero sized device (also prevents self reference) */
765 if (!nr_pages) {
766 err = -EINVAL;
767 goto out;
768 }
769
770 bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
771 bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
772 if (!bitmap) {
773 err = -ENOMEM;
774 goto out;
775 }
776
777 reset_bdev(zram);
778
779 zram->bdev = I_BDEV(inode);
780 zram->backing_dev = backing_dev;
781 zram->bitmap = bitmap;
782 zram->nr_pages = nr_pages;
783
784 pr_info("setup backing device %s\n", file_name);
785 kfree(file_name);
786
787 return len;
788 out:
789 kvfree(bitmap);
790
791 if (backing_dev)
792 filp_close(backing_dev, NULL);
793
794 kfree(file_name);
795
796 return err;
797 }
798
zram_reserve_bdev_block(struct zram * zram)799 static unsigned long zram_reserve_bdev_block(struct zram *zram)
800 {
801 unsigned long blk_idx;
802
803 blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, 0);
804 if (blk_idx == zram->nr_pages)
805 return INVALID_BDEV_BLOCK;
806
807 set_bit(blk_idx, zram->bitmap);
808 atomic64_inc(&zram->stats.bd_count);
809 return blk_idx;
810 }
811
zram_release_bdev_block(struct zram * zram,unsigned long blk_idx)812 static void zram_release_bdev_block(struct zram *zram, unsigned long blk_idx)
813 {
814 int was_set;
815
816 was_set = test_and_clear_bit(blk_idx, zram->bitmap);
817 WARN_ON_ONCE(!was_set);
818 atomic64_dec(&zram->stats.bd_count);
819 }
820
release_wb_req(struct zram_wb_req * req)821 static void release_wb_req(struct zram_wb_req *req)
822 {
823 __free_page(req->page);
824 kfree(req);
825 }
826
release_wb_ctl(struct zram_wb_ctl * wb_ctl)827 static void release_wb_ctl(struct zram_wb_ctl *wb_ctl)
828 {
829 if (!wb_ctl)
830 return;
831
832 /* We should never have inflight requests at this point */
833 WARN_ON(atomic_read(&wb_ctl->num_inflight));
834 WARN_ON(!list_empty(&wb_ctl->done_reqs));
835
836 while (!list_empty(&wb_ctl->idle_reqs)) {
837 struct zram_wb_req *req;
838
839 req = list_first_entry(&wb_ctl->idle_reqs,
840 struct zram_wb_req, entry);
841 list_del(&req->entry);
842 release_wb_req(req);
843 }
844
845 kfree_rcu(wb_ctl, rcu);
846 }
847
init_wb_ctl(struct zram * zram)848 static struct zram_wb_ctl *init_wb_ctl(struct zram *zram)
849 {
850 struct zram_wb_ctl *wb_ctl;
851 int i;
852
853 wb_ctl = kmalloc_obj(*wb_ctl);
854 if (!wb_ctl)
855 return NULL;
856
857 INIT_LIST_HEAD(&wb_ctl->idle_reqs);
858 INIT_LIST_HEAD(&wb_ctl->done_reqs);
859 atomic_set(&wb_ctl->num_inflight, 0);
860 init_waitqueue_head(&wb_ctl->done_wait);
861 spin_lock_init(&wb_ctl->done_lock);
862
863 for (i = 0; i < zram->wb_batch_size; i++) {
864 struct zram_wb_req *req;
865
866 /*
867 * This is fatal condition only if we couldn't allocate
868 * any requests at all. Otherwise we just work with the
869 * requests that we have successfully allocated, so that
870 * writeback can still proceed, even if there is only one
871 * request on the idle list.
872 */
873 req = kzalloc_obj(*req, GFP_KERNEL | __GFP_NOWARN);
874 if (!req)
875 break;
876
877 req->page = alloc_page(GFP_KERNEL | __GFP_NOWARN);
878 if (!req->page) {
879 kfree(req);
880 break;
881 }
882
883 list_add(&req->entry, &wb_ctl->idle_reqs);
884 }
885
886 /* We couldn't allocate any requests, so writeabck is not possible */
887 if (list_empty(&wb_ctl->idle_reqs))
888 goto release_wb_ctl;
889
890 return wb_ctl;
891
892 release_wb_ctl:
893 release_wb_ctl(wb_ctl);
894 return NULL;
895 }
896
zram_account_writeback_rollback(struct zram * zram)897 static void zram_account_writeback_rollback(struct zram *zram)
898 {
899 lockdep_assert_held_write(&zram->dev_lock);
900
901 if (zram->wb_limit_enable)
902 zram->bd_wb_limit += 1UL << (PAGE_SHIFT - 12);
903 }
904
zram_account_writeback_submit(struct zram * zram)905 static void zram_account_writeback_submit(struct zram *zram)
906 {
907 lockdep_assert_held_write(&zram->dev_lock);
908
909 if (zram->wb_limit_enable && zram->bd_wb_limit > 0)
910 zram->bd_wb_limit -= 1UL << (PAGE_SHIFT - 12);
911 }
912
zram_writeback_complete(struct zram * zram,struct zram_wb_req * req)913 static int zram_writeback_complete(struct zram *zram, struct zram_wb_req *req)
914 {
915 unsigned long index = req->pps->index;
916 int err;
917
918 err = blk_status_to_errno(req->bio.bi_status);
919 if (err) {
920 /*
921 * Failed wb requests should not be accounted in wb_limit
922 * (if enabled).
923 */
924 zram_account_writeback_rollback(zram);
925 zram_release_bdev_block(zram, req->blk_idx);
926 return err;
927 }
928
929 atomic64_inc(&zram->stats.bd_writes);
930 slot_lock(zram, index);
931 /*
932 * We release slot lock during writeback so slot can change under us:
933 * slot_free() or slot_free() and zram_write_page(). In both cases
934 * slot loses ZRAM_PP_SLOT flag. No concurrent post-processing can
935 * set ZRAM_PP_SLOT on such slots until current post-processing
936 * finishes.
937 */
938 if (!test_slot_flag(zram, index, ZRAM_PP_SLOT)) {
939 zram_release_bdev_block(zram, req->blk_idx);
940 goto out;
941 }
942
943 clear_slot_flag(zram, index, ZRAM_IDLE);
944 if (test_slot_flag(zram, index, ZRAM_HUGE))
945 atomic64_dec(&zram->stats.huge_pages);
946 atomic64_sub(get_slot_size(zram, index), &zram->stats.compr_data_size);
947 zs_free(zram->mem_pool, get_slot_handle(zram, index));
948 set_slot_handle(zram, index, req->blk_idx);
949 set_slot_flag(zram, index, ZRAM_WB);
950
951 out:
952 slot_unlock(zram, index);
953 return 0;
954 }
955
zram_writeback_endio(struct bio * bio)956 static void zram_writeback_endio(struct bio *bio)
957 {
958 struct zram_wb_req *req = container_of(bio, struct zram_wb_req, bio);
959 struct zram_wb_ctl *wb_ctl = bio->bi_private;
960 unsigned long flags;
961
962 rcu_read_lock();
963 spin_lock_irqsave(&wb_ctl->done_lock, flags);
964 list_add(&req->entry, &wb_ctl->done_reqs);
965 spin_unlock_irqrestore(&wb_ctl->done_lock, flags);
966
967 wake_up(&wb_ctl->done_wait);
968 rcu_read_unlock();
969 }
970
zram_submit_wb_request(struct zram * zram,struct zram_wb_ctl * wb_ctl,struct zram_wb_req * req)971 static void zram_submit_wb_request(struct zram *zram,
972 struct zram_wb_ctl *wb_ctl,
973 struct zram_wb_req *req)
974 {
975 /*
976 * wb_limit (if enabled) should be adjusted before submission,
977 * so that we don't over-submit.
978 */
979 zram_account_writeback_submit(zram);
980 atomic_inc(&wb_ctl->num_inflight);
981 req->bio.bi_private = wb_ctl;
982 submit_bio(&req->bio);
983 }
984
zram_complete_done_reqs(struct zram * zram,struct zram_wb_ctl * wb_ctl)985 static int zram_complete_done_reqs(struct zram *zram,
986 struct zram_wb_ctl *wb_ctl)
987 {
988 struct zram_wb_req *req;
989 unsigned long flags;
990 int ret = 0, err;
991
992 while (atomic_read(&wb_ctl->num_inflight) > 0) {
993 spin_lock_irqsave(&wb_ctl->done_lock, flags);
994 req = list_first_entry_or_null(&wb_ctl->done_reqs,
995 struct zram_wb_req, entry);
996 if (req)
997 list_del(&req->entry);
998 spin_unlock_irqrestore(&wb_ctl->done_lock, flags);
999
1000 /* ->num_inflight > 0 doesn't mean we have done requests */
1001 if (!req)
1002 break;
1003
1004 err = zram_writeback_complete(zram, req);
1005 if (err)
1006 ret = err;
1007
1008 atomic_dec(&wb_ctl->num_inflight);
1009 release_pp_slot(zram, req->pps);
1010 req->pps = NULL;
1011
1012 list_add(&req->entry, &wb_ctl->idle_reqs);
1013 }
1014
1015 return ret;
1016 }
1017
zram_select_idle_req(struct zram_wb_ctl * wb_ctl)1018 static struct zram_wb_req *zram_select_idle_req(struct zram_wb_ctl *wb_ctl)
1019 {
1020 struct zram_wb_req *req;
1021
1022 req = list_first_entry_or_null(&wb_ctl->idle_reqs,
1023 struct zram_wb_req, entry);
1024 if (req)
1025 list_del(&req->entry);
1026 return req;
1027 }
1028
zram_writeback_slots(struct zram * zram,struct zram_pp_ctl * ctl,struct zram_wb_ctl * wb_ctl)1029 static int zram_writeback_slots(struct zram *zram,
1030 struct zram_pp_ctl *ctl,
1031 struct zram_wb_ctl *wb_ctl)
1032 {
1033 unsigned long blk_idx = INVALID_BDEV_BLOCK;
1034 struct zram_wb_req *req = NULL;
1035 struct zram_pp_slot *pps;
1036 int ret = 0, err = 0;
1037 unsigned long index = 0;
1038
1039 while ((pps = select_pp_slot(ctl))) {
1040 if (zram->wb_limit_enable && !zram->bd_wb_limit) {
1041 ret = -EIO;
1042 break;
1043 }
1044
1045 while (!req) {
1046 req = zram_select_idle_req(wb_ctl);
1047 if (req)
1048 break;
1049
1050 wait_event(wb_ctl->done_wait,
1051 !list_empty(&wb_ctl->done_reqs));
1052
1053 err = zram_complete_done_reqs(zram, wb_ctl);
1054 /*
1055 * BIO errors are not fatal, we continue and simply
1056 * attempt to writeback the remaining objects (pages).
1057 * At the same time we need to signal user-space that
1058 * some writes (at least one, but also could be all of
1059 * them) were not successful and we do so by returning
1060 * the most recent BIO error.
1061 */
1062 if (err)
1063 ret = err;
1064 }
1065
1066 if (blk_idx == INVALID_BDEV_BLOCK) {
1067 blk_idx = zram_reserve_bdev_block(zram);
1068 if (blk_idx == INVALID_BDEV_BLOCK) {
1069 ret = -ENOSPC;
1070 break;
1071 }
1072 }
1073
1074 index = pps->index;
1075 slot_lock(zram, index);
1076 /*
1077 * scan_slots() sets ZRAM_PP_SLOT and releases slot lock, so
1078 * slots can change in the meantime. If slots are accessed or
1079 * freed they lose ZRAM_PP_SLOT flag and hence we don't
1080 * post-process them.
1081 */
1082 if (!test_slot_flag(zram, index, ZRAM_PP_SLOT))
1083 goto next;
1084 if (zram->compressed_wb)
1085 err = read_from_zspool_raw(zram, req->page, index);
1086 else
1087 err = read_from_zspool(zram, req->page, index);
1088 if (err)
1089 goto next;
1090 slot_unlock(zram, index);
1091
1092 /*
1093 * From now on pp-slot is owned by the req, remove it from
1094 * its pp bucket.
1095 */
1096 list_del_init(&pps->entry);
1097
1098 req->blk_idx = blk_idx;
1099 req->pps = pps;
1100 bio_init(&req->bio, zram->bdev, &req->bio_vec, 1, REQ_OP_WRITE);
1101 req->bio.bi_iter.bi_sector = req->blk_idx * (PAGE_SIZE >> 9);
1102 req->bio.bi_end_io = zram_writeback_endio;
1103 __bio_add_page(&req->bio, req->page, PAGE_SIZE, 0);
1104
1105 zram_submit_wb_request(zram, wb_ctl, req);
1106 blk_idx = INVALID_BDEV_BLOCK;
1107 req = NULL;
1108 cond_resched();
1109 continue;
1110
1111 next:
1112 slot_unlock(zram, index);
1113 release_pp_slot(zram, pps);
1114 }
1115
1116 /*
1117 * Selected idle req, but never submitted it due to some error or
1118 * wb limit.
1119 */
1120 if (req)
1121 release_wb_req(req);
1122
1123 if (blk_idx != INVALID_BDEV_BLOCK)
1124 zram_release_bdev_block(zram, blk_idx);
1125
1126 while (atomic_read(&wb_ctl->num_inflight) > 0) {
1127 wait_event(wb_ctl->done_wait, !list_empty(&wb_ctl->done_reqs));
1128 err = zram_complete_done_reqs(zram, wb_ctl);
1129 if (err)
1130 ret = err;
1131 }
1132
1133 return ret;
1134 }
1135
1136 #define PAGE_WRITEBACK 0
1137 #define HUGE_WRITEBACK (1 << 0)
1138 #define IDLE_WRITEBACK (1 << 1)
1139 #define INCOMPRESSIBLE_WRITEBACK (1 << 2)
1140
parse_page_index(char * val,unsigned long nr_pages,unsigned long * lo,unsigned long * hi)1141 static int parse_page_index(char *val, unsigned long nr_pages,
1142 unsigned long *lo, unsigned long *hi)
1143 {
1144 int ret;
1145
1146 ret = kstrtoul(val, 10, lo);
1147 if (ret)
1148 return ret;
1149 if (*lo >= nr_pages)
1150 return -ERANGE;
1151 *hi = *lo + 1;
1152 return 0;
1153 }
1154
parse_page_indexes(char * val,unsigned long nr_pages,unsigned long * lo,unsigned long * hi)1155 static int parse_page_indexes(char *val, unsigned long nr_pages,
1156 unsigned long *lo, unsigned long *hi)
1157 {
1158 char *delim;
1159 int ret;
1160
1161 delim = strchr(val, '-');
1162 if (!delim)
1163 return -EINVAL;
1164
1165 *delim = 0x00;
1166 ret = kstrtoul(val, 10, lo);
1167 if (ret)
1168 return ret;
1169 if (*lo >= nr_pages)
1170 return -ERANGE;
1171
1172 ret = kstrtoul(delim + 1, 10, hi);
1173 if (ret)
1174 return ret;
1175 if (*hi >= nr_pages || *lo > *hi)
1176 return -ERANGE;
1177 *hi += 1;
1178 return 0;
1179 }
1180
parse_mode(char * val,u32 * mode)1181 static int parse_mode(char *val, u32 *mode)
1182 {
1183 *mode = 0;
1184
1185 if (!strcmp(val, "idle"))
1186 *mode = IDLE_WRITEBACK;
1187 if (!strcmp(val, "huge"))
1188 *mode = HUGE_WRITEBACK;
1189 if (!strcmp(val, "huge_idle"))
1190 *mode = IDLE_WRITEBACK | HUGE_WRITEBACK;
1191 if (!strcmp(val, "incompressible"))
1192 *mode = INCOMPRESSIBLE_WRITEBACK;
1193
1194 if (*mode == 0)
1195 return -EINVAL;
1196 return 0;
1197 }
1198
scan_slots_for_writeback(struct zram * zram,u32 mode,unsigned long lo,unsigned long hi,struct zram_pp_ctl * ctl)1199 static void scan_slots_for_writeback(struct zram *zram, u32 mode,
1200 unsigned long lo, unsigned long hi,
1201 struct zram_pp_ctl *ctl)
1202 {
1203 unsigned long index = lo;
1204
1205 while (index < hi) {
1206 bool ok = true;
1207
1208 slot_lock(zram, index);
1209 if (!slot_allocated(zram, index))
1210 goto next;
1211
1212 if (test_slot_flag(zram, index, ZRAM_WB) ||
1213 test_slot_flag(zram, index, ZRAM_SAME))
1214 goto next;
1215
1216 if (mode & IDLE_WRITEBACK &&
1217 !test_slot_flag(zram, index, ZRAM_IDLE))
1218 goto next;
1219 if (mode & HUGE_WRITEBACK &&
1220 !test_slot_flag(zram, index, ZRAM_HUGE))
1221 goto next;
1222 if (mode & INCOMPRESSIBLE_WRITEBACK &&
1223 !test_slot_flag(zram, index, ZRAM_INCOMPRESSIBLE))
1224 goto next;
1225
1226 ok = place_pp_slot(zram, ctl, index);
1227 next:
1228 slot_unlock(zram, index);
1229 if (!ok)
1230 break;
1231 index++;
1232 }
1233 }
1234
writeback_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1235 static ssize_t writeback_store(struct device *dev,
1236 struct device_attribute *attr,
1237 const char *buf, size_t len)
1238 {
1239 struct zram *zram = dev_to_zram(dev);
1240 unsigned long nr_pages;
1241 unsigned long lo = 0, hi;
1242 struct zram_pp_ctl *pp_ctl = NULL;
1243 struct zram_wb_ctl *wb_ctl = NULL;
1244 char *args, *param, *val;
1245 ssize_t ret = len;
1246 int err, mode = 0;
1247
1248 guard(rwsem_write)(&zram->dev_lock);
1249 if (!init_done(zram))
1250 return -EINVAL;
1251
1252 if (!zram->backing_dev)
1253 return -ENODEV;
1254
1255 nr_pages = zram->disksize >> PAGE_SHIFT;
1256 hi = nr_pages;
1257
1258 pp_ctl = init_pp_ctl();
1259 if (!pp_ctl)
1260 return -ENOMEM;
1261
1262 wb_ctl = init_wb_ctl(zram);
1263 if (!wb_ctl) {
1264 ret = -ENOMEM;
1265 goto out;
1266 }
1267
1268 args = skip_spaces(buf);
1269 while (*args) {
1270 args = next_arg(args, ¶m, &val);
1271
1272 /*
1273 * Workaround to support the old writeback interface.
1274 *
1275 * The old writeback interface has a minor inconsistency and
1276 * requires key=value only for page_index parameter, while the
1277 * writeback mode is a valueless parameter.
1278 *
1279 * This is not the case anymore and now all parameters are
1280 * required to have values, however, we need to support the
1281 * legacy writeback interface format so we check if we can
1282 * recognize a valueless parameter as the (legacy) writeback
1283 * mode.
1284 */
1285 if (!val || !*val) {
1286 err = parse_mode(param, &mode);
1287 if (err) {
1288 ret = err;
1289 goto out;
1290 }
1291
1292 scan_slots_for_writeback(zram, mode, lo, hi, pp_ctl);
1293 break;
1294 }
1295
1296 if (!strcmp(param, "type")) {
1297 err = parse_mode(val, &mode);
1298 if (err) {
1299 ret = err;
1300 goto out;
1301 }
1302
1303 scan_slots_for_writeback(zram, mode, lo, hi, pp_ctl);
1304 break;
1305 }
1306
1307 if (!strcmp(param, "page_index")) {
1308 err = parse_page_index(val, nr_pages, &lo, &hi);
1309 if (err) {
1310 ret = err;
1311 goto out;
1312 }
1313
1314 scan_slots_for_writeback(zram, mode, lo, hi, pp_ctl);
1315 continue;
1316 }
1317
1318 if (!strcmp(param, "page_indexes")) {
1319 err = parse_page_indexes(val, nr_pages, &lo, &hi);
1320 if (err) {
1321 ret = err;
1322 goto out;
1323 }
1324
1325 scan_slots_for_writeback(zram, mode, lo, hi, pp_ctl);
1326 continue;
1327 }
1328 }
1329
1330 err = zram_writeback_slots(zram, pp_ctl, wb_ctl);
1331 if (err)
1332 ret = err;
1333
1334 out:
1335 release_pp_ctl(zram, pp_ctl);
1336 release_wb_ctl(wb_ctl);
1337
1338 return ret;
1339 }
1340
decompress_bdev_page(struct zram * zram,struct page * page,unsigned long index)1341 static int decompress_bdev_page(struct zram *zram, struct page *page,
1342 unsigned long index)
1343 {
1344 struct zcomp_strm *zstrm;
1345 unsigned int size;
1346 int ret, prio;
1347 void *src;
1348
1349 slot_lock(zram, index);
1350 /* Since slot was unlocked we need to make sure it's still ZRAM_WB */
1351 if (!test_slot_flag(zram, index, ZRAM_WB)) {
1352 slot_unlock(zram, index);
1353 /* We read some stale data, zero it out */
1354 memset_page(page, 0, 0, PAGE_SIZE);
1355 return -EIO;
1356 }
1357
1358 if (test_slot_flag(zram, index, ZRAM_HUGE)) {
1359 slot_unlock(zram, index);
1360 return 0;
1361 }
1362
1363 size = get_slot_size(zram, index);
1364 prio = get_slot_comp_priority(zram, index);
1365
1366 zstrm = zcomp_stream_get(zram->comps[prio]);
1367 src = kmap_local_page(page);
1368 ret = zcomp_decompress(zram->comps[prio], zstrm, src, size,
1369 zstrm->local_copy);
1370 if (!ret)
1371 copy_page(src, zstrm->local_copy);
1372 kunmap_local(src);
1373 zcomp_stream_put(zstrm);
1374 slot_unlock(zram, index);
1375
1376 return ret;
1377 }
1378
zram_deferred_decompress(struct work_struct * w)1379 static void zram_deferred_decompress(struct work_struct *w)
1380 {
1381 struct zram_rb_req *req = container_of(w, struct zram_rb_req, work);
1382 struct page *page = bio_first_page_all(req->bio);
1383 struct zram *zram = req->zram;
1384 unsigned long index = req->index;
1385 int ret;
1386
1387 ret = decompress_bdev_page(zram, page, index);
1388 if (ret)
1389 req->parent->bi_status = BLK_STS_IOERR;
1390
1391 /* Decrement parent's ->remaining */
1392 bio_endio(req->parent);
1393 bio_put(req->bio);
1394 kfree(req);
1395 }
1396
zram_async_read_endio(struct bio * bio)1397 static void zram_async_read_endio(struct bio *bio)
1398 {
1399 struct zram_rb_req *req = bio->bi_private;
1400 struct zram *zram = req->zram;
1401
1402 if (bio->bi_status) {
1403 req->parent->bi_status = bio->bi_status;
1404 bio_endio(req->parent);
1405 bio_put(bio);
1406 kfree(req);
1407 return;
1408 }
1409
1410 /*
1411 * NOTE: zram_async_read_endio() is not exactly right place for this.
1412 * Ideally, we need to do it after ZRAM_WB check, but this requires
1413 * us to use wq path even on systems that don't enable compressed
1414 * writeback, because we cannot take slot-lock in the current context.
1415 *
1416 * Keep the existing behavior for now.
1417 */
1418 if (zram->compressed_wb == false) {
1419 /* No decompression needed, complete the parent IO */
1420 bio_endio(req->parent);
1421 bio_put(bio);
1422 kfree(req);
1423 return;
1424 }
1425
1426 /*
1427 * zram decompression is sleepable, so we need to deffer it to
1428 * a preemptible context.
1429 */
1430 INIT_WORK(&req->work, zram_deferred_decompress);
1431 queue_work(system_highpri_wq, &req->work);
1432 }
1433
read_from_bdev_async(struct zram * zram,struct page * page,unsigned long index,unsigned long blk_idx,struct bio * parent)1434 static int read_from_bdev_async(struct zram *zram, struct page *page,
1435 unsigned long index, unsigned long blk_idx,
1436 struct bio *parent)
1437 {
1438 struct zram_rb_req *req;
1439 struct bio *bio;
1440
1441 req = kmalloc_obj(*req, GFP_NOIO);
1442 if (!req)
1443 return -ENOMEM;
1444
1445 bio = bio_alloc(zram->bdev, 1, parent->bi_opf, GFP_NOIO);
1446 if (!bio) {
1447 kfree(req);
1448 return -ENOMEM;
1449 }
1450
1451 req->zram = zram;
1452 req->index = index;
1453 req->blk_idx = blk_idx;
1454 req->bio = bio;
1455 req->parent = parent;
1456
1457 bio->bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
1458 bio->bi_private = req;
1459 bio->bi_end_io = zram_async_read_endio;
1460
1461 __bio_add_page(bio, page, PAGE_SIZE, 0);
1462 bio_inc_remaining(parent);
1463 submit_bio(bio);
1464
1465 return 0;
1466 }
1467
zram_sync_read(struct work_struct * w)1468 static void zram_sync_read(struct work_struct *w)
1469 {
1470 struct zram_rb_req *req = container_of(w, struct zram_rb_req, work);
1471 struct bio_vec bv;
1472 struct bio bio;
1473
1474 bio_init(&bio, req->zram->bdev, &bv, 1, REQ_OP_READ);
1475 bio.bi_iter.bi_sector = req->blk_idx * (PAGE_SIZE >> 9);
1476 __bio_add_page(&bio, req->page, PAGE_SIZE, 0);
1477 req->error = submit_bio_wait(&bio);
1478 }
1479
1480 /*
1481 * Block layer want one ->submit_bio to be active at a time, so if we use
1482 * chained IO with parent IO in same context, it's a deadlock. To avoid that,
1483 * use a worker thread context.
1484 */
read_from_bdev_sync(struct zram * zram,struct page * page,unsigned long index,unsigned long blk_idx)1485 static int read_from_bdev_sync(struct zram *zram, struct page *page,
1486 unsigned long index, unsigned long blk_idx)
1487 {
1488 struct zram_rb_req req;
1489
1490 req.page = page;
1491 req.zram = zram;
1492 req.blk_idx = blk_idx;
1493
1494 INIT_WORK_ONSTACK(&req.work, zram_sync_read);
1495 queue_work(system_dfl_wq, &req.work);
1496 flush_work(&req.work);
1497 destroy_work_on_stack(&req.work);
1498
1499 if (req.error || zram->compressed_wb == false)
1500 return req.error;
1501
1502 return decompress_bdev_page(zram, page, index);
1503 }
1504
read_from_bdev(struct zram * zram,struct page * page,unsigned long index,unsigned long blk_idx,struct bio * parent)1505 static int read_from_bdev(struct zram *zram, struct page *page,
1506 unsigned long index, unsigned long blk_idx,
1507 struct bio *parent)
1508 {
1509 atomic64_inc(&zram->stats.bd_reads);
1510 if (!parent) {
1511 if (WARN_ON_ONCE(!IS_ENABLED(ZRAM_PARTIAL_IO)))
1512 return -EIO;
1513 return read_from_bdev_sync(zram, page, index, blk_idx);
1514 }
1515 return read_from_bdev_async(zram, page, index, blk_idx, parent);
1516 }
1517 #else
reset_bdev(struct zram * zram)1518 static inline void reset_bdev(struct zram *zram) {};
read_from_bdev(struct zram * zram,struct page * page,unsigned long index,unsigned long blk_idx,struct bio * parent)1519 static int read_from_bdev(struct zram *zram, struct page *page,
1520 unsigned long index, unsigned long blk_idx,
1521 struct bio *parent)
1522 {
1523 return -EIO;
1524 }
1525
zram_release_bdev_block(struct zram * zram,unsigned long blk_idx)1526 static void zram_release_bdev_block(struct zram *zram, unsigned long blk_idx)
1527 {
1528 }
1529 #endif
1530
1531 #ifdef CONFIG_ZRAM_MEMORY_TRACKING
1532
1533 static struct dentry *zram_debugfs_root;
1534
zram_debugfs_create(void)1535 static void zram_debugfs_create(void)
1536 {
1537 zram_debugfs_root = debugfs_create_dir("zram", NULL);
1538 }
1539
zram_debugfs_destroy(void)1540 static void zram_debugfs_destroy(void)
1541 {
1542 debugfs_remove_recursive(zram_debugfs_root);
1543 }
1544
read_block_state(struct file * file,char __user * buf,size_t count,loff_t * ppos)1545 static ssize_t read_block_state(struct file *file, char __user *buf,
1546 size_t count, loff_t *ppos)
1547 {
1548 char *kbuf;
1549 unsigned long index;
1550 ssize_t written = 0;
1551 struct zram *zram = file->private_data;
1552 unsigned long nr_pages;
1553
1554 kbuf = kvmalloc(count, GFP_KERNEL);
1555 if (!kbuf)
1556 return -ENOMEM;
1557
1558 guard(rwsem_read)(&zram->dev_lock);
1559 if (!init_done(zram)) {
1560 kvfree(kbuf);
1561 return -EINVAL;
1562 }
1563
1564 nr_pages = zram->disksize >> PAGE_SHIFT;
1565
1566 for (index = *ppos; index < nr_pages; index++) {
1567 int copied;
1568
1569 slot_lock(zram, index);
1570 if (!slot_allocated(zram, index))
1571 goto next;
1572
1573 copied = snprintf(kbuf + written, count,
1574 "%12lu %12u.%06d %c%c%c%c%c%c\n",
1575 index, zram->table[index].attr.ac_time, 0,
1576 test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.',
1577 test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.',
1578 test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
1579 test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
1580 get_slot_comp_priority(zram, index) ? 'r' : '.',
1581 test_slot_flag(zram, index,
1582 ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
1583
1584 if (count <= copied) {
1585 slot_unlock(zram, index);
1586 break;
1587 }
1588 written += copied;
1589 count -= copied;
1590 next:
1591 slot_unlock(zram, index);
1592 *ppos += 1;
1593 }
1594
1595 if (copy_to_user(buf, kbuf, written))
1596 written = -EFAULT;
1597 kvfree(kbuf);
1598
1599 return written;
1600 }
1601
1602 static const struct file_operations proc_zram_block_state_op = {
1603 .open = simple_open,
1604 .read = read_block_state,
1605 .llseek = default_llseek,
1606 };
1607
zram_debugfs_register(struct zram * zram)1608 static void zram_debugfs_register(struct zram *zram)
1609 {
1610 if (!zram_debugfs_root)
1611 return;
1612
1613 zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
1614 zram_debugfs_root);
1615 debugfs_create_file("block_state", 0400, zram->debugfs_dir,
1616 zram, &proc_zram_block_state_op);
1617 }
1618
zram_debugfs_unregister(struct zram * zram)1619 static void zram_debugfs_unregister(struct zram *zram)
1620 {
1621 debugfs_remove_recursive(zram->debugfs_dir);
1622 }
1623 #else
zram_debugfs_create(void)1624 static void zram_debugfs_create(void) {};
zram_debugfs_destroy(void)1625 static void zram_debugfs_destroy(void) {};
zram_debugfs_register(struct zram * zram)1626 static void zram_debugfs_register(struct zram *zram) {};
zram_debugfs_unregister(struct zram * zram)1627 static void zram_debugfs_unregister(struct zram *zram) {};
1628 #endif
1629
1630 /* Only algo parameter given, lookup by algo name */
lookup_algo_priority(struct zram * zram,const char * algo,u32 min_prio)1631 static int lookup_algo_priority(struct zram *zram, const char *algo,
1632 u32 min_prio)
1633 {
1634 s32 prio;
1635
1636 for (prio = min_prio; prio < ZRAM_MAX_COMPS; prio++) {
1637 if (!zram->comp_algs[prio])
1638 continue;
1639
1640 if (!strcmp(zram->comp_algs[prio], algo))
1641 return prio;
1642 }
1643
1644 return -EINVAL;
1645 }
1646
1647 /* Both algo and priority parameters given, validate them */
validate_algo_priority(struct zram * zram,const char * algo,u32 prio)1648 static int validate_algo_priority(struct zram *zram, const char *algo, u32 prio)
1649 {
1650 if (prio >= ZRAM_MAX_COMPS)
1651 return -EINVAL;
1652 /* No algo at given priority */
1653 if (!zram->comp_algs[prio])
1654 return -EINVAL;
1655 /* A different algo at given priority */
1656 if (strcmp(zram->comp_algs[prio], algo))
1657 return -EINVAL;
1658 return 0;
1659 }
1660
comp_algorithm_set(struct zram * zram,u32 prio,const char * alg)1661 static void comp_algorithm_set(struct zram *zram, u32 prio, const char *alg)
1662 {
1663 zram->comp_algs[prio] = alg;
1664 }
1665
comp_params_reset(struct zram * zram,u32 prio)1666 static void comp_params_reset(struct zram *zram, u32 prio)
1667 {
1668 struct zcomp_params *params = &zram->params[prio];
1669
1670 vfree(params->dict);
1671 params->level = ZCOMP_PARAM_NOT_SET;
1672 params->deflate.winbits = ZCOMP_PARAM_NOT_SET;
1673 params->dict_sz = 0;
1674 params->dict = NULL;
1675 }
1676
__comp_algorithm_store(struct zram * zram,u32 prio,const char * buf)1677 static int __comp_algorithm_store(struct zram *zram, u32 prio, const char *buf)
1678 {
1679 const char *alg;
1680 size_t sz;
1681
1682 sz = strlen(buf);
1683 if (sz >= ZRAM_MAX_ALGO_NAME_SZ)
1684 return -E2BIG;
1685
1686 alg = zcomp_lookup_backend_name(buf);
1687 if (!alg)
1688 return -EINVAL;
1689
1690 guard(rwsem_write)(&zram->dev_lock);
1691 if (init_done(zram)) {
1692 pr_info("Can't change algorithm for initialized device\n");
1693 return -EBUSY;
1694 }
1695
1696 comp_algorithm_set(zram, prio, alg);
1697 comp_params_reset(zram, prio);
1698 return 0;
1699 }
1700
comp_params_store(struct zram * zram,u32 prio,s32 level,const char * dict_path,struct deflate_params * deflate_params)1701 static int comp_params_store(struct zram *zram, u32 prio, s32 level,
1702 const char *dict_path,
1703 struct deflate_params *deflate_params)
1704 {
1705 ssize_t sz = 0;
1706
1707 comp_params_reset(zram, prio);
1708
1709 if (dict_path) {
1710 sz = kernel_read_file_from_path(dict_path, 0,
1711 &zram->params[prio].dict,
1712 INT_MAX,
1713 NULL,
1714 READING_POLICY);
1715 if (sz < 0) {
1716 pr_err("failed to load dictionary %s (err=%zd)\n",
1717 dict_path, sz);
1718 return sz;
1719 }
1720 if (sz == 0) {
1721 pr_err("failed to load dictionary %s (empty file)\n",
1722 dict_path);
1723 return -EINVAL;
1724 }
1725 }
1726
1727 zram->params[prio].dict_sz = sz;
1728 zram->params[prio].level = level;
1729 zram->params[prio].deflate.winbits = deflate_params->winbits;
1730 return 0;
1731 }
1732
algorithm_params_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1733 static ssize_t algorithm_params_store(struct device *dev,
1734 struct device_attribute *attr,
1735 const char *buf,
1736 size_t len)
1737 {
1738 s32 prio = ZRAM_PRIMARY_COMP, level = ZCOMP_PARAM_NOT_SET;
1739 char *args, *param, *val, *algo = NULL, *dict_path = NULL;
1740 struct deflate_params deflate_params;
1741 struct zram *zram = dev_to_zram(dev);
1742 bool prio_param = false;
1743 int ret;
1744
1745 deflate_params.winbits = ZCOMP_PARAM_NOT_SET;
1746
1747 args = skip_spaces(buf);
1748 while (*args) {
1749 args = next_arg(args, ¶m, &val);
1750
1751 if (!val || !*val)
1752 return -EINVAL;
1753
1754 if (!strcmp(param, "priority")) {
1755 prio_param = true;
1756 ret = kstrtoint(val, 10, &prio);
1757 if (ret)
1758 return ret;
1759 continue;
1760 }
1761
1762 if (!strcmp(param, "level")) {
1763 ret = kstrtoint(val, 10, &level);
1764 if (ret)
1765 return ret;
1766 continue;
1767 }
1768
1769 if (!strcmp(param, "algo")) {
1770 algo = val;
1771 continue;
1772 }
1773
1774 if (!strcmp(param, "dict")) {
1775 dict_path = val;
1776 continue;
1777 }
1778
1779 if (!strcmp(param, "deflate.winbits")) {
1780 ret = kstrtoint(val, 10, &deflate_params.winbits);
1781 if (ret)
1782 return ret;
1783 continue;
1784 }
1785 }
1786
1787 guard(rwsem_write)(&zram->dev_lock);
1788 if (init_done(zram))
1789 return -EBUSY;
1790
1791 if (prio_param) {
1792 if (prio < ZRAM_PRIMARY_COMP || prio >= ZRAM_MAX_COMPS)
1793 return -EINVAL;
1794 }
1795
1796 if (algo && prio_param) {
1797 ret = validate_algo_priority(zram, algo, prio);
1798 if (ret)
1799 return ret;
1800 }
1801
1802 if (algo && !prio_param) {
1803 prio = lookup_algo_priority(zram, algo, ZRAM_PRIMARY_COMP);
1804 if (prio < 0)
1805 return -EINVAL;
1806 }
1807
1808 ret = comp_params_store(zram, prio, level, dict_path, &deflate_params);
1809 return ret ? ret : len;
1810 }
1811
comp_algorithm_show(struct device * dev,struct device_attribute * attr,char * buf)1812 static ssize_t comp_algorithm_show(struct device *dev,
1813 struct device_attribute *attr,
1814 char *buf)
1815 {
1816 struct zram *zram = dev_to_zram(dev);
1817 ssize_t sz;
1818
1819 guard(rwsem_read)(&zram->dev_lock);
1820 sz = zcomp_available_show(zram->comp_algs[ZRAM_PRIMARY_COMP], buf, 0);
1821 return sz;
1822 }
1823
comp_algorithm_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1824 static ssize_t comp_algorithm_store(struct device *dev,
1825 struct device_attribute *attr,
1826 const char *buf,
1827 size_t len)
1828 {
1829 struct zram *zram = dev_to_zram(dev);
1830 int ret;
1831
1832 ret = __comp_algorithm_store(zram, ZRAM_PRIMARY_COMP, buf);
1833 return ret ? ret : len;
1834 }
1835
1836 #ifdef CONFIG_ZRAM_MULTI_COMP
recomp_algorithm_show(struct device * dev,struct device_attribute * attr,char * buf)1837 static ssize_t recomp_algorithm_show(struct device *dev,
1838 struct device_attribute *attr,
1839 char *buf)
1840 {
1841 struct zram *zram = dev_to_zram(dev);
1842 ssize_t sz = 0;
1843 u32 prio;
1844
1845 guard(rwsem_read)(&zram->dev_lock);
1846 for (prio = ZRAM_SECONDARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
1847 if (!zram->comp_algs[prio])
1848 continue;
1849
1850 sz += sysfs_emit_at(buf, sz, "#%d: ", prio);
1851 sz += zcomp_available_show(zram->comp_algs[prio], buf, sz);
1852 }
1853 return sz;
1854 }
1855
recomp_algorithm_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1856 static ssize_t recomp_algorithm_store(struct device *dev,
1857 struct device_attribute *attr,
1858 const char *buf,
1859 size_t len)
1860 {
1861 struct zram *zram = dev_to_zram(dev);
1862 int prio = ZRAM_SECONDARY_COMP;
1863 char *args, *param, *val;
1864 char *alg = NULL;
1865 int ret;
1866
1867 args = skip_spaces(buf);
1868 while (*args) {
1869 args = next_arg(args, ¶m, &val);
1870
1871 if (!val || !*val)
1872 return -EINVAL;
1873
1874 if (!strcmp(param, "algo")) {
1875 alg = val;
1876 continue;
1877 }
1878
1879 if (!strcmp(param, "priority")) {
1880 ret = kstrtoint(val, 10, &prio);
1881 if (ret)
1882 return ret;
1883 continue;
1884 }
1885 }
1886
1887 if (!alg)
1888 return -EINVAL;
1889
1890 if (prio < ZRAM_SECONDARY_COMP || prio >= ZRAM_MAX_COMPS)
1891 return -EINVAL;
1892
1893 ret = __comp_algorithm_store(zram, prio, alg);
1894 return ret ? ret : len;
1895 }
1896 #endif
1897
compact_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1898 static ssize_t compact_store(struct device *dev, struct device_attribute *attr,
1899 const char *buf, size_t len)
1900 {
1901 struct zram *zram = dev_to_zram(dev);
1902
1903 guard(rwsem_read)(&zram->dev_lock);
1904 if (!init_done(zram))
1905 return -EINVAL;
1906
1907 zs_compact(zram->mem_pool);
1908
1909 return len;
1910 }
1911
io_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1912 static ssize_t io_stat_show(struct device *dev, struct device_attribute *attr,
1913 char *buf)
1914 {
1915 struct zram *zram = dev_to_zram(dev);
1916 ssize_t ret;
1917
1918 guard(rwsem_read)(&zram->dev_lock);
1919 ret = sysfs_emit(buf,
1920 "%8llu %8llu 0 %8llu\n",
1921 (u64)atomic64_read(&zram->stats.failed_reads),
1922 (u64)atomic64_read(&zram->stats.failed_writes),
1923 (u64)atomic64_read(&zram->stats.notify_free));
1924
1925 return ret;
1926 }
1927
mm_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1928 static ssize_t mm_stat_show(struct device *dev, struct device_attribute *attr,
1929 char *buf)
1930 {
1931 struct zram *zram = dev_to_zram(dev);
1932 struct zs_pool_stats pool_stats;
1933 u64 orig_size, mem_used = 0;
1934 long max_used;
1935 ssize_t ret;
1936
1937 memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
1938
1939 guard(rwsem_read)(&zram->dev_lock);
1940 if (init_done(zram)) {
1941 mem_used = zs_get_total_pages(zram->mem_pool);
1942 zs_pool_stats(zram->mem_pool, &pool_stats);
1943 }
1944
1945 orig_size = atomic64_read(&zram->stats.pages_stored);
1946 max_used = atomic_long_read(&zram->stats.max_used_pages);
1947
1948 ret = sysfs_emit(buf,
1949 "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu %8llu\n",
1950 orig_size << PAGE_SHIFT,
1951 (u64)atomic64_read(&zram->stats.compr_data_size),
1952 mem_used << PAGE_SHIFT,
1953 zram->limit_pages << PAGE_SHIFT,
1954 max_used << PAGE_SHIFT,
1955 (u64)atomic64_read(&zram->stats.same_pages),
1956 atomic_long_read(&pool_stats.pages_compacted),
1957 (u64)atomic64_read(&zram->stats.huge_pages),
1958 (u64)atomic64_read(&zram->stats.huge_pages_since));
1959
1960 return ret;
1961 }
1962
debug_stat_show(struct device * dev,struct device_attribute * attr,char * buf)1963 static ssize_t debug_stat_show(struct device *dev,
1964 struct device_attribute *attr, char *buf)
1965 {
1966 int version = 1;
1967 struct zram *zram = dev_to_zram(dev);
1968 ssize_t ret;
1969
1970 guard(rwsem_read)(&zram->dev_lock);
1971 ret = sysfs_emit(buf,
1972 "version: %d\n0 %8llu\n",
1973 version,
1974 (u64)atomic64_read(&zram->stats.miss_free));
1975
1976 return ret;
1977 }
1978
zram_meta_free(struct zram * zram,u64 disksize)1979 static void zram_meta_free(struct zram *zram, u64 disksize)
1980 {
1981 unsigned long num_pages = disksize >> PAGE_SHIFT;
1982 unsigned long index;
1983
1984 if (!zram->table)
1985 return;
1986
1987 /* Free all pages that are still in this zram device */
1988 for (index = 0; index < num_pages; index++)
1989 slot_free(zram, index);
1990
1991 zs_destroy_pool(zram->mem_pool);
1992 vfree(zram->table);
1993 zram->table = NULL;
1994 lockdep_unregister_key(&zram->table_lock_key);
1995 }
1996
zram_meta_alloc(struct zram * zram,u64 disksize)1997 static bool zram_meta_alloc(struct zram *zram, u64 disksize)
1998 {
1999 unsigned long num_pages;
2000
2001 num_pages = disksize >> PAGE_SHIFT;
2002 zram->table = vzalloc(array_size(num_pages, sizeof(*zram->table)));
2003 if (!zram->table)
2004 return false;
2005
2006 zram->mem_pool = zs_create_pool(zram->disk->disk_name);
2007 if (!zram->mem_pool) {
2008 vfree(zram->table);
2009 zram->table = NULL;
2010 return false;
2011 }
2012
2013 if (!huge_class_size)
2014 huge_class_size = zs_huge_class_size(zram->mem_pool);
2015
2016 lockdep_register_key(&zram->table_lock_key);
2017 lockdep_init_map(&zram->table_lock_map, "zram->table[index].lock", &zram->table_lock_key, 0);
2018
2019 return true;
2020 }
2021
slot_free(struct zram * zram,unsigned long index)2022 static void slot_free(struct zram *zram, unsigned long index)
2023 {
2024 unsigned long handle;
2025
2026 #ifdef CONFIG_ZRAM_TRACK_ENTRY_ACTIME
2027 zram->table[index].attr.ac_time = 0;
2028 #endif
2029
2030 clear_slot_flag(zram, index, ZRAM_IDLE);
2031 clear_slot_flag(zram, index, ZRAM_INCOMPRESSIBLE);
2032 clear_slot_flag(zram, index, ZRAM_PP_SLOT);
2033 set_slot_comp_priority(zram, index, 0);
2034
2035 if (test_slot_flag(zram, index, ZRAM_HUGE)) {
2036 /*
2037 * Writeback completion decrements ->huge_pages but keeps
2038 * ZRAM_HUGE flag for deferred decompression path.
2039 */
2040 if (!test_slot_flag(zram, index, ZRAM_WB))
2041 atomic64_dec(&zram->stats.huge_pages);
2042 clear_slot_flag(zram, index, ZRAM_HUGE);
2043 }
2044
2045 if (test_slot_flag(zram, index, ZRAM_WB)) {
2046 clear_slot_flag(zram, index, ZRAM_WB);
2047 zram_release_bdev_block(zram, get_slot_handle(zram, index));
2048 goto out;
2049 }
2050
2051 /*
2052 * No memory is allocated for same element filled pages.
2053 * Simply clear same page flag.
2054 */
2055 if (test_slot_flag(zram, index, ZRAM_SAME)) {
2056 clear_slot_flag(zram, index, ZRAM_SAME);
2057 atomic64_dec(&zram->stats.same_pages);
2058 goto out;
2059 }
2060
2061 handle = get_slot_handle(zram, index);
2062 if (!handle)
2063 return;
2064
2065 zs_free(zram->mem_pool, handle);
2066
2067 atomic64_sub(get_slot_size(zram, index),
2068 &zram->stats.compr_data_size);
2069 out:
2070 atomic64_dec(&zram->stats.pages_stored);
2071 set_slot_handle(zram, index, 0);
2072 set_slot_size(zram, index, 0);
2073 }
2074
read_same_filled_page(struct zram * zram,struct page * page,unsigned long index)2075 static int read_same_filled_page(struct zram *zram, struct page *page,
2076 unsigned long index)
2077 {
2078 void *mem;
2079
2080 mem = kmap_local_page(page);
2081 zram_fill_page(mem, PAGE_SIZE, get_slot_handle(zram, index));
2082 kunmap_local(mem);
2083 return 0;
2084 }
2085
read_incompressible_page(struct zram * zram,struct page * page,unsigned long index)2086 static int read_incompressible_page(struct zram *zram, struct page *page,
2087 unsigned long index)
2088 {
2089 unsigned long handle;
2090 void *src, *dst;
2091
2092 handle = get_slot_handle(zram, index);
2093 src = zs_obj_read_begin(zram->mem_pool, handle, PAGE_SIZE, NULL);
2094 dst = kmap_local_page(page);
2095 copy_page(dst, src);
2096 kunmap_local(dst);
2097 zs_obj_read_end(zram->mem_pool, handle, PAGE_SIZE, src);
2098
2099 return 0;
2100 }
2101
read_compressed_page(struct zram * zram,struct page * page,unsigned long index)2102 static int read_compressed_page(struct zram *zram, struct page *page,
2103 unsigned long index)
2104 {
2105 struct zcomp_strm *zstrm;
2106 unsigned long handle;
2107 unsigned int size;
2108 void *src, *dst;
2109 int ret, prio;
2110
2111 handle = get_slot_handle(zram, index);
2112 size = get_slot_size(zram, index);
2113 prio = get_slot_comp_priority(zram, index);
2114
2115 zstrm = zcomp_stream_get(zram->comps[prio]);
2116 src = zs_obj_read_begin(zram->mem_pool, handle, size,
2117 zstrm->local_copy);
2118 dst = kmap_local_page(page);
2119 ret = zcomp_decompress(zram->comps[prio], zstrm, src, size, dst);
2120 kunmap_local(dst);
2121 zs_obj_read_end(zram->mem_pool, handle, size, src);
2122 zcomp_stream_put(zstrm);
2123
2124 return ret;
2125 }
2126
2127 #if defined CONFIG_ZRAM_WRITEBACK
read_from_zspool_raw(struct zram * zram,struct page * page,unsigned long index)2128 static int read_from_zspool_raw(struct zram *zram, struct page *page,
2129 unsigned long index)
2130 {
2131 struct zcomp_strm *zstrm;
2132 unsigned long handle;
2133 unsigned int size;
2134 void *src;
2135
2136 handle = get_slot_handle(zram, index);
2137 size = get_slot_size(zram, index);
2138
2139 /*
2140 * We need to get stream just for ->local_copy buffer, in
2141 * case if object spans two physical pages. No decompression
2142 * takes place here, as we read raw compressed data.
2143 */
2144 zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
2145 src = zs_obj_read_begin(zram->mem_pool, handle, size,
2146 zstrm->local_copy);
2147 memcpy_to_page(page, 0, src, size);
2148 zs_obj_read_end(zram->mem_pool, handle, size, src);
2149 zcomp_stream_put(zstrm);
2150
2151 memzero_page(page, size, PAGE_SIZE - size);
2152
2153 return 0;
2154 }
2155 #endif
2156
2157 /*
2158 * Reads (decompresses if needed) a page from zspool (zsmalloc).
2159 * Corresponding ZRAM slot should be locked.
2160 */
read_from_zspool(struct zram * zram,struct page * page,unsigned long index)2161 static int read_from_zspool(struct zram *zram, struct page *page,
2162 unsigned long index)
2163 {
2164 if (test_slot_flag(zram, index, ZRAM_SAME) ||
2165 !get_slot_handle(zram, index))
2166 return read_same_filled_page(zram, page, index);
2167
2168 if (!test_slot_flag(zram, index, ZRAM_HUGE))
2169 return read_compressed_page(zram, page, index);
2170 else
2171 return read_incompressible_page(zram, page, index);
2172 }
2173
zram_read_page(struct zram * zram,struct page * page,unsigned long index,struct bio * parent)2174 static int zram_read_page(struct zram *zram, struct page *page,
2175 unsigned long index, struct bio *parent)
2176 {
2177 int ret;
2178
2179 slot_lock(zram, index);
2180 if (!test_slot_flag(zram, index, ZRAM_WB)) {
2181 /* Slot should be locked through out the function call */
2182 ret = read_from_zspool(zram, page, index);
2183 slot_unlock(zram, index);
2184 } else {
2185 unsigned long blk_idx = get_slot_handle(zram, index);
2186
2187 /*
2188 * The slot should be unlocked before reading from the backing
2189 * device.
2190 */
2191 slot_unlock(zram, index);
2192 ret = read_from_bdev(zram, page, index, blk_idx, parent);
2193 }
2194
2195 /* Should NEVER happen. Return bio error if it does. */
2196 if (WARN_ON(ret < 0))
2197 pr_err("Decompression failed! err=%d, page=%lu\n", ret, index);
2198
2199 return ret;
2200 }
2201
2202 /*
2203 * Use a temporary buffer to decompress the page, as the decompressor
2204 * always expects a full page for the output.
2205 */
zram_bvec_read_partial(struct zram * zram,struct bio_vec * bvec,unsigned long index,int offset)2206 static int zram_bvec_read_partial(struct zram *zram, struct bio_vec *bvec,
2207 unsigned long index, int offset)
2208 {
2209 struct page *page = alloc_page(GFP_NOIO);
2210 int ret;
2211
2212 if (!page)
2213 return -ENOMEM;
2214 ret = zram_read_page(zram, page, index, NULL);
2215 if (likely(!ret))
2216 memcpy_to_bvec(bvec, page_address(page) + offset);
2217 __free_page(page);
2218 return ret;
2219 }
2220
zram_bvec_read(struct zram * zram,struct bio_vec * bvec,unsigned long index,int offset,struct bio * bio)2221 static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
2222 unsigned long index, int offset, struct bio *bio)
2223 {
2224 if (is_partial_io(bvec))
2225 return zram_bvec_read_partial(zram, bvec, index, offset);
2226 return zram_read_page(zram, bvec->bv_page, index, bio);
2227 }
2228
write_same_filled_page(struct zram * zram,unsigned long fill,unsigned long index)2229 static int write_same_filled_page(struct zram *zram, unsigned long fill,
2230 unsigned long index)
2231 {
2232 slot_lock(zram, index);
2233 slot_free(zram, index);
2234 set_slot_flag(zram, index, ZRAM_SAME);
2235 set_slot_handle(zram, index, fill);
2236 slot_unlock(zram, index);
2237
2238 atomic64_inc(&zram->stats.same_pages);
2239 atomic64_inc(&zram->stats.pages_stored);
2240
2241 return 0;
2242 }
2243
write_incompressible_page(struct zram * zram,struct page * page,unsigned long index)2244 static int write_incompressible_page(struct zram *zram, struct page *page,
2245 unsigned long index)
2246 {
2247 unsigned long handle;
2248 void *src;
2249
2250 /*
2251 * This function is called from preemptible context so we don't need
2252 * to do optimistic and fallback to pessimistic handle allocation,
2253 * like we do for compressible pages.
2254 */
2255 handle = zs_malloc(zram->mem_pool, PAGE_SIZE,
2256 GFP_NOIO | __GFP_NOWARN |
2257 __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page));
2258 if (IS_ERR_VALUE(handle))
2259 return PTR_ERR((void *)handle);
2260
2261 if (!zram_can_store_page(zram)) {
2262 zs_free(zram->mem_pool, handle);
2263 return -ENOMEM;
2264 }
2265
2266 src = kmap_local_page(page);
2267 zs_obj_write(zram->mem_pool, handle, src, PAGE_SIZE);
2268 kunmap_local(src);
2269
2270 slot_lock(zram, index);
2271 slot_free(zram, index);
2272 set_slot_flag(zram, index, ZRAM_HUGE);
2273 set_slot_handle(zram, index, handle);
2274 set_slot_size(zram, index, PAGE_SIZE);
2275 slot_unlock(zram, index);
2276
2277 atomic64_add(PAGE_SIZE, &zram->stats.compr_data_size);
2278 atomic64_inc(&zram->stats.huge_pages);
2279 atomic64_inc(&zram->stats.huge_pages_since);
2280 atomic64_inc(&zram->stats.pages_stored);
2281
2282 return 0;
2283 }
2284
zram_write_page(struct zram * zram,struct page * page,unsigned long index)2285 static int zram_write_page(struct zram *zram, struct page *page,
2286 unsigned long index)
2287 {
2288 int ret = 0;
2289 unsigned long handle;
2290 unsigned int comp_len;
2291 void *mem;
2292 struct zcomp_strm *zstrm;
2293 unsigned long element;
2294 bool same_filled;
2295
2296 mem = kmap_local_page(page);
2297 same_filled = page_same_filled(mem, &element);
2298 kunmap_local(mem);
2299 if (same_filled)
2300 return write_same_filled_page(zram, element, index);
2301
2302 zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]);
2303 mem = kmap_local_page(page);
2304 ret = zcomp_compress(zram->comps[ZRAM_PRIMARY_COMP], zstrm,
2305 mem, &comp_len);
2306 kunmap_local(mem);
2307
2308 if (unlikely(ret)) {
2309 zcomp_stream_put(zstrm);
2310 pr_err("Compression failed! err=%d\n", ret);
2311 return ret;
2312 }
2313
2314 if (comp_len >= huge_class_size) {
2315 zcomp_stream_put(zstrm);
2316 return write_incompressible_page(zram, page, index);
2317 }
2318
2319 handle = zs_malloc(zram->mem_pool, comp_len,
2320 GFP_NOIO | __GFP_NOWARN |
2321 __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page));
2322 if (IS_ERR_VALUE(handle)) {
2323 zcomp_stream_put(zstrm);
2324 return PTR_ERR((void *)handle);
2325 }
2326
2327 if (!zram_can_store_page(zram)) {
2328 zcomp_stream_put(zstrm);
2329 zs_free(zram->mem_pool, handle);
2330 return -ENOMEM;
2331 }
2332
2333 zs_obj_write(zram->mem_pool, handle, zstrm->buffer, comp_len);
2334 zcomp_stream_put(zstrm);
2335
2336 slot_lock(zram, index);
2337 slot_free(zram, index);
2338 set_slot_handle(zram, index, handle);
2339 set_slot_size(zram, index, comp_len);
2340 slot_unlock(zram, index);
2341
2342 /* Update stats */
2343 atomic64_inc(&zram->stats.pages_stored);
2344 atomic64_add(comp_len, &zram->stats.compr_data_size);
2345
2346 return ret;
2347 }
2348
2349 /*
2350 * This is a partial IO. Read the full page before writing the changes.
2351 */
zram_bvec_write_partial(struct zram * zram,struct bio_vec * bvec,unsigned long index,int offset)2352 static int zram_bvec_write_partial(struct zram *zram, struct bio_vec *bvec,
2353 unsigned long index, int offset)
2354 {
2355 struct page *page = alloc_page(GFP_NOIO);
2356 int ret;
2357
2358 if (!page)
2359 return -ENOMEM;
2360
2361 ret = zram_read_page(zram, page, index, NULL);
2362 if (!ret) {
2363 memcpy_from_bvec(page_address(page) + offset, bvec);
2364 ret = zram_write_page(zram, page, index);
2365 }
2366 __free_page(page);
2367 return ret;
2368 }
2369
zram_bvec_write(struct zram * zram,struct bio_vec * bvec,unsigned long index,int offset)2370 static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
2371 unsigned long index, int offset)
2372 {
2373 if (is_partial_io(bvec))
2374 return zram_bvec_write_partial(zram, bvec, index, offset);
2375 return zram_write_page(zram, bvec->bv_page, index);
2376 }
2377
2378 #ifdef CONFIG_ZRAM_MULTI_COMP
2379 #define RECOMPRESS_IDLE (1 << 0)
2380 #define RECOMPRESS_HUGE (1 << 1)
2381
highest_priority_algorithm(struct zram * zram,u32 prio)2382 static bool highest_priority_algorithm(struct zram *zram, u32 prio)
2383 {
2384 u32 p;
2385
2386 for (p = prio + 1; p < ZRAM_MAX_COMPS; p++) {
2387 if (zram->comp_algs[p])
2388 return false;
2389 }
2390
2391 return true;
2392 }
2393
scan_slots_for_recompress(struct zram * zram,u32 mode,u32 prio,struct zram_pp_ctl * ctl)2394 static void scan_slots_for_recompress(struct zram *zram, u32 mode, u32 prio,
2395 struct zram_pp_ctl *ctl)
2396 {
2397 unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
2398 unsigned long index;
2399
2400 for (index = 0; index < nr_pages; index++) {
2401 bool ok = true;
2402
2403 slot_lock(zram, index);
2404 if (!slot_allocated(zram, index))
2405 goto next;
2406
2407 if (mode & RECOMPRESS_IDLE &&
2408 !test_slot_flag(zram, index, ZRAM_IDLE))
2409 goto next;
2410
2411 if (mode & RECOMPRESS_HUGE &&
2412 !test_slot_flag(zram, index, ZRAM_HUGE))
2413 goto next;
2414
2415 if (test_slot_flag(zram, index, ZRAM_WB) ||
2416 test_slot_flag(zram, index, ZRAM_SAME) ||
2417 test_slot_flag(zram, index, ZRAM_INCOMPRESSIBLE))
2418 goto next;
2419
2420 /* Already compressed with same or higher priority */
2421 if (get_slot_comp_priority(zram, index) >= prio)
2422 goto next;
2423
2424 ok = place_pp_slot(zram, ctl, index);
2425 next:
2426 slot_unlock(zram, index);
2427 if (!ok)
2428 break;
2429 }
2430 }
2431
2432 /*
2433 * This function will decompress (unless it's ZRAM_HUGE) the page and then
2434 * attempt to compress it using provided compression algorithm priority
2435 * (which is potentially more effective).
2436 *
2437 * Corresponding ZRAM slot should be locked.
2438 */
recompress_slot(struct zram * zram,unsigned long index,struct page * page,u64 * num_recomp_pages,u32 threshold,u32 prio)2439 static int recompress_slot(struct zram *zram, unsigned long index,
2440 struct page *page, u64 *num_recomp_pages,
2441 u32 threshold, u32 prio)
2442 {
2443 struct zcomp_strm *zstrm = NULL;
2444 unsigned long handle_old;
2445 unsigned long handle_new;
2446 unsigned int comp_len_old;
2447 unsigned int comp_len_new;
2448 unsigned int class_index_old;
2449 unsigned int class_index_new;
2450 void *src;
2451 int ret = 0;
2452
2453 handle_old = get_slot_handle(zram, index);
2454 if (!handle_old)
2455 return -EINVAL;
2456
2457 comp_len_old = get_slot_size(zram, index);
2458 /*
2459 * Do not recompress objects that are already "small enough".
2460 */
2461 if (comp_len_old < threshold)
2462 return 0;
2463
2464 ret = read_from_zspool(zram, page, index);
2465 if (ret)
2466 return ret;
2467
2468 /*
2469 * We touched this entry so mark it as non-IDLE. This makes sure that
2470 * we don't preserve IDLE flag and don't incorrectly pick this entry
2471 * for different post-processing type (e.g. writeback).
2472 */
2473 clear_slot_flag(zram, index, ZRAM_IDLE);
2474
2475 zstrm = zcomp_stream_get(zram->comps[prio]);
2476 src = kmap_local_page(page);
2477 ret = zcomp_compress(zram->comps[prio], zstrm, src, &comp_len_new);
2478 kunmap_local(src);
2479
2480 /*
2481 * Decrement the limit (if set) on pages we can recompress, even
2482 * when current recompression was unsuccessful or did not compress
2483 * the page below the threshold, because we still spent resources
2484 * on it.
2485 */
2486 if (*num_recomp_pages)
2487 *num_recomp_pages -= 1;
2488
2489 if (ret) {
2490 zcomp_stream_put(zstrm);
2491 return ret;
2492 }
2493
2494 class_index_old = zs_lookup_class_index(zram->mem_pool, comp_len_old);
2495 class_index_new = zs_lookup_class_index(zram->mem_pool, comp_len_new);
2496
2497 if (class_index_new >= class_index_old ||
2498 (threshold && comp_len_new >= threshold)) {
2499 zcomp_stream_put(zstrm);
2500
2501 /*
2502 * Secondary algorithms failed to re-compress the page
2503 * in a way that would save memory.
2504 *
2505 * Mark the object incompressible if the max-priority (the
2506 * last configured one) algorithm couldn't re-compress it.
2507 */
2508 if (highest_priority_algorithm(zram, prio))
2509 set_slot_flag(zram, index, ZRAM_INCOMPRESSIBLE);
2510 return 0;
2511 }
2512
2513 /*
2514 * We are holding per-CPU stream mutex and entry lock so better
2515 * avoid direct reclaim. Allocation error is not fatal since
2516 * we still have the old object in the mem_pool.
2517 *
2518 * XXX: technically, the node we really want here is the node that
2519 * holds the original compressed data. But that would require us to
2520 * modify zsmalloc API to return this information. For now, we will
2521 * make do with the node of the page allocated for recompression.
2522 */
2523 handle_new = zs_malloc(zram->mem_pool, comp_len_new,
2524 GFP_NOIO | __GFP_NOWARN |
2525 __GFP_HIGHMEM | __GFP_MOVABLE,
2526 page_to_nid(page));
2527 if (IS_ERR_VALUE(handle_new)) {
2528 zcomp_stream_put(zstrm);
2529 return PTR_ERR((void *)handle_new);
2530 }
2531
2532 zs_obj_write(zram->mem_pool, handle_new, zstrm->buffer, comp_len_new);
2533 zcomp_stream_put(zstrm);
2534
2535 slot_free(zram, index);
2536 set_slot_handle(zram, index, handle_new);
2537 set_slot_size(zram, index, comp_len_new);
2538 set_slot_comp_priority(zram, index, prio);
2539
2540 atomic64_add(comp_len_new, &zram->stats.compr_data_size);
2541 atomic64_inc(&zram->stats.pages_stored);
2542
2543 return 0;
2544 }
2545
recompress_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)2546 static ssize_t recompress_store(struct device *dev,
2547 struct device_attribute *attr,
2548 const char *buf, size_t len)
2549 {
2550 struct zram *zram = dev_to_zram(dev);
2551 char *args, *param, *val, *algo = NULL;
2552 u64 num_recomp_pages = ULLONG_MAX;
2553 struct zram_pp_ctl *ctl = NULL;
2554 s32 prio = ZRAM_SECONDARY_COMP;
2555 u32 mode = 0, threshold = 0;
2556 struct zram_pp_slot *pps;
2557 struct page *page = NULL;
2558 bool prio_param = false;
2559 ssize_t ret;
2560
2561 args = skip_spaces(buf);
2562 while (*args) {
2563 args = next_arg(args, ¶m, &val);
2564
2565 if (!val || !*val)
2566 return -EINVAL;
2567
2568 if (!strcmp(param, "type")) {
2569 if (!strcmp(val, "idle"))
2570 mode = RECOMPRESS_IDLE;
2571 if (!strcmp(val, "huge"))
2572 mode = RECOMPRESS_HUGE;
2573 if (!strcmp(val, "huge_idle"))
2574 mode = RECOMPRESS_IDLE | RECOMPRESS_HUGE;
2575 if (!mode)
2576 return -EINVAL;
2577 continue;
2578 }
2579
2580 if (!strcmp(param, "max_pages")) {
2581 /*
2582 * Limit the number of entries (pages) we attempt to
2583 * recompress.
2584 */
2585 ret = kstrtoull(val, 10, &num_recomp_pages);
2586 if (ret)
2587 return ret;
2588 continue;
2589 }
2590
2591 if (!strcmp(param, "threshold")) {
2592 /*
2593 * We will re-compress only idle objects equal or
2594 * greater in size than watermark.
2595 */
2596 ret = kstrtouint(val, 10, &threshold);
2597 if (ret)
2598 return ret;
2599 continue;
2600 }
2601
2602 if (!strcmp(param, "algo")) {
2603 algo = val;
2604 continue;
2605 }
2606
2607 if (!strcmp(param, "priority")) {
2608 prio_param = true;
2609 ret = kstrtoint(val, 10, &prio);
2610 if (ret)
2611 return ret;
2612 continue;
2613 }
2614 }
2615
2616 if (threshold >= huge_class_size)
2617 return -EINVAL;
2618
2619 guard(rwsem_write)(&zram->dev_lock);
2620 if (!init_done(zram))
2621 return -EINVAL;
2622
2623 if (prio_param) {
2624 if (prio < ZRAM_SECONDARY_COMP || prio >= ZRAM_MAX_COMPS)
2625 return -EINVAL;
2626 }
2627
2628 if (algo && prio_param) {
2629 ret = validate_algo_priority(zram, algo, prio);
2630 if (ret)
2631 return ret;
2632 }
2633
2634 if (algo && !prio_param) {
2635 prio = lookup_algo_priority(zram, algo, ZRAM_SECONDARY_COMP);
2636 if (prio < 0)
2637 return -EINVAL;
2638 }
2639
2640 if (!zram->comps[prio])
2641 return -EINVAL;
2642
2643 page = alloc_page(GFP_KERNEL);
2644 if (!page) {
2645 ret = -ENOMEM;
2646 goto out;
2647 }
2648
2649 ctl = init_pp_ctl();
2650 if (!ctl) {
2651 ret = -ENOMEM;
2652 goto out;
2653 }
2654
2655 scan_slots_for_recompress(zram, mode, prio, ctl);
2656
2657 ret = len;
2658 while ((pps = select_pp_slot(ctl))) {
2659 int err = 0;
2660
2661 if (!num_recomp_pages)
2662 break;
2663
2664 slot_lock(zram, pps->index);
2665 if (!test_slot_flag(zram, pps->index, ZRAM_PP_SLOT))
2666 goto next;
2667
2668 err = recompress_slot(zram, pps->index, page,
2669 &num_recomp_pages, threshold, prio);
2670 next:
2671 slot_unlock(zram, pps->index);
2672 release_pp_slot(zram, pps);
2673
2674 if (err) {
2675 ret = err;
2676 break;
2677 }
2678
2679 cond_resched();
2680 }
2681
2682 out:
2683 if (page)
2684 __free_page(page);
2685 release_pp_ctl(zram, ctl);
2686 return ret;
2687 }
2688 #endif
2689
zram_bio_discard(struct zram * zram,struct bio * bio)2690 static void zram_bio_discard(struct zram *zram, struct bio *bio)
2691 {
2692 size_t n = bio->bi_iter.bi_size;
2693 unsigned long index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
2694 u32 offset = (bio->bi_iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
2695 SECTOR_SHIFT;
2696
2697 /*
2698 * zram manages data in physical block size units. Because logical block
2699 * size isn't identical with physical block size on some arch, we
2700 * could get a discard request pointing to a specific offset within a
2701 * certain physical block. Although we can handle this request by
2702 * reading that physiclal block and decompressing and partially zeroing
2703 * and re-compressing and then re-storing it, this isn't reasonable
2704 * because our intent with a discard request is to save memory. So
2705 * skipping this logical block is appropriate here.
2706 */
2707 if (offset) {
2708 if (n <= (PAGE_SIZE - offset))
2709 goto end_bio;
2710
2711 n -= (PAGE_SIZE - offset);
2712 index++;
2713 }
2714
2715 while (n >= PAGE_SIZE) {
2716 slot_lock(zram, index);
2717 slot_free(zram, index);
2718 slot_unlock(zram, index);
2719 atomic64_inc(&zram->stats.notify_free);
2720 index++;
2721 n -= PAGE_SIZE;
2722 }
2723
2724 end_bio:
2725 bio_endio(bio);
2726 }
2727
zram_bio_read(struct zram * zram,struct bio * bio)2728 static void zram_bio_read(struct zram *zram, struct bio *bio)
2729 {
2730 unsigned long start_time = bio_start_io_acct(bio);
2731 struct bvec_iter iter = bio->bi_iter;
2732
2733 do {
2734 unsigned long index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
2735 u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
2736 SECTOR_SHIFT;
2737 struct bio_vec bv = bio_iter_iovec(bio, iter);
2738
2739 bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
2740
2741 if (zram_bvec_read(zram, &bv, index, offset, bio) < 0) {
2742 atomic64_inc(&zram->stats.failed_reads);
2743 bio->bi_status = BLK_STS_IOERR;
2744 break;
2745 }
2746 flush_dcache_page(bv.bv_page);
2747
2748 slot_lock(zram, index);
2749 mark_slot_accessed(zram, index);
2750 slot_unlock(zram, index);
2751
2752 bio_advance_iter_single(bio, &iter, bv.bv_len);
2753 } while (iter.bi_size);
2754
2755 bio_end_io_acct(bio, start_time);
2756 bio_endio(bio);
2757 }
2758
zram_bio_write(struct zram * zram,struct bio * bio)2759 static void zram_bio_write(struct zram *zram, struct bio *bio)
2760 {
2761 unsigned long start_time = bio_start_io_acct(bio);
2762 struct bvec_iter iter = bio->bi_iter;
2763
2764 do {
2765 unsigned long index = iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
2766 u32 offset = (iter.bi_sector & (SECTORS_PER_PAGE - 1)) <<
2767 SECTOR_SHIFT;
2768 struct bio_vec bv = bio_iter_iovec(bio, iter);
2769
2770 bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
2771
2772 if (zram_bvec_write(zram, &bv, index, offset) < 0) {
2773 atomic64_inc(&zram->stats.failed_writes);
2774 bio->bi_status = BLK_STS_IOERR;
2775 break;
2776 }
2777
2778 slot_lock(zram, index);
2779 mark_slot_accessed(zram, index);
2780 slot_unlock(zram, index);
2781
2782 bio_advance_iter_single(bio, &iter, bv.bv_len);
2783 } while (iter.bi_size);
2784
2785 bio_end_io_acct(bio, start_time);
2786 bio_endio(bio);
2787 }
2788
2789 /*
2790 * Handler function for all zram I/O requests.
2791 */
zram_submit_bio(struct bio * bio)2792 static void zram_submit_bio(struct bio *bio)
2793 {
2794 struct zram *zram = bio->bi_bdev->bd_disk->private_data;
2795
2796 switch (bio_op(bio)) {
2797 case REQ_OP_READ:
2798 zram_bio_read(zram, bio);
2799 break;
2800 case REQ_OP_WRITE:
2801 zram_bio_write(zram, bio);
2802 break;
2803 case REQ_OP_DISCARD:
2804 case REQ_OP_WRITE_ZEROES:
2805 zram_bio_discard(zram, bio);
2806 break;
2807 default:
2808 WARN_ON_ONCE(1);
2809 bio_endio(bio);
2810 }
2811 }
2812
zram_slot_free_notify(struct block_device * bdev,unsigned long index)2813 static void zram_slot_free_notify(struct block_device *bdev,
2814 unsigned long index)
2815 {
2816 struct zram *zram;
2817
2818 zram = bdev->bd_disk->private_data;
2819
2820 atomic64_inc(&zram->stats.notify_free);
2821 if (!slot_trylock(zram, index)) {
2822 atomic64_inc(&zram->stats.miss_free);
2823 return;
2824 }
2825
2826 slot_free(zram, index);
2827 slot_unlock(zram, index);
2828 }
2829
zram_comp_params_reset(struct zram * zram)2830 static void zram_comp_params_reset(struct zram *zram)
2831 {
2832 u32 prio;
2833
2834 for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
2835 comp_params_reset(zram, prio);
2836 }
2837 }
2838
zram_destroy_comps(struct zram * zram)2839 static void zram_destroy_comps(struct zram *zram)
2840 {
2841 u32 prio;
2842
2843 for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
2844 struct zcomp *comp = zram->comps[prio];
2845
2846 zram->comps[prio] = NULL;
2847 if (!comp)
2848 continue;
2849 zcomp_destroy(comp);
2850 }
2851
2852 for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++)
2853 zram->comp_algs[prio] = NULL;
2854
2855 zram_comp_params_reset(zram);
2856 comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
2857 }
2858
zram_reset_device(struct zram * zram)2859 static void zram_reset_device(struct zram *zram)
2860 {
2861 guard(rwsem_write)(&zram->dev_lock);
2862
2863 zram->limit_pages = 0;
2864
2865 set_capacity_and_notify(zram->disk, 0);
2866 part_stat_set_all(zram->disk->part0, 0);
2867
2868 /* I/O operation under all of CPU are done so let's free */
2869 zram_meta_free(zram, zram->disksize);
2870 zram->disksize = 0;
2871 zram_destroy_comps(zram);
2872 memset(&zram->stats, 0, sizeof(zram->stats));
2873 reset_bdev(zram);
2874 }
2875
disksize_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)2876 static ssize_t disksize_store(struct device *dev, struct device_attribute *attr,
2877 const char *buf, size_t len)
2878 {
2879 unsigned long num_pages;
2880 u64 disksize;
2881 struct zcomp *comp;
2882 struct zram *zram = dev_to_zram(dev);
2883 int err;
2884 u32 prio;
2885
2886 disksize = memparse(buf, NULL);
2887 if (!disksize)
2888 return -EINVAL;
2889
2890 guard(rwsem_write)(&zram->dev_lock);
2891 if (init_done(zram)) {
2892 pr_info("Cannot change disksize for initialized device\n");
2893 return -EBUSY;
2894 }
2895
2896 disksize = PAGE_ALIGN(disksize);
2897 num_pages = disksize >> PAGE_SHIFT;
2898 /* Slots are addressed by an unsigned long index */
2899 if (!num_pages || ((u64)num_pages << PAGE_SHIFT) != disksize)
2900 return -EINVAL;
2901
2902 if (!zram_meta_alloc(zram, disksize))
2903 return -ENOMEM;
2904
2905 for (prio = ZRAM_PRIMARY_COMP; prio < ZRAM_MAX_COMPS; prio++) {
2906 if (!zram->comp_algs[prio])
2907 continue;
2908
2909 comp = zcomp_create(zram->comp_algs[prio],
2910 &zram->params[prio]);
2911 if (IS_ERR(comp)) {
2912 pr_err("Cannot initialise %s compressing backend\n",
2913 zram->comp_algs[prio]);
2914 err = PTR_ERR(comp);
2915 goto out_free_comps;
2916 }
2917
2918 zram->comps[prio] = comp;
2919 }
2920 zram->disksize = disksize;
2921 set_capacity_and_notify(zram->disk, zram->disksize >> SECTOR_SHIFT);
2922
2923 return len;
2924
2925 out_free_comps:
2926 zram_destroy_comps(zram);
2927 zram_meta_free(zram, disksize);
2928 return err;
2929 }
2930
reset_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)2931 static ssize_t reset_store(struct device *dev,
2932 struct device_attribute *attr, const char *buf, size_t len)
2933 {
2934 int ret;
2935 unsigned short do_reset;
2936 struct zram *zram;
2937 struct gendisk *disk;
2938
2939 ret = kstrtou16(buf, 10, &do_reset);
2940 if (ret)
2941 return ret;
2942
2943 if (!do_reset)
2944 return -EINVAL;
2945
2946 zram = dev_to_zram(dev);
2947 disk = zram->disk;
2948
2949 mutex_lock(&disk->open_mutex);
2950 /* Do not reset an active device or claimed device */
2951 if (disk_openers(disk) || zram->claim) {
2952 mutex_unlock(&disk->open_mutex);
2953 return -EBUSY;
2954 }
2955
2956 /* From now on, anyone can't open /dev/zram[0-9] */
2957 zram->claim = true;
2958 mutex_unlock(&disk->open_mutex);
2959
2960 /* Make sure all the pending I/O are finished */
2961 sync_blockdev(disk->part0);
2962 zram_reset_device(zram);
2963
2964 mutex_lock(&disk->open_mutex);
2965 zram->claim = false;
2966 mutex_unlock(&disk->open_mutex);
2967
2968 return len;
2969 }
2970
zram_open(struct gendisk * disk,blk_mode_t mode)2971 static int zram_open(struct gendisk *disk, blk_mode_t mode)
2972 {
2973 struct zram *zram = disk->private_data;
2974
2975 WARN_ON(!mutex_is_locked(&disk->open_mutex));
2976
2977 /* zram was claimed to reset so open request fails */
2978 if (zram->claim)
2979 return -EBUSY;
2980 return 0;
2981 }
2982
2983 static const struct block_device_operations zram_devops = {
2984 .open = zram_open,
2985 .submit_bio = zram_submit_bio,
2986 .swap_slot_free_notify = zram_slot_free_notify,
2987 .owner = THIS_MODULE
2988 };
2989
2990 static DEVICE_ATTR_RO(io_stat);
2991 static DEVICE_ATTR_RO(mm_stat);
2992 static DEVICE_ATTR_RO(debug_stat);
2993 static DEVICE_ATTR_WO(compact);
2994 static DEVICE_ATTR_RW(disksize);
2995 static DEVICE_ATTR_RO(initstate);
2996 static DEVICE_ATTR_WO(reset);
2997 static DEVICE_ATTR_WO(mem_limit);
2998 static DEVICE_ATTR_WO(mem_used_max);
2999 static DEVICE_ATTR_WO(idle);
3000 static DEVICE_ATTR_RW(comp_algorithm);
3001 #ifdef CONFIG_ZRAM_WRITEBACK
3002 static DEVICE_ATTR_RO(bd_stat);
3003 static DEVICE_ATTR_RW(backing_dev);
3004 static DEVICE_ATTR_WO(writeback);
3005 static DEVICE_ATTR_RW(writeback_limit);
3006 static DEVICE_ATTR_RW(writeback_limit_enable);
3007 static DEVICE_ATTR_RW(writeback_batch_size);
3008 static DEVICE_ATTR_RW(compressed_writeback);
3009 #endif
3010 #ifdef CONFIG_ZRAM_MULTI_COMP
3011 static DEVICE_ATTR_RW(recomp_algorithm);
3012 static DEVICE_ATTR_WO(recompress);
3013 #endif
3014 static DEVICE_ATTR_WO(algorithm_params);
3015
3016 static struct attribute *zram_disk_attrs[] = {
3017 &dev_attr_disksize.attr,
3018 &dev_attr_initstate.attr,
3019 &dev_attr_reset.attr,
3020 &dev_attr_compact.attr,
3021 &dev_attr_mem_limit.attr,
3022 &dev_attr_mem_used_max.attr,
3023 &dev_attr_idle.attr,
3024 &dev_attr_comp_algorithm.attr,
3025 #ifdef CONFIG_ZRAM_WRITEBACK
3026 &dev_attr_bd_stat.attr,
3027 &dev_attr_backing_dev.attr,
3028 &dev_attr_writeback.attr,
3029 &dev_attr_writeback_limit.attr,
3030 &dev_attr_writeback_limit_enable.attr,
3031 &dev_attr_writeback_batch_size.attr,
3032 &dev_attr_compressed_writeback.attr,
3033 #endif
3034 &dev_attr_io_stat.attr,
3035 &dev_attr_mm_stat.attr,
3036 &dev_attr_debug_stat.attr,
3037 #ifdef CONFIG_ZRAM_MULTI_COMP
3038 &dev_attr_recomp_algorithm.attr,
3039 &dev_attr_recompress.attr,
3040 #endif
3041 &dev_attr_algorithm_params.attr,
3042 NULL,
3043 };
3044
3045 ATTRIBUTE_GROUPS(zram_disk);
3046
3047 /*
3048 * Allocate and initialize new zram device. the function returns
3049 * '>= 0' device_id upon success, and negative value otherwise.
3050 */
zram_add(void)3051 static int zram_add(void)
3052 {
3053 struct queue_limits lim = {
3054 .logical_block_size = ZRAM_LOGICAL_BLOCK_SIZE,
3055 /*
3056 * To ensure that we always get PAGE_SIZE aligned and
3057 * n*PAGE_SIZED sized I/O requests.
3058 */
3059 .physical_block_size = PAGE_SIZE,
3060 .io_min = PAGE_SIZE,
3061 .io_opt = PAGE_SIZE,
3062 .max_hw_discard_sectors = UINT_MAX,
3063 /*
3064 * zram_bio_discard() will clear all logical blocks if logical
3065 * block size is identical with physical block size(PAGE_SIZE).
3066 * But if it is different, we will skip discarding some parts of
3067 * logical blocks in the part of the request range which isn't
3068 * aligned to physical block size. So we can't ensure that all
3069 * discarded logical blocks are zeroed.
3070 */
3071 #if ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE
3072 .max_write_zeroes_sectors = UINT_MAX,
3073 #endif
3074 .features = BLK_FEAT_STABLE_WRITES |
3075 BLK_FEAT_SYNCHRONOUS,
3076 };
3077 struct zram *zram;
3078 int ret, device_id;
3079
3080 zram = kzalloc_obj(struct zram);
3081 if (!zram)
3082 return -ENOMEM;
3083
3084 ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
3085 if (ret < 0)
3086 goto out_free_dev;
3087 device_id = ret;
3088
3089 init_rwsem(&zram->dev_lock);
3090 #ifdef CONFIG_ZRAM_WRITEBACK
3091 zram->wb_batch_size = 32;
3092 zram->compressed_wb = false;
3093 #endif
3094
3095 /* gendisk structure */
3096 zram->disk = blk_alloc_disk(&lim, NUMA_NO_NODE);
3097 if (IS_ERR(zram->disk)) {
3098 pr_err("Error allocating disk structure for device %d\n",
3099 device_id);
3100 ret = PTR_ERR(zram->disk);
3101 goto out_free_idr;
3102 }
3103
3104 zram->disk->major = zram_major;
3105 zram->disk->first_minor = device_id;
3106 zram->disk->minors = 1;
3107 zram->disk->flags |= GENHD_FL_NO_PART;
3108 zram->disk->fops = &zram_devops;
3109 zram->disk->private_data = zram;
3110 snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
3111 zram_comp_params_reset(zram);
3112 comp_algorithm_set(zram, ZRAM_PRIMARY_COMP, default_compressor);
3113
3114 /* Actual capacity set using sysfs (/sys/block/zram<id>/disksize */
3115 set_capacity(zram->disk, 0);
3116 ret = device_add_disk(NULL, zram->disk, zram_disk_groups);
3117 if (ret)
3118 goto out_cleanup_disk;
3119
3120 zram_debugfs_register(zram);
3121 pr_info("Added device: %s\n", zram->disk->disk_name);
3122 return device_id;
3123
3124 out_cleanup_disk:
3125 put_disk(zram->disk);
3126 out_free_idr:
3127 idr_remove(&zram_index_idr, device_id);
3128 out_free_dev:
3129 kfree(zram);
3130 return ret;
3131 }
3132
zram_remove(struct zram * zram)3133 static int zram_remove(struct zram *zram)
3134 {
3135 bool claimed;
3136
3137 mutex_lock(&zram->disk->open_mutex);
3138 if (disk_openers(zram->disk)) {
3139 mutex_unlock(&zram->disk->open_mutex);
3140 return -EBUSY;
3141 }
3142
3143 claimed = zram->claim;
3144 if (!claimed)
3145 zram->claim = true;
3146 mutex_unlock(&zram->disk->open_mutex);
3147
3148 zram_debugfs_unregister(zram);
3149
3150 if (claimed) {
3151 /*
3152 * If we were claimed by reset_store(), del_gendisk() will
3153 * wait until reset_store() is done, so nothing need to do.
3154 */
3155 ;
3156 } else {
3157 /* Make sure all the pending I/O are finished */
3158 sync_blockdev(zram->disk->part0);
3159 zram_reset_device(zram);
3160 }
3161
3162 pr_info("Removed device: %s\n", zram->disk->disk_name);
3163
3164 del_gendisk(zram->disk);
3165
3166 /* del_gendisk drains pending reset_store */
3167 WARN_ON_ONCE(claimed && zram->claim);
3168
3169 /*
3170 * disksize_store() may be called in between zram_reset_device()
3171 * and del_gendisk(), so run the last reset to avoid leaking
3172 * anything allocated with disksize_store()
3173 */
3174 zram_reset_device(zram);
3175
3176 put_disk(zram->disk);
3177 kfree(zram);
3178 return 0;
3179 }
3180
3181 /* zram-control sysfs attributes */
3182
3183 /*
3184 * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
3185 * sense that reading from this file does alter the state of your system -- it
3186 * creates a new un-initialized zram device and returns back this device's
3187 * device_id (or an error code if it fails to create a new device).
3188 */
hot_add_show(const struct class * class,const struct class_attribute * attr,char * buf)3189 static ssize_t hot_add_show(const struct class *class,
3190 const struct class_attribute *attr,
3191 char *buf)
3192 {
3193 int ret;
3194
3195 mutex_lock(&zram_index_mutex);
3196 ret = zram_add();
3197 mutex_unlock(&zram_index_mutex);
3198
3199 if (ret < 0)
3200 return ret;
3201 return sysfs_emit(buf, "%d\n", ret);
3202 }
3203 /* This attribute must be set to 0400, so CLASS_ATTR_RO() can not be used */
3204 static struct class_attribute class_attr_hot_add =
3205 __ATTR(hot_add, 0400, hot_add_show, NULL);
3206
hot_remove_store(const struct class * class,const struct class_attribute * attr,const char * buf,size_t count)3207 static ssize_t hot_remove_store(const struct class *class,
3208 const struct class_attribute *attr,
3209 const char *buf,
3210 size_t count)
3211 {
3212 struct zram *zram;
3213 int ret, dev_id;
3214
3215 /* dev_id is gendisk->first_minor, which is `int' */
3216 ret = kstrtoint(buf, 10, &dev_id);
3217 if (ret)
3218 return ret;
3219 if (dev_id < 0)
3220 return -EINVAL;
3221
3222 mutex_lock(&zram_index_mutex);
3223
3224 zram = idr_find(&zram_index_idr, dev_id);
3225 if (zram) {
3226 ret = zram_remove(zram);
3227 if (!ret)
3228 idr_remove(&zram_index_idr, dev_id);
3229 } else {
3230 ret = -ENODEV;
3231 }
3232
3233 mutex_unlock(&zram_index_mutex);
3234 return ret ? ret : count;
3235 }
3236 static CLASS_ATTR_WO(hot_remove);
3237
3238 static struct attribute *zram_control_class_attrs[] = {
3239 &class_attr_hot_add.attr,
3240 &class_attr_hot_remove.attr,
3241 NULL,
3242 };
3243 ATTRIBUTE_GROUPS(zram_control_class);
3244
3245 static struct class zram_control_class = {
3246 .name = "zram-control",
3247 .class_groups = zram_control_class_groups,
3248 };
3249
zram_remove_cb(int id,void * ptr,void * data)3250 static int zram_remove_cb(int id, void *ptr, void *data)
3251 {
3252 WARN_ON_ONCE(zram_remove(ptr));
3253 return 0;
3254 }
3255
destroy_devices(void)3256 static void destroy_devices(void)
3257 {
3258 class_unregister(&zram_control_class);
3259 idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
3260 zram_debugfs_destroy();
3261 idr_destroy(&zram_index_idr);
3262 unregister_blkdev(zram_major, "zram");
3263 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
3264 }
3265
zram_init(void)3266 static int __init zram_init(void)
3267 {
3268 struct zram_table_entry zram_te;
3269 int ret;
3270
3271 BUILD_BUG_ON(__NR_ZRAM_PAGEFLAGS > sizeof(zram_te.attr.flags) * 8);
3272
3273 ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
3274 zcomp_cpu_up_prepare, zcomp_cpu_dead);
3275 if (ret < 0)
3276 return ret;
3277
3278 ret = class_register(&zram_control_class);
3279 if (ret) {
3280 pr_err("Unable to register zram-control class\n");
3281 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
3282 return ret;
3283 }
3284
3285 zram_debugfs_create();
3286 zram_major = register_blkdev(0, "zram");
3287 if (zram_major <= 0) {
3288 pr_err("Unable to get major number\n");
3289 class_unregister(&zram_control_class);
3290 cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
3291 return -EBUSY;
3292 }
3293
3294 while (num_devices != 0) {
3295 mutex_lock(&zram_index_mutex);
3296 ret = zram_add();
3297 mutex_unlock(&zram_index_mutex);
3298 if (ret < 0)
3299 goto out_error;
3300 num_devices--;
3301 }
3302
3303 return 0;
3304
3305 out_error:
3306 destroy_devices();
3307 return ret;
3308 }
3309
zram_exit(void)3310 static void __exit zram_exit(void)
3311 {
3312 destroy_devices();
3313 }
3314
3315 module_init(zram_init);
3316 module_exit(zram_exit);
3317
3318 module_param(num_devices, uint, 0);
3319 MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
3320
3321 MODULE_LICENSE("Dual BSD/GPL");
3322 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
3323 MODULE_DESCRIPTION("Compressed RAM Block Device");
3324