xref: /linux/fs/btrfs/zstd.c (revision 2d8b3d9b210a388129e41757372d70c66ae20a5b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2016-present, Facebook, Inc.
4  * All rights reserved.
5  *
6  */
7 
8 #include <linux/bio.h>
9 #include <linux/bitmap.h>
10 #include <linux/err.h>
11 #include <linux/init.h>
12 #include <linux/kernel.h>
13 #include <linux/mm.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 "misc.h"
21 #include "fs.h"
22 #include "btrfs_inode.h"
23 #include "compression.h"
24 #include "super.h"
25 
26 #define ZSTD_BTRFS_MAX_WINDOWLOG 17
27 #define ZSTD_BTRFS_MAX_INPUT (1U << ZSTD_BTRFS_MAX_WINDOWLOG)
28 #define ZSTD_BTRFS_DEFAULT_LEVEL 3
29 #define ZSTD_BTRFS_MIN_LEVEL -15
30 #define ZSTD_BTRFS_MAX_LEVEL 15
31 /* 307s to avoid pathologically clashing with transaction commit */
32 #define ZSTD_BTRFS_RECLAIM_JIFFIES (307 * HZ)
33 
34 static zstd_parameters zstd_get_btrfs_parameters(int level,
35 						 size_t src_len)
36 {
37 	zstd_parameters params = zstd_get_params(level, src_len);
38 
39 	if (params.cParams.windowLog > ZSTD_BTRFS_MAX_WINDOWLOG)
40 		params.cParams.windowLog = ZSTD_BTRFS_MAX_WINDOWLOG;
41 	WARN_ON(src_len > ZSTD_BTRFS_MAX_INPUT);
42 	return params;
43 }
44 
45 struct workspace {
46 	void *mem;
47 	size_t size;
48 	char *buf;
49 	int level;
50 	int req_level;
51 	unsigned long last_used; /* jiffies */
52 	struct list_head list;
53 	struct list_head lru_list;
54 	zstd_in_buffer in_buf;
55 	zstd_out_buffer out_buf;
56 	zstd_parameters params;
57 };
58 
59 /*
60  * Zstd Workspace Management
61  *
62  * Zstd workspaces have different memory requirements depending on the level.
63  * The zstd workspaces are managed by having individual lists for each level
64  * and a global lru.  Forward progress is maintained by protecting a max level
65  * workspace.
66  *
67  * Getting a workspace is done by using the bitmap to identify the levels that
68  * have available workspaces and scans up.  This lets us recycle higher level
69  * workspaces because of the monotonic memory guarantee.  A workspace's
70  * last_used is only updated if it is being used by the corresponding memory
71  * level.  Putting a workspace involves adding it back to the appropriate places
72  * and adding it back to the lru if necessary.
73  *
74  * A timer is used to reclaim workspaces if they have not been used for
75  * ZSTD_BTRFS_RECLAIM_JIFFIES.  This helps keep only active workspaces around.
76  * The upper bound is provided by the workqueue limit which is 2 (percpu limit).
77  */
78 
79 struct zstd_workspace_manager {
80 	spinlock_t lock;
81 	struct list_head lru_list;
82 	struct list_head idle_ws[ZSTD_BTRFS_MAX_LEVEL];
83 	unsigned long active_map;
84 	wait_queue_head_t wait;
85 	struct timer_list timer;
86 };
87 
88 static size_t zstd_ws_mem_sizes[ZSTD_BTRFS_MAX_LEVEL];
89 
90 static inline struct workspace *list_to_workspace(struct list_head *list)
91 {
92 	return container_of(list, struct workspace, list);
93 }
94 
95 static inline int clip_level(int level)
96 {
97 	return max(0, level - 1);
98 }
99 
100 /*
101  * Timer callback to free unused workspaces.
102  *
103  * @t: timer
104  *
105  * This scans the lru_list and attempts to reclaim any workspace that hasn't
106  * been used for ZSTD_BTRFS_RECLAIM_JIFFIES.
107  *
108  * The context is softirq and does not need the _bh locking primitives.
109  */
110 static void zstd_reclaim_timer_fn(struct timer_list *timer)
111 {
112 	struct zstd_workspace_manager *zwsm =
113 		container_of(timer, struct zstd_workspace_manager, timer);
114 	unsigned long reclaim_threshold = jiffies - ZSTD_BTRFS_RECLAIM_JIFFIES;
115 	struct list_head *pos, *next;
116 
117 	spin_lock(&zwsm->lock);
118 
119 	if (list_empty(&zwsm->lru_list)) {
120 		spin_unlock(&zwsm->lock);
121 		return;
122 	}
123 
124 	list_for_each_prev_safe(pos, next, &zwsm->lru_list) {
125 		struct workspace *victim = container_of(pos, struct workspace,
126 							lru_list);
127 		int level;
128 
129 		if (time_after(victim->last_used, reclaim_threshold))
130 			break;
131 
132 		/* workspace is in use */
133 		if (victim->req_level)
134 			continue;
135 
136 		level = victim->level;
137 		list_del(&victim->lru_list);
138 		list_del(&victim->list);
139 		zstd_free_workspace(&victim->list);
140 
141 		if (list_empty(&zwsm->idle_ws[level]))
142 			clear_bit(level, &zwsm->active_map);
143 
144 	}
145 
146 	if (!list_empty(&zwsm->lru_list))
147 		mod_timer(&zwsm->timer, jiffies + ZSTD_BTRFS_RECLAIM_JIFFIES);
148 
149 	spin_unlock(&zwsm->lock);
150 }
151 
152 /*
153  * Calculate monotonic memory bounds.
154  *
155  * It is possible based on the level configurations that a higher level
156  * workspace uses less memory than a lower level workspace.  In order to reuse
157  * workspaces, this must be made a monotonic relationship.  This precomputes
158  * the required memory for each level and enforces the monotonicity between
159  * level and memory required.
160  */
161 static void zstd_calc_ws_mem_sizes(void)
162 {
163 	size_t max_size = 0;
164 	int level;
165 
166 	for (level = ZSTD_BTRFS_MIN_LEVEL; level <= ZSTD_BTRFS_MAX_LEVEL; level++) {
167 		if (level == 0)
168 			continue;
169 		zstd_parameters params =
170 			zstd_get_btrfs_parameters(level, ZSTD_BTRFS_MAX_INPUT);
171 		size_t level_size =
172 			max_t(size_t,
173 			      zstd_cstream_workspace_bound(&params.cParams),
174 			      zstd_dstream_workspace_bound(ZSTD_BTRFS_MAX_INPUT));
175 
176 		max_size = max_t(size_t, max_size, level_size);
177 		/* Use level 1 workspace size for all the fast mode negative levels. */
178 		zstd_ws_mem_sizes[clip_level(level)] = max_size;
179 	}
180 }
181 
182 int zstd_alloc_workspace_manager(struct btrfs_fs_info *fs_info)
183 {
184 	struct zstd_workspace_manager *zwsm;
185 	struct list_head *ws;
186 
187 	ASSERT(fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD] == NULL);
188 	zwsm = kzalloc_obj(*zwsm);
189 	if (!zwsm)
190 		return -ENOMEM;
191 	zstd_calc_ws_mem_sizes();
192 	spin_lock_init(&zwsm->lock);
193 	init_waitqueue_head(&zwsm->wait);
194 	timer_setup(&zwsm->timer, zstd_reclaim_timer_fn, 0);
195 
196 	INIT_LIST_HEAD(&zwsm->lru_list);
197 	for (int i = 0; i < ZSTD_BTRFS_MAX_LEVEL; i++)
198 		INIT_LIST_HEAD(&zwsm->idle_ws[i]);
199 	fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD] = zwsm;
200 
201 	ws = zstd_alloc_workspace(fs_info, ZSTD_BTRFS_MAX_LEVEL);
202 	if (IS_ERR(ws)) {
203 		btrfs_warn(NULL, "cannot preallocate zstd compression workspace");
204 	} else {
205 		set_bit(ZSTD_BTRFS_MAX_LEVEL - 1, &zwsm->active_map);
206 		list_add(ws, &zwsm->idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1]);
207 	}
208 	return 0;
209 }
210 
211 void zstd_free_workspace_manager(struct btrfs_fs_info *fs_info)
212 {
213 	struct zstd_workspace_manager *zwsm = fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD];
214 	struct workspace *workspace;
215 
216 	if (!zwsm)
217 		return;
218 	fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD] = NULL;
219 	spin_lock_bh(&zwsm->lock);
220 	for (int i = 0; i < ZSTD_BTRFS_MAX_LEVEL; i++) {
221 		while (!list_empty(&zwsm->idle_ws[i])) {
222 			workspace = container_of(zwsm->idle_ws[i].next,
223 						 struct workspace, list);
224 			list_del(&workspace->list);
225 			list_del(&workspace->lru_list);
226 			zstd_free_workspace(&workspace->list);
227 		}
228 	}
229 	spin_unlock_bh(&zwsm->lock);
230 	timer_delete_sync(&zwsm->timer);
231 	kfree(zwsm);
232 }
233 
234 /*
235  * Find workspace for given level.
236  *
237  * @level: compression level
238  *
239  * This iterates over the set bits in the active_map beginning at the requested
240  * compression level.  This lets us utilize already allocated workspaces before
241  * allocating a new one.  If the workspace is of a larger size, it is used, but
242  * the place in the lru_list and last_used times are not updated.  This is to
243  * offer the opportunity to reclaim the workspace in favor of allocating an
244  * appropriately sized one in the future.
245  */
246 static struct list_head *zstd_find_workspace(struct btrfs_fs_info *fs_info, int level)
247 {
248 	struct zstd_workspace_manager *zwsm = fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD];
249 	struct list_head *ws;
250 	struct workspace *workspace;
251 	int i = clip_level(level);
252 
253 	ASSERT(zwsm);
254 	spin_lock_bh(&zwsm->lock);
255 	for_each_set_bit_from(i, &zwsm->active_map, ZSTD_BTRFS_MAX_LEVEL) {
256 		if (!list_empty(&zwsm->idle_ws[i])) {
257 			ws = zwsm->idle_ws[i].next;
258 			workspace = list_to_workspace(ws);
259 			list_del_init(ws);
260 			/* keep its place if it's a lower level using this */
261 			workspace->req_level = level;
262 			if (clip_level(level) == workspace->level)
263 				list_del(&workspace->lru_list);
264 			if (list_empty(&zwsm->idle_ws[i]))
265 				clear_bit(i, &zwsm->active_map);
266 			spin_unlock_bh(&zwsm->lock);
267 			return ws;
268 		}
269 	}
270 	spin_unlock_bh(&zwsm->lock);
271 
272 	return NULL;
273 }
274 
275 /*
276  * Zstd get_workspace for level.
277  *
278  * @level: compression level
279  *
280  * If @level is 0, then any compression level can be used.  Therefore, we begin
281  * scanning from 1.  We first scan through possible workspaces and then after
282  * attempt to allocate a new workspace.  If we fail to allocate one due to
283  * memory pressure, go to sleep waiting for the max level workspace to free up.
284  */
285 struct list_head *zstd_get_workspace(struct btrfs_fs_info *fs_info, int level)
286 {
287 	struct zstd_workspace_manager *zwsm = fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD];
288 	struct list_head *ws;
289 	unsigned int nofs_flag;
290 
291 	ASSERT(zwsm);
292 
293 	/* level == 0 means we can use any workspace */
294 	if (!level)
295 		level = 1;
296 
297 again:
298 	ws = zstd_find_workspace(fs_info, level);
299 	if (ws)
300 		return ws;
301 
302 	nofs_flag = memalloc_nofs_save();
303 	ws = zstd_alloc_workspace(fs_info, level);
304 	memalloc_nofs_restore(nofs_flag);
305 
306 	if (IS_ERR(ws)) {
307 		DEFINE_WAIT(wait);
308 
309 		prepare_to_wait(&zwsm->wait, &wait, TASK_UNINTERRUPTIBLE);
310 		/*
311 		 * Re-check after being queued: zstd_put_workspace() only wakes
312 		 * a queue that already has a sleeper, so a workspace returned
313 		 * since the failed allocation woke nobody.
314 		 */
315 		ws = zstd_find_workspace(fs_info, level);
316 		if (!ws)
317 			schedule();
318 		finish_wait(&zwsm->wait, &wait);
319 		if (ws)
320 			return ws;
321 
322 		goto again;
323 	}
324 
325 	return ws;
326 }
327 
328 /*
329  * Zstd put_workspace.
330  *
331  * @ws: list_head for the workspace
332  *
333  * When putting back a workspace, we only need to update the LRU if we are of
334  * the requested compression level.  Here is where we continue to protect the
335  * max level workspace or update last_used accordingly.  If the reclaim timer
336  * isn't set, it is also set here.  Only the max level workspace tries and wakes
337  * up waiting workspaces.
338  */
339 void zstd_put_workspace(struct btrfs_fs_info *fs_info, struct list_head *ws)
340 {
341 	struct zstd_workspace_manager *zwsm = fs_info->compr_wsm[BTRFS_COMPRESS_ZSTD];
342 	struct workspace *workspace = list_to_workspace(ws);
343 	bool wakeup;
344 
345 	ASSERT(zwsm);
346 	spin_lock_bh(&zwsm->lock);
347 
348 	/* A node is only taken off the lru if we are the corresponding level */
349 	if (clip_level(workspace->req_level) == workspace->level) {
350 		/* Hide a max level workspace from reclaim */
351 		if (workspace->level == ZSTD_BTRFS_MAX_LEVEL - 1 &&
352 		    list_empty(&zwsm->idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1])) {
353 			INIT_LIST_HEAD(&workspace->lru_list);
354 		} else {
355 			workspace->last_used = jiffies;
356 			list_add(&workspace->lru_list, &zwsm->lru_list);
357 			if (!timer_pending(&zwsm->timer))
358 				mod_timer(&zwsm->timer,
359 					  jiffies + ZSTD_BTRFS_RECLAIM_JIFFIES);
360 		}
361 	}
362 
363 	set_bit(workspace->level, &zwsm->active_map);
364 	list_add(&workspace->list, &zwsm->idle_ws[workspace->level]);
365 	workspace->req_level = 0;
366 
367 	/*
368 	 * Check if we should wakeup before releasing the lock because after
369 	 * that the reclaim function can run and free the workspace.
370 	 */
371 	wakeup = (workspace->level == clip_level(ZSTD_BTRFS_MAX_LEVEL));
372 	spin_unlock_bh(&zwsm->lock);
373 
374 	if (wakeup)
375 		cond_wake_up(&zwsm->wait);
376 }
377 
378 void zstd_free_workspace(struct list_head *ws)
379 {
380 	struct workspace *workspace = list_entry(ws, struct workspace, list);
381 
382 	kvfree(workspace->mem);
383 	kvfree(workspace->buf);
384 	kfree(workspace);
385 }
386 
387 struct list_head *zstd_alloc_workspace(struct btrfs_fs_info *fs_info, int level)
388 {
389 	struct workspace *workspace;
390 
391 	workspace = kzalloc_obj(*workspace);
392 	if (!workspace)
393 		return ERR_PTR(-ENOMEM);
394 
395 	/* Use level 1 workspace size for all the fast mode negative levels. */
396 	workspace->size = zstd_ws_mem_sizes[clip_level(level)];
397 	workspace->level = clip_level(level);
398 	workspace->req_level = level;
399 	workspace->last_used = jiffies;
400 	workspace->mem = kvmalloc(workspace->size, GFP_KERNEL | __GFP_NOWARN);
401 	workspace->buf = kvmalloc(fs_info->sectorsize, GFP_KERNEL);
402 	if (!workspace->mem || !workspace->buf)
403 		goto fail;
404 
405 	INIT_LIST_HEAD(&workspace->list);
406 	INIT_LIST_HEAD(&workspace->lru_list);
407 
408 	return &workspace->list;
409 fail:
410 	zstd_free_workspace(&workspace->list);
411 	return ERR_PTR(-ENOMEM);
412 }
413 
414 int zstd_compress_bio(struct list_head *ws, struct compressed_bio *cb)
415 {
416 	struct btrfs_inode *inode = cb->bbio.inode;
417 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
418 	struct workspace *workspace = list_entry(ws, struct workspace, list);
419 	struct address_space *mapping = inode->vfs_inode.i_mapping;
420 	struct bio *bio = &cb->bbio.bio;
421 	zstd_cstream *stream;
422 	int ret = 0;
423 	/* The current folio to read. */
424 	struct folio *in_folio = NULL;
425 	/* The current folio to write to. */
426 	struct folio *out_folio = NULL;
427 	unsigned long tot_in = 0;
428 	unsigned long tot_out = 0;
429 	const u64 start = cb->start;
430 	const u32 len = cb->len;
431 	const u64 end = start + len;
432 	const u32 min_folio_size = btrfs_min_folio_size(fs_info);
433 
434 	workspace->params = zstd_get_btrfs_parameters(workspace->req_level, len);
435 
436 	/* Initialize the stream. */
437 	stream = zstd_init_cstream(&workspace->params, len, workspace->mem, workspace->size);
438 	if (unlikely(!stream)) {
439 		btrfs_err(fs_info,
440 	"zstd compression init level %d failed, root %llu inode %llu offset %llu",
441 			  workspace->req_level, btrfs_root_id(inode->root),
442 			  btrfs_ino(inode), start);
443 		ret = -EIO;
444 		goto out;
445 	}
446 
447 	/* Map in the first page of input data. */
448 	ret = btrfs_compress_filemap_get_folio(mapping, start, &in_folio);
449 	if (ret < 0)
450 		goto out;
451 	workspace->in_buf.src = kmap_local_folio(in_folio, offset_in_folio(in_folio, start));
452 	workspace->in_buf.pos = 0;
453 	workspace->in_buf.size = btrfs_calc_input_length(in_folio, end, start);
454 
455 	/* Allocate and map in the output buffer. */
456 	out_folio = btrfs_alloc_compr_folio(fs_info, GFP_NOFS);
457 	if (out_folio == NULL) {
458 		ret = -ENOMEM;
459 		goto out;
460 	}
461 	workspace->out_buf.dst = folio_address(out_folio);
462 	workspace->out_buf.pos = 0;
463 	workspace->out_buf.size = min_folio_size;
464 
465 	while (1) {
466 		size_t ret2;
467 
468 		ret2 = zstd_compress_stream(stream, &workspace->out_buf, &workspace->in_buf);
469 		if (unlikely(zstd_is_error(ret2))) {
470 			btrfs_warn(fs_info,
471 "zstd compression level %d failed, error %d root %llu inode %llu offset %llu",
472 				   workspace->req_level, zstd_get_error_code(ret2),
473 				   btrfs_root_id(inode->root), btrfs_ino(inode),
474 				   start + tot_in);
475 			ret = -EIO;
476 			goto out;
477 		}
478 
479 		/* Check to see if we are making it bigger. */
480 		if (tot_in + workspace->in_buf.pos > fs_info->sectorsize * 2 &&
481 		    tot_in + workspace->in_buf.pos < tot_out + workspace->out_buf.pos) {
482 			ret = -E2BIG;
483 			goto out;
484 		}
485 
486 		/* Check if we need more output space. */
487 		if (workspace->out_buf.pos >= workspace->out_buf.size) {
488 			tot_out += min_folio_size;
489 			if (tot_out >= len) {
490 				ret = -E2BIG;
491 				goto out;
492 			}
493 			/* Queue the current foliot into the bio. */
494 			if (!bio_add_folio(bio, out_folio, folio_size(out_folio), 0)) {
495 				ret = -E2BIG;
496 				goto out;
497 			}
498 
499 			out_folio = btrfs_alloc_compr_folio(fs_info, GFP_NOFS);
500 			if (out_folio == NULL) {
501 				ret = -ENOMEM;
502 				goto out;
503 			}
504 			workspace->out_buf.dst = folio_address(out_folio);
505 			workspace->out_buf.pos = 0;
506 			workspace->out_buf.size = min_folio_size;
507 		}
508 
509 		/* We've reached the end of the input. */
510 		if (tot_in + workspace->in_buf.pos >= len) {
511 			tot_in += workspace->in_buf.pos;
512 			break;
513 		}
514 
515 		/* Check if we need more input. */
516 		if (workspace->in_buf.pos >= workspace->in_buf.size) {
517 			u64 cur;
518 
519 			tot_in += workspace->in_buf.size;
520 			cur = start + tot_in;
521 
522 			kunmap_local(workspace->in_buf.src);
523 			workspace->in_buf.src = NULL;
524 			folio_put(in_folio);
525 
526 			ret = btrfs_compress_filemap_get_folio(mapping, cur, &in_folio);
527 			if (ret < 0)
528 				goto out;
529 			workspace->in_buf.src = kmap_local_folio(in_folio,
530 							 offset_in_folio(in_folio, cur));
531 			workspace->in_buf.pos = 0;
532 			workspace->in_buf.size = btrfs_calc_input_length(in_folio, end, cur);
533 		}
534 	}
535 
536 	while (1) {
537 		size_t ret2;
538 
539 		ret2 = zstd_end_stream(stream, &workspace->out_buf);
540 		if (unlikely(zstd_is_error(ret2))) {
541 			btrfs_err(fs_info,
542 "zstd compression end level %d failed, error %d root %llu inode %llu offset %llu",
543 				  workspace->req_level, zstd_get_error_code(ret2),
544 				  btrfs_root_id(inode->root), btrfs_ino(inode),
545 				  start + tot_in);
546 			ret = -EIO;
547 			goto out;
548 		}
549 		/* Queue the remaining part of the output folio into bio. */
550 		if (ret2 == 0) {
551 			tot_out += workspace->out_buf.pos;
552 			if (tot_out >= len) {
553 				ret = -E2BIG;
554 				goto out;
555 			}
556 			if (!bio_add_folio(bio, out_folio, workspace->out_buf.pos, 0)) {
557 				ret = -E2BIG;
558 				goto out;
559 			}
560 			out_folio = NULL;
561 			break;
562 		}
563 		tot_out += min_folio_size;
564 		if (tot_out >= len) {
565 			ret = -E2BIG;
566 			goto out;
567 		}
568 		if (!bio_add_folio(bio, out_folio, folio_size(out_folio), 0)) {
569 			ret = -E2BIG;
570 			goto out;
571 		}
572 		out_folio = btrfs_alloc_compr_folio(fs_info, GFP_NOFS);
573 		if (out_folio == NULL) {
574 			ret = -ENOMEM;
575 			goto out;
576 		}
577 		workspace->out_buf.dst = folio_address(out_folio);
578 		workspace->out_buf.pos = 0;
579 		workspace->out_buf.size = min_folio_size;
580 	}
581 
582 	if (tot_out >= tot_in) {
583 		ret = -E2BIG;
584 		goto out;
585 	}
586 
587 	ret = 0;
588 	ASSERT(tot_out == bio->bi_iter.bi_size);
589 out:
590 	if (out_folio)
591 		btrfs_free_compr_folio(out_folio);
592 	if (workspace->in_buf.src) {
593 		kunmap_local(workspace->in_buf.src);
594 		folio_put(in_folio);
595 	}
596 	return ret;
597 }
598 
599 /*
600  * Map the destination for the next chunk of output.
601  *
602  * @decompressed is the offset of the next output byte inside the fully
603  * decompressed extent.  If that offset has reached the current destination
604  * segment, its page-bounded bio_vec is kmapped so that zstd can write into the
605  * page cache directly, and the number of bytes writable there is returned.
606  * Otherwise @kaddr_ret is set to NULL and the number of bytes to skip before
607  * that segment is returned.  This covers both the initial prefix and gaps in
608  * the destination bio.
609  */
610 static u32 zstd_map_dest(struct compressed_bio *cb, u32 decompressed,
611 			 void **kaddr_ret)
612 {
613 	struct bio *orig_bio = &cb->orig_bbio->bio;
614 	struct bio_vec bvec;
615 	u32 bvec_offset;
616 	u32 off;
617 
618 	bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
619 	/*
620 	 * cb->start may underflow, but subtracting that value can still give us
621 	 * the correct offset inside the full decompressed extent.
622 	 */
623 	bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
624 
625 	if (decompressed < bvec_offset) {
626 		*kaddr_ret = NULL;
627 		return bvec_offset - decompressed;
628 	}
629 
630 	off = decompressed - bvec_offset;
631 	ASSERT(off < bvec.bv_len);
632 	*kaddr_ret = bvec_kmap_local(&bvec) + off;
633 	return bvec.bv_len - off;
634 }
635 
636 int zstd_decompress_bio(struct list_head *ws, struct compressed_bio *cb)
637 {
638 	struct btrfs_fs_info *fs_info = cb_to_fs_info(cb);
639 	struct workspace *workspace = list_entry(ws, struct workspace, list);
640 	struct bio *orig_bio = &cb->orig_bbio->bio;
641 	struct folio_iter fi;
642 	size_t srclen = bio_get_size(&cb->bbio.bio);
643 	zstd_dstream *stream;
644 	int ret = 0;
645 	const unsigned int min_folio_size = btrfs_min_folio_size(fs_info);
646 	unsigned long folio_in_index = 0;
647 	unsigned long total_folios_in = DIV_ROUND_UP(srclen, min_folio_size);
648 	unsigned long total_out = 0;
649 
650 	bio_first_folio(&fi, &cb->bbio.bio, 0);
651 	if (unlikely(!fi.folio))
652 		return -EINVAL;
653 	ASSERT(folio_size(fi.folio) == min_folio_size);
654 
655 	stream = zstd_init_dstream(
656 			ZSTD_BTRFS_MAX_INPUT, workspace->mem, workspace->size);
657 	if (unlikely(!stream)) {
658 		struct btrfs_inode *inode = cb->bbio.inode;
659 
660 		btrfs_err(inode->root->fs_info,
661 		"zstd decompression init failed, root %llu inode %llu offset %llu",
662 			  btrfs_root_id(inode->root), btrfs_ino(inode), cb->start);
663 		ret = -EIO;
664 		goto done;
665 	}
666 
667 	workspace->in_buf.src = kmap_local_folio(fi.folio, 0);
668 	workspace->in_buf.pos = 0;
669 	workspace->in_buf.size = min_t(size_t, srclen, min_folio_size);
670 
671 	while (orig_bio->bi_iter.bi_size) {
672 		size_t ret2;
673 		void *kaddr;
674 		u32 dstlen;
675 
676 		dstlen = zstd_map_dest(cb, total_out, &kaddr);
677 		if (kaddr) {
678 			workspace->out_buf.dst = kaddr;
679 			workspace->out_buf.size = dstlen;
680 		} else {
681 			workspace->out_buf.dst = workspace->buf;
682 			workspace->out_buf.size = min_t(u32, dstlen,
683 							fs_info->sectorsize);
684 		}
685 		workspace->out_buf.pos = 0;
686 
687 		ret2 = zstd_decompress_stream(stream, &workspace->out_buf,
688 				&workspace->in_buf);
689 		if (kaddr)
690 			kunmap_local(kaddr);
691 		if (unlikely(zstd_is_error(ret2))) {
692 			struct btrfs_inode *inode = cb->bbio.inode;
693 
694 			btrfs_err(inode->root->fs_info,
695 		"zstd decompression failed, error %d root %llu inode %llu offset %llu",
696 				  zstd_get_error_code(ret2), btrfs_root_id(inode->root),
697 				  btrfs_ino(inode), cb->start);
698 			ret = -EIO;
699 			goto done;
700 		}
701 		total_out += workspace->out_buf.pos;
702 		if (kaddr)
703 			bio_advance(orig_bio, workspace->out_buf.pos);
704 
705 		if (workspace->in_buf.pos >= srclen)
706 			break;
707 
708 		/* Check if we've hit the end of a frame */
709 		if (ret2 == 0)
710 			break;
711 
712 		if (workspace->in_buf.pos == workspace->in_buf.size) {
713 			kunmap_local(workspace->in_buf.src);
714 			folio_in_index++;
715 			if (unlikely(folio_in_index >= total_folios_in)) {
716 				workspace->in_buf.src = NULL;
717 				ret = -EIO;
718 				goto done;
719 			}
720 			srclen -= min_folio_size;
721 			bio_next_folio(&fi, &cb->bbio.bio);
722 			ASSERT(fi.folio);
723 			workspace->in_buf.src = kmap_local_folio(fi.folio, 0);
724 			workspace->in_buf.pos = 0;
725 			workspace->in_buf.size = min_t(size_t, srclen, min_folio_size);
726 		}
727 	}
728 	ret = 0;
729 done:
730 	if (workspace->in_buf.src)
731 		kunmap_local(workspace->in_buf.src);
732 	return ret;
733 }
734 
735 int zstd_decompress(struct list_head *ws, const u8 *data_in,
736 		struct folio *dest_folio, unsigned long dest_pgoff, size_t srclen,
737 		size_t destlen)
738 {
739 	struct workspace *workspace = list_entry(ws, struct workspace, list);
740 	struct btrfs_fs_info *fs_info = btrfs_sb(folio_inode(dest_folio)->i_sb);
741 	zstd_dstream *stream;
742 	int ret = 0;
743 	unsigned long to_copy = 0;
744 
745 	stream = zstd_init_dstream(
746 			ZSTD_BTRFS_MAX_INPUT, workspace->mem, workspace->size);
747 	if (unlikely(!stream)) {
748 		struct btrfs_inode *inode = folio_to_inode(dest_folio);
749 
750 		btrfs_err(inode->root->fs_info,
751 		"zstd decompression init failed, root %llu inode %llu offset %llu",
752 			  btrfs_root_id(inode->root), btrfs_ino(inode),
753 			  folio_pos(dest_folio));
754 		ret = -EIO;
755 		goto finish;
756 	}
757 
758 	workspace->in_buf.src = data_in;
759 	workspace->in_buf.pos = 0;
760 	workspace->in_buf.size = srclen;
761 
762 	workspace->out_buf.dst = workspace->buf;
763 	workspace->out_buf.pos = 0;
764 	workspace->out_buf.size = fs_info->sectorsize;
765 
766 	/*
767 	 * Since both input and output buffers should not exceed one sector,
768 	 * one call should end the decompression.
769 	 */
770 	ret = zstd_decompress_stream(stream, &workspace->out_buf, &workspace->in_buf);
771 	if (unlikely(zstd_is_error(ret))) {
772 		struct btrfs_inode *inode = folio_to_inode(dest_folio);
773 
774 		btrfs_err(inode->root->fs_info,
775 		"zstd decompression failed, error %d root %llu inode %llu offset %llu",
776 			  zstd_get_error_code(ret), btrfs_root_id(inode->root),
777 			  btrfs_ino(inode), folio_pos(dest_folio));
778 		goto finish;
779 	}
780 	to_copy = workspace->out_buf.pos;
781 	memcpy_to_folio(dest_folio, dest_pgoff, workspace->out_buf.dst, to_copy);
782 finish:
783 	/* Error or early end. */
784 	if (unlikely(to_copy < destlen)) {
785 		ret = -EIO;
786 		folio_zero_range(dest_folio, dest_pgoff + to_copy, destlen - to_copy);
787 	}
788 	return ret;
789 }
790 
791 const struct btrfs_compress_levels btrfs_zstd_compress = {
792 	.min_level	= ZSTD_BTRFS_MIN_LEVEL,
793 	.max_level	= ZSTD_BTRFS_MAX_LEVEL,
794 	.default_level	= ZSTD_BTRFS_DEFAULT_LEVEL,
795 };
796