1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (c) 2016-present, Facebook, Inc.
9 #include <linux/bitmap.h>
10 #include <linux/err.h>
11 #include <linux/init.h>
12 #include <linux/kernel.h>
14 #include <linux/sched/mm.h>
15 #include <linux/pagemap.h>
16 #include <linux/refcount.h>
17 #include <linux/sched.h>
18 #include <linux/slab.h>
19 #include <linux/zstd.h>
20 #include "compression.h"
23 #define ZSTD_BTRFS_MAX_WINDOWLOG 17
24 #define ZSTD_BTRFS_MAX_INPUT (1 << ZSTD_BTRFS_MAX_WINDOWLOG)
25 #define ZSTD_BTRFS_DEFAULT_LEVEL 3
26 #define ZSTD_BTRFS_MAX_LEVEL 15
27 /* 307s to avoid pathologically clashing with transaction commit */
28 #define ZSTD_BTRFS_RECLAIM_JIFFIES (307 * HZ)
30 static ZSTD_parameters zstd_get_btrfs_parameters(unsigned int level,
33 ZSTD_parameters params = ZSTD_getParams(level, src_len, 0);
35 if (params.cParams.windowLog > ZSTD_BTRFS_MAX_WINDOWLOG)
36 params.cParams.windowLog = ZSTD_BTRFS_MAX_WINDOWLOG;
37 WARN_ON(src_len > ZSTD_BTRFS_MAX_INPUT);
46 unsigned int req_level;
47 unsigned long last_used; /* jiffies */
48 struct list_head list;
49 struct list_head lru_list;
51 ZSTD_outBuffer out_buf;
55 * Zstd Workspace Management
57 * Zstd workspaces have different memory requirements depending on the level.
58 * The zstd workspaces are managed by having individual lists for each level
59 * and a global lru. Forward progress is maintained by protecting a max level
62 * Getting a workspace is done by using the bitmap to identify the levels that
63 * have available workspaces and scans up. This lets us recycle higher level
64 * workspaces because of the monotonic memory guarantee. A workspace's
65 * last_used is only updated if it is being used by the corresponding memory
66 * level. Putting a workspace involves adding it back to the appropriate places
67 * and adding it back to the lru if necessary.
69 * A timer is used to reclaim workspaces if they have not been used for
70 * ZSTD_BTRFS_RECLAIM_JIFFIES. This helps keep only active workspaces around.
71 * The upper bound is provided by the workqueue limit which is 2 (percpu limit).
74 struct zstd_workspace_manager {
75 const struct btrfs_compress_op *ops;
77 struct list_head lru_list;
78 struct list_head idle_ws[ZSTD_BTRFS_MAX_LEVEL];
79 unsigned long active_map;
80 wait_queue_head_t wait;
81 struct timer_list timer;
84 static struct zstd_workspace_manager wsm;
86 static size_t zstd_ws_mem_sizes[ZSTD_BTRFS_MAX_LEVEL];
88 static inline struct workspace *list_to_workspace(struct list_head *list)
90 return container_of(list, struct workspace, list);
94 * zstd_reclaim_timer_fn - reclaim timer
97 * This scans the lru_list and attempts to reclaim any workspace that hasn't
98 * been used for ZSTD_BTRFS_RECLAIM_JIFFIES.
100 static void zstd_reclaim_timer_fn(struct timer_list *timer)
102 unsigned long reclaim_threshold = jiffies - ZSTD_BTRFS_RECLAIM_JIFFIES;
103 struct list_head *pos, *next;
105 spin_lock(&wsm.lock);
107 if (list_empty(&wsm.lru_list)) {
108 spin_unlock(&wsm.lock);
112 list_for_each_prev_safe(pos, next, &wsm.lru_list) {
113 struct workspace *victim = container_of(pos, struct workspace,
117 if (time_after(victim->last_used, reclaim_threshold))
120 /* workspace is in use */
121 if (victim->req_level)
124 level = victim->level;
125 list_del(&victim->lru_list);
126 list_del(&victim->list);
127 wsm.ops->free_workspace(&victim->list);
129 if (list_empty(&wsm.idle_ws[level - 1]))
130 clear_bit(level - 1, &wsm.active_map);
134 if (!list_empty(&wsm.lru_list))
135 mod_timer(&wsm.timer, jiffies + ZSTD_BTRFS_RECLAIM_JIFFIES);
137 spin_unlock(&wsm.lock);
141 * zstd_calc_ws_mem_sizes - calculate monotonic memory bounds
143 * It is possible based on the level configurations that a higher level
144 * workspace uses less memory than a lower level workspace. In order to reuse
145 * workspaces, this must be made a monotonic relationship. This precomputes
146 * the required memory for each level and enforces the monotonicity between
147 * level and memory required.
149 static void zstd_calc_ws_mem_sizes(void)
154 for (level = 1; level <= ZSTD_BTRFS_MAX_LEVEL; level++) {
155 ZSTD_parameters params =
156 zstd_get_btrfs_parameters(level, ZSTD_BTRFS_MAX_INPUT);
159 ZSTD_CStreamWorkspaceBound(params.cParams),
160 ZSTD_DStreamWorkspaceBound(ZSTD_BTRFS_MAX_INPUT));
162 max_size = max_t(size_t, max_size, level_size);
163 zstd_ws_mem_sizes[level - 1] = max_size;
167 static void zstd_init_workspace_manager(void)
169 struct list_head *ws;
172 zstd_calc_ws_mem_sizes();
174 wsm.ops = &btrfs_zstd_compress;
175 spin_lock_init(&wsm.lock);
176 init_waitqueue_head(&wsm.wait);
177 timer_setup(&wsm.timer, zstd_reclaim_timer_fn, 0);
179 INIT_LIST_HEAD(&wsm.lru_list);
180 for (i = 0; i < ZSTD_BTRFS_MAX_LEVEL; i++)
181 INIT_LIST_HEAD(&wsm.idle_ws[i]);
183 ws = wsm.ops->alloc_workspace(ZSTD_BTRFS_MAX_LEVEL);
186 "BTRFS: cannot preallocate zstd compression workspace\n");
188 set_bit(ZSTD_BTRFS_MAX_LEVEL - 1, &wsm.active_map);
189 list_add(ws, &wsm.idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1]);
193 static void zstd_cleanup_workspace_manager(void)
195 struct workspace *workspace;
198 del_timer(&wsm.timer);
200 for (i = 0; i < ZSTD_BTRFS_MAX_LEVEL; i++) {
201 while (!list_empty(&wsm.idle_ws[i])) {
202 workspace = container_of(wsm.idle_ws[i].next,
203 struct workspace, list);
204 list_del(&workspace->list);
205 list_del(&workspace->lru_list);
206 wsm.ops->free_workspace(&workspace->list);
212 * zstd_find_workspace - find workspace
213 * @level: compression level
215 * This iterates over the set bits in the active_map beginning at the requested
216 * compression level. This lets us utilize already allocated workspaces before
217 * allocating a new one. If the workspace is of a larger size, it is used, but
218 * the place in the lru_list and last_used times are not updated. This is to
219 * offer the opportunity to reclaim the workspace in favor of allocating an
220 * appropriately sized one in the future.
222 static struct list_head *zstd_find_workspace(unsigned int level)
224 struct list_head *ws;
225 struct workspace *workspace;
228 spin_lock(&wsm.lock);
229 for_each_set_bit_from(i, &wsm.active_map, ZSTD_BTRFS_MAX_LEVEL) {
230 if (!list_empty(&wsm.idle_ws[i])) {
231 ws = wsm.idle_ws[i].next;
232 workspace = list_to_workspace(ws);
234 /* keep its place if it's a lower level using this */
235 workspace->req_level = level;
236 if (level == workspace->level)
237 list_del(&workspace->lru_list);
238 if (list_empty(&wsm.idle_ws[i]))
239 clear_bit(i, &wsm.active_map);
240 spin_unlock(&wsm.lock);
244 spin_unlock(&wsm.lock);
250 * zstd_get_workspace - zstd's get_workspace
251 * @level: compression level
253 * If @level is 0, then any compression level can be used. Therefore, we begin
254 * scanning from 1. We first scan through possible workspaces and then after
255 * attempt to allocate a new workspace. If we fail to allocate one due to
256 * memory pressure, go to sleep waiting for the max level workspace to free up.
258 static struct list_head *zstd_get_workspace(unsigned int level)
260 struct list_head *ws;
261 unsigned int nofs_flag;
263 /* level == 0 means we can use any workspace */
268 ws = zstd_find_workspace(level);
272 nofs_flag = memalloc_nofs_save();
273 ws = wsm.ops->alloc_workspace(level);
274 memalloc_nofs_restore(nofs_flag);
279 prepare_to_wait(&wsm.wait, &wait, TASK_UNINTERRUPTIBLE);
281 finish_wait(&wsm.wait, &wait);
290 * zstd_put_workspace - zstd put_workspace
291 * @ws: list_head for the workspace
293 * When putting back a workspace, we only need to update the LRU if we are of
294 * the requested compression level. Here is where we continue to protect the
295 * max level workspace or update last_used accordingly. If the reclaim timer
296 * isn't set, it is also set here. Only the max level workspace tries and wakes
297 * up waiting workspaces.
299 static void zstd_put_workspace(struct list_head *ws)
301 struct workspace *workspace = list_to_workspace(ws);
303 spin_lock(&wsm.lock);
305 /* A node is only taken off the lru if we are the corresponding level */
306 if (workspace->req_level == workspace->level) {
307 /* Hide a max level workspace from reclaim */
308 if (list_empty(&wsm.idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1])) {
309 INIT_LIST_HEAD(&workspace->lru_list);
311 workspace->last_used = jiffies;
312 list_add(&workspace->lru_list, &wsm.lru_list);
313 if (!timer_pending(&wsm.timer))
314 mod_timer(&wsm.timer,
315 jiffies + ZSTD_BTRFS_RECLAIM_JIFFIES);
319 set_bit(workspace->level - 1, &wsm.active_map);
320 list_add(&workspace->list, &wsm.idle_ws[workspace->level - 1]);
321 workspace->req_level = 0;
323 spin_unlock(&wsm.lock);
325 if (workspace->level == ZSTD_BTRFS_MAX_LEVEL)
326 cond_wake_up(&wsm.wait);
329 static void zstd_free_workspace(struct list_head *ws)
331 struct workspace *workspace = list_entry(ws, struct workspace, list);
333 kvfree(workspace->mem);
334 kfree(workspace->buf);
338 static struct list_head *zstd_alloc_workspace(unsigned int level)
340 struct workspace *workspace;
342 workspace = kzalloc(sizeof(*workspace), GFP_KERNEL);
344 return ERR_PTR(-ENOMEM);
346 workspace->size = zstd_ws_mem_sizes[level - 1];
347 workspace->level = level;
348 workspace->req_level = level;
349 workspace->last_used = jiffies;
350 workspace->mem = kvmalloc(workspace->size, GFP_KERNEL);
351 workspace->buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
352 if (!workspace->mem || !workspace->buf)
355 INIT_LIST_HEAD(&workspace->list);
356 INIT_LIST_HEAD(&workspace->lru_list);
358 return &workspace->list;
360 zstd_free_workspace(&workspace->list);
361 return ERR_PTR(-ENOMEM);
364 static int zstd_compress_pages(struct list_head *ws,
365 struct address_space *mapping,
368 unsigned long *out_pages,
369 unsigned long *total_in,
370 unsigned long *total_out)
372 struct workspace *workspace = list_entry(ws, struct workspace, list);
373 ZSTD_CStream *stream;
376 struct page *in_page = NULL; /* The current page to read */
377 struct page *out_page = NULL; /* The current page to write to */
378 unsigned long tot_in = 0;
379 unsigned long tot_out = 0;
380 unsigned long len = *total_out;
381 const unsigned long nr_dest_pages = *out_pages;
382 unsigned long max_out = nr_dest_pages * PAGE_SIZE;
383 ZSTD_parameters params = zstd_get_btrfs_parameters(workspace->req_level,
390 /* Initialize the stream */
391 stream = ZSTD_initCStream(params, len, workspace->mem,
394 pr_warn("BTRFS: ZSTD_initCStream failed\n");
399 /* map in the first page of input data */
400 in_page = find_get_page(mapping, start >> PAGE_SHIFT);
401 workspace->in_buf.src = kmap(in_page);
402 workspace->in_buf.pos = 0;
403 workspace->in_buf.size = min_t(size_t, len, PAGE_SIZE);
406 /* Allocate and map in the output buffer */
407 out_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
408 if (out_page == NULL) {
412 pages[nr_pages++] = out_page;
413 workspace->out_buf.dst = kmap(out_page);
414 workspace->out_buf.pos = 0;
415 workspace->out_buf.size = min_t(size_t, max_out, PAGE_SIZE);
420 ret2 = ZSTD_compressStream(stream, &workspace->out_buf,
422 if (ZSTD_isError(ret2)) {
423 pr_debug("BTRFS: ZSTD_compressStream returned %d\n",
424 ZSTD_getErrorCode(ret2));
429 /* Check to see if we are making it bigger */
430 if (tot_in + workspace->in_buf.pos > 8192 &&
431 tot_in + workspace->in_buf.pos <
432 tot_out + workspace->out_buf.pos) {
437 /* We've reached the end of our output range */
438 if (workspace->out_buf.pos >= max_out) {
439 tot_out += workspace->out_buf.pos;
444 /* Check if we need more output space */
445 if (workspace->out_buf.pos == workspace->out_buf.size) {
446 tot_out += PAGE_SIZE;
447 max_out -= PAGE_SIZE;
449 if (nr_pages == nr_dest_pages) {
454 out_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
455 if (out_page == NULL) {
459 pages[nr_pages++] = out_page;
460 workspace->out_buf.dst = kmap(out_page);
461 workspace->out_buf.pos = 0;
462 workspace->out_buf.size = min_t(size_t, max_out,
466 /* We've reached the end of the input */
467 if (workspace->in_buf.pos >= len) {
468 tot_in += workspace->in_buf.pos;
472 /* Check if we need more input */
473 if (workspace->in_buf.pos == workspace->in_buf.size) {
480 in_page = find_get_page(mapping, start >> PAGE_SHIFT);
481 workspace->in_buf.src = kmap(in_page);
482 workspace->in_buf.pos = 0;
483 workspace->in_buf.size = min_t(size_t, len, PAGE_SIZE);
489 ret2 = ZSTD_endStream(stream, &workspace->out_buf);
490 if (ZSTD_isError(ret2)) {
491 pr_debug("BTRFS: ZSTD_endStream returned %d\n",
492 ZSTD_getErrorCode(ret2));
497 tot_out += workspace->out_buf.pos;
500 if (workspace->out_buf.pos >= max_out) {
501 tot_out += workspace->out_buf.pos;
506 tot_out += PAGE_SIZE;
507 max_out -= PAGE_SIZE;
509 if (nr_pages == nr_dest_pages) {
514 out_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
515 if (out_page == NULL) {
519 pages[nr_pages++] = out_page;
520 workspace->out_buf.dst = kmap(out_page);
521 workspace->out_buf.pos = 0;
522 workspace->out_buf.size = min_t(size_t, max_out, PAGE_SIZE);
525 if (tot_out >= tot_in) {
532 *total_out = tot_out;
534 *out_pages = nr_pages;
545 static int zstd_decompress_bio(struct list_head *ws, struct compressed_bio *cb)
547 struct workspace *workspace = list_entry(ws, struct workspace, list);
548 struct page **pages_in = cb->compressed_pages;
549 u64 disk_start = cb->start;
550 struct bio *orig_bio = cb->orig_bio;
551 size_t srclen = cb->compressed_len;
552 ZSTD_DStream *stream;
554 unsigned long page_in_index = 0;
555 unsigned long total_pages_in = DIV_ROUND_UP(srclen, PAGE_SIZE);
556 unsigned long buf_start;
557 unsigned long total_out = 0;
559 stream = ZSTD_initDStream(
560 ZSTD_BTRFS_MAX_INPUT, workspace->mem, workspace->size);
562 pr_debug("BTRFS: ZSTD_initDStream failed\n");
567 workspace->in_buf.src = kmap(pages_in[page_in_index]);
568 workspace->in_buf.pos = 0;
569 workspace->in_buf.size = min_t(size_t, srclen, PAGE_SIZE);
571 workspace->out_buf.dst = workspace->buf;
572 workspace->out_buf.pos = 0;
573 workspace->out_buf.size = PAGE_SIZE;
578 ret2 = ZSTD_decompressStream(stream, &workspace->out_buf,
580 if (ZSTD_isError(ret2)) {
581 pr_debug("BTRFS: ZSTD_decompressStream returned %d\n",
582 ZSTD_getErrorCode(ret2));
586 buf_start = total_out;
587 total_out += workspace->out_buf.pos;
588 workspace->out_buf.pos = 0;
590 ret = btrfs_decompress_buf2page(workspace->out_buf.dst,
591 buf_start, total_out, disk_start, orig_bio);
595 if (workspace->in_buf.pos >= srclen)
598 /* Check if we've hit the end of a frame */
602 if (workspace->in_buf.pos == workspace->in_buf.size) {
603 kunmap(pages_in[page_in_index++]);
604 if (page_in_index >= total_pages_in) {
605 workspace->in_buf.src = NULL;
610 workspace->in_buf.src = kmap(pages_in[page_in_index]);
611 workspace->in_buf.pos = 0;
612 workspace->in_buf.size = min_t(size_t, srclen, PAGE_SIZE);
616 zero_fill_bio(orig_bio);
618 if (workspace->in_buf.src)
619 kunmap(pages_in[page_in_index]);
623 static int zstd_decompress(struct list_head *ws, unsigned char *data_in,
624 struct page *dest_page,
625 unsigned long start_byte,
626 size_t srclen, size_t destlen)
628 struct workspace *workspace = list_entry(ws, struct workspace, list);
629 ZSTD_DStream *stream;
632 unsigned long total_out = 0;
633 unsigned long pg_offset = 0;
636 stream = ZSTD_initDStream(
637 ZSTD_BTRFS_MAX_INPUT, workspace->mem, workspace->size);
639 pr_warn("BTRFS: ZSTD_initDStream failed\n");
644 destlen = min_t(size_t, destlen, PAGE_SIZE);
646 workspace->in_buf.src = data_in;
647 workspace->in_buf.pos = 0;
648 workspace->in_buf.size = srclen;
650 workspace->out_buf.dst = workspace->buf;
651 workspace->out_buf.pos = 0;
652 workspace->out_buf.size = PAGE_SIZE;
655 while (pg_offset < destlen
656 && workspace->in_buf.pos < workspace->in_buf.size) {
657 unsigned long buf_start;
658 unsigned long buf_offset;
661 /* Check if the frame is over and we still need more input */
663 pr_debug("BTRFS: ZSTD_decompressStream ended early\n");
667 ret2 = ZSTD_decompressStream(stream, &workspace->out_buf,
669 if (ZSTD_isError(ret2)) {
670 pr_debug("BTRFS: ZSTD_decompressStream returned %d\n",
671 ZSTD_getErrorCode(ret2));
676 buf_start = total_out;
677 total_out += workspace->out_buf.pos;
678 workspace->out_buf.pos = 0;
680 if (total_out <= start_byte)
683 if (total_out > start_byte && buf_start < start_byte)
684 buf_offset = start_byte - buf_start;
688 bytes = min_t(unsigned long, destlen - pg_offset,
689 workspace->out_buf.size - buf_offset);
691 kaddr = kmap_atomic(dest_page);
692 memcpy(kaddr + pg_offset, workspace->out_buf.dst + buf_offset,
694 kunmap_atomic(kaddr);
700 if (pg_offset < destlen) {
701 kaddr = kmap_atomic(dest_page);
702 memset(kaddr + pg_offset, 0, destlen - pg_offset);
703 kunmap_atomic(kaddr);
708 static unsigned int zstd_set_level(unsigned int level)
711 return ZSTD_BTRFS_DEFAULT_LEVEL;
713 return min_t(unsigned int, level, ZSTD_BTRFS_MAX_LEVEL);
716 const struct btrfs_compress_op btrfs_zstd_compress = {
717 .init_workspace_manager = zstd_init_workspace_manager,
718 .cleanup_workspace_manager = zstd_cleanup_workspace_manager,
719 .get_workspace = zstd_get_workspace,
720 .put_workspace = zstd_put_workspace,
721 .alloc_workspace = zstd_alloc_workspace,
722 .free_workspace = zstd_free_workspace,
723 .compress_pages = zstd_compress_pages,
724 .decompress_bio = zstd_decompress_bio,
725 .decompress = zstd_decompress,
726 .set_level = zstd_set_level,