xref: /freebsd/sys/contrib/openzfs/module/zstd/zfs_zstd.c (revision 15f0b8c309dea1dcb14d3e374686576ff68ac43f)
1eda14cbcSMatt Macy /*
2eda14cbcSMatt Macy  * BSD 3-Clause New License (https://spdx.org/licenses/BSD-3-Clause.html)
3eda14cbcSMatt Macy  *
4eda14cbcSMatt Macy  * Redistribution and use in source and binary forms, with or without
5eda14cbcSMatt Macy  * modification, are permitted provided that the following conditions are met:
6eda14cbcSMatt Macy  *
7eda14cbcSMatt Macy  * 1. Redistributions of source code must retain the above copyright notice,
8eda14cbcSMatt Macy  * this list of conditions and the following disclaimer.
9eda14cbcSMatt Macy  *
10eda14cbcSMatt Macy  * 2. Redistributions in binary form must reproduce the above copyright notice,
11eda14cbcSMatt Macy  * this list of conditions and the following disclaimer in the documentation
12eda14cbcSMatt Macy  * and/or other materials provided with the distribution.
13eda14cbcSMatt Macy  *
14eda14cbcSMatt Macy  * 3. Neither the name of the copyright holder nor the names of its
15eda14cbcSMatt Macy  * contributors may be used to endorse or promote products derived from this
16eda14cbcSMatt Macy  * software without specific prior written permission.
17eda14cbcSMatt Macy  *
18eda14cbcSMatt Macy  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19eda14cbcSMatt Macy  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20eda14cbcSMatt Macy  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21eda14cbcSMatt Macy  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22eda14cbcSMatt Macy  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23eda14cbcSMatt Macy  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24eda14cbcSMatt Macy  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25eda14cbcSMatt Macy  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26eda14cbcSMatt Macy  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27eda14cbcSMatt Macy  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28eda14cbcSMatt Macy  * POSSIBILITY OF SUCH DAMAGE.
29eda14cbcSMatt Macy  */
30eda14cbcSMatt Macy 
31eda14cbcSMatt Macy /*
32eda14cbcSMatt Macy  * Copyright (c) 2016-2018, Klara Inc.
33eda14cbcSMatt Macy  * Copyright (c) 2016-2018, Allan Jude
34eda14cbcSMatt Macy  * Copyright (c) 2018-2020, Sebastian Gottschall
35eda14cbcSMatt Macy  * Copyright (c) 2019-2020, Michael Niewöhner
36eda14cbcSMatt Macy  * Copyright (c) 2020, The FreeBSD Foundation [1]
37eda14cbcSMatt Macy  *
38eda14cbcSMatt Macy  * [1] Portions of this software were developed by Allan Jude
39eda14cbcSMatt Macy  *     under sponsorship from the FreeBSD Foundation.
40eda14cbcSMatt Macy  */
41eda14cbcSMatt Macy 
42eda14cbcSMatt Macy #include <sys/param.h>
43eda14cbcSMatt Macy #include <sys/sysmacros.h>
44eda14cbcSMatt Macy #include <sys/zfs_context.h>
45eda14cbcSMatt Macy #include <sys/zio_compress.h>
46eda14cbcSMatt Macy #include <sys/spa.h>
47eda14cbcSMatt Macy #include <sys/zstd/zstd.h>
48eda14cbcSMatt Macy 
49eda14cbcSMatt Macy #define	ZSTD_STATIC_LINKING_ONLY
50eda14cbcSMatt Macy #include "lib/zstd.h"
51c03c5b1cSMartin Matuska #include "lib/common/zstd_errors.h"
52eda14cbcSMatt Macy 
53e3aa18adSMartin Matuska #ifndef IN_LIBSA
54be181ee2SMartin Matuska static uint_t zstd_earlyabort_pass = 1;
55e3aa18adSMartin Matuska static int zstd_cutoff_level = ZIO_ZSTD_LEVEL_3;
56e3aa18adSMartin Matuska static unsigned int zstd_abort_size = (128 * 1024);
57e3aa18adSMartin Matuska #endif
58e3aa18adSMartin Matuska 
59716fd348SMartin Matuska static kstat_t *zstd_ksp = NULL;
60eda14cbcSMatt Macy 
61eda14cbcSMatt Macy typedef struct zstd_stats {
62eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_alloc_fail;
63eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_alloc_fallback;
64eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_com_alloc_fail;
65eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_dec_alloc_fail;
66eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_com_inval;
67eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_dec_inval;
68eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_dec_header_inval;
69eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_com_fail;
70eda14cbcSMatt Macy 	kstat_named_t	zstd_stat_dec_fail;
71e3aa18adSMartin Matuska 	/*
72e3aa18adSMartin Matuska 	 * LZ4 first-pass early abort verdict
73e3aa18adSMartin Matuska 	 */
74e3aa18adSMartin Matuska 	kstat_named_t	zstd_stat_lz4pass_allowed;
75e3aa18adSMartin Matuska 	kstat_named_t	zstd_stat_lz4pass_rejected;
76e3aa18adSMartin Matuska 	/*
77e3aa18adSMartin Matuska 	 * zstd-1 second-pass early abort verdict
78e3aa18adSMartin Matuska 	 */
79e3aa18adSMartin Matuska 	kstat_named_t	zstd_stat_zstdpass_allowed;
80e3aa18adSMartin Matuska 	kstat_named_t	zstd_stat_zstdpass_rejected;
81e3aa18adSMartin Matuska 	/*
82e3aa18adSMartin Matuska 	 * We excluded this from early abort for some reason
83e3aa18adSMartin Matuska 	 */
84e3aa18adSMartin Matuska 	kstat_named_t	zstd_stat_passignored;
85e3aa18adSMartin Matuska 	kstat_named_t	zstd_stat_passignored_size;
864a58b4abSMateusz Guzik 	kstat_named_t	zstd_stat_buffers;
874a58b4abSMateusz Guzik 	kstat_named_t	zstd_stat_size;
88eda14cbcSMatt Macy } zstd_stats_t;
89eda14cbcSMatt Macy 
90eda14cbcSMatt Macy static zstd_stats_t zstd_stats = {
91eda14cbcSMatt Macy 	{ "alloc_fail",			KSTAT_DATA_UINT64 },
92eda14cbcSMatt Macy 	{ "alloc_fallback",		KSTAT_DATA_UINT64 },
93eda14cbcSMatt Macy 	{ "compress_alloc_fail",	KSTAT_DATA_UINT64 },
94eda14cbcSMatt Macy 	{ "decompress_alloc_fail",	KSTAT_DATA_UINT64 },
95eda14cbcSMatt Macy 	{ "compress_level_invalid",	KSTAT_DATA_UINT64 },
96eda14cbcSMatt Macy 	{ "decompress_level_invalid",	KSTAT_DATA_UINT64 },
97eda14cbcSMatt Macy 	{ "decompress_header_invalid",	KSTAT_DATA_UINT64 },
98eda14cbcSMatt Macy 	{ "compress_failed",		KSTAT_DATA_UINT64 },
99eda14cbcSMatt Macy 	{ "decompress_failed",		KSTAT_DATA_UINT64 },
100e3aa18adSMartin Matuska 	{ "lz4pass_allowed",		KSTAT_DATA_UINT64 },
101e3aa18adSMartin Matuska 	{ "lz4pass_rejected",		KSTAT_DATA_UINT64 },
102e3aa18adSMartin Matuska 	{ "zstdpass_allowed",		KSTAT_DATA_UINT64 },
103e3aa18adSMartin Matuska 	{ "zstdpass_rejected",		KSTAT_DATA_UINT64 },
104e3aa18adSMartin Matuska 	{ "passignored",		KSTAT_DATA_UINT64 },
105e3aa18adSMartin Matuska 	{ "passignored_size",		KSTAT_DATA_UINT64 },
1064a58b4abSMateusz Guzik 	{ "buffers",			KSTAT_DATA_UINT64 },
1074a58b4abSMateusz Guzik 	{ "size",			KSTAT_DATA_UINT64 },
108eda14cbcSMatt Macy };
109eda14cbcSMatt Macy 
110e3aa18adSMartin Matuska #ifdef _KERNEL
111e3aa18adSMartin Matuska static int
112e3aa18adSMartin Matuska kstat_zstd_update(kstat_t *ksp, int rw)
113e3aa18adSMartin Matuska {
114e3aa18adSMartin Matuska 	ASSERT(ksp != NULL);
115e3aa18adSMartin Matuska 
116e3aa18adSMartin Matuska 	if (rw == KSTAT_WRITE && ksp == zstd_ksp) {
117e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_alloc_fail);
118e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_alloc_fallback);
119e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_com_alloc_fail);
120e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_dec_alloc_fail);
121e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_com_inval);
122e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_dec_inval);
123e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_dec_header_inval);
124e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_com_fail);
125e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_dec_fail);
126e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_lz4pass_allowed);
127e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_lz4pass_rejected);
128e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_zstdpass_allowed);
129e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_zstdpass_rejected);
130e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_passignored);
131e3aa18adSMartin Matuska 		ZSTDSTAT_ZERO(zstd_stat_passignored_size);
132e3aa18adSMartin Matuska 	}
133e3aa18adSMartin Matuska 
134e3aa18adSMartin Matuska 	return (0);
135e3aa18adSMartin Matuska }
136e3aa18adSMartin Matuska #endif
137e3aa18adSMartin Matuska 
138eda14cbcSMatt Macy /* Enums describing the allocator type specified by kmem_type in zstd_kmem */
139eda14cbcSMatt Macy enum zstd_kmem_type {
140eda14cbcSMatt Macy 	ZSTD_KMEM_UNKNOWN = 0,
141eda14cbcSMatt Macy 	/* Allocation type using kmem_vmalloc */
142eda14cbcSMatt Macy 	ZSTD_KMEM_DEFAULT,
143eda14cbcSMatt Macy 	/* Pool based allocation using mempool_alloc */
144eda14cbcSMatt Macy 	ZSTD_KMEM_POOL,
145eda14cbcSMatt Macy 	/* Reserved fallback memory for decompression only */
146eda14cbcSMatt Macy 	ZSTD_KMEM_DCTX,
147eda14cbcSMatt Macy 	ZSTD_KMEM_COUNT,
148eda14cbcSMatt Macy };
149eda14cbcSMatt Macy 
150eda14cbcSMatt Macy /* Structure for pooled memory objects */
151eda14cbcSMatt Macy struct zstd_pool {
152eda14cbcSMatt Macy 	void *mem;
153eda14cbcSMatt Macy 	size_t size;
154eda14cbcSMatt Macy 	kmutex_t barrier;
155eda14cbcSMatt Macy 	hrtime_t timeout;
156eda14cbcSMatt Macy };
157eda14cbcSMatt Macy 
158eda14cbcSMatt Macy /* Global structure for handling memory allocations */
159eda14cbcSMatt Macy struct zstd_kmem {
160eda14cbcSMatt Macy 	enum zstd_kmem_type kmem_type;
161eda14cbcSMatt Macy 	size_t kmem_size;
162eda14cbcSMatt Macy 	struct zstd_pool *pool;
163eda14cbcSMatt Macy };
164eda14cbcSMatt Macy 
165eda14cbcSMatt Macy /* Fallback memory structure used for decompression only if memory runs out */
166eda14cbcSMatt Macy struct zstd_fallback_mem {
167eda14cbcSMatt Macy 	size_t mem_size;
168eda14cbcSMatt Macy 	void *mem;
169eda14cbcSMatt Macy 	kmutex_t barrier;
170eda14cbcSMatt Macy };
171eda14cbcSMatt Macy 
172eda14cbcSMatt Macy struct zstd_levelmap {
173eda14cbcSMatt Macy 	int16_t zstd_level;
174eda14cbcSMatt Macy 	enum zio_zstd_levels level;
175eda14cbcSMatt Macy };
176eda14cbcSMatt Macy 
177eda14cbcSMatt Macy /*
178eda14cbcSMatt Macy  * ZSTD memory handlers
179eda14cbcSMatt Macy  *
180eda14cbcSMatt Macy  * For decompression we use a different handler which also provides fallback
181eda14cbcSMatt Macy  * memory allocation in case memory runs out.
182eda14cbcSMatt Macy  *
183eda14cbcSMatt Macy  * The ZSTD handlers were split up for the most simplified implementation.
184eda14cbcSMatt Macy  */
1854f0c9b76SWarner Losh #ifndef IN_LIBSA
186eda14cbcSMatt Macy static void *zstd_alloc(void *opaque, size_t size);
1874f0c9b76SWarner Losh #endif
188eda14cbcSMatt Macy static void *zstd_dctx_alloc(void *opaque, size_t size);
189eda14cbcSMatt Macy static void zstd_free(void *opaque, void *ptr);
190eda14cbcSMatt Macy 
1914f0c9b76SWarner Losh #ifndef IN_LIBSA
192eda14cbcSMatt Macy /* Compression memory handler */
193eda14cbcSMatt Macy static const ZSTD_customMem zstd_malloc = {
194eda14cbcSMatt Macy 	zstd_alloc,
195eda14cbcSMatt Macy 	zstd_free,
196eda14cbcSMatt Macy 	NULL,
197eda14cbcSMatt Macy };
1984f0c9b76SWarner Losh #endif
199eda14cbcSMatt Macy 
200eda14cbcSMatt Macy /* Decompression memory handler */
201eda14cbcSMatt Macy static const ZSTD_customMem zstd_dctx_malloc = {
202eda14cbcSMatt Macy 	zstd_dctx_alloc,
203eda14cbcSMatt Macy 	zstd_free,
204eda14cbcSMatt Macy 	NULL,
205eda14cbcSMatt Macy };
206eda14cbcSMatt Macy 
207eda14cbcSMatt Macy /* Level map for converting ZFS internal levels to ZSTD levels and vice versa */
208eda14cbcSMatt Macy static struct zstd_levelmap zstd_levels[] = {
209eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_1, ZIO_ZSTD_LEVEL_1},
210eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_2, ZIO_ZSTD_LEVEL_2},
211eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_3, ZIO_ZSTD_LEVEL_3},
212eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_4, ZIO_ZSTD_LEVEL_4},
213eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_5, ZIO_ZSTD_LEVEL_5},
214eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_6, ZIO_ZSTD_LEVEL_6},
215eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_7, ZIO_ZSTD_LEVEL_7},
216eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_8, ZIO_ZSTD_LEVEL_8},
217eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_9, ZIO_ZSTD_LEVEL_9},
218eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_10, ZIO_ZSTD_LEVEL_10},
219eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_11, ZIO_ZSTD_LEVEL_11},
220eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_12, ZIO_ZSTD_LEVEL_12},
221eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_13, ZIO_ZSTD_LEVEL_13},
222eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_14, ZIO_ZSTD_LEVEL_14},
223eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_15, ZIO_ZSTD_LEVEL_15},
224eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_16, ZIO_ZSTD_LEVEL_16},
225eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_17, ZIO_ZSTD_LEVEL_17},
226eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_18, ZIO_ZSTD_LEVEL_18},
227eda14cbcSMatt Macy 	{ZIO_ZSTD_LEVEL_19, ZIO_ZSTD_LEVEL_19},
228eda14cbcSMatt Macy 	{-1, ZIO_ZSTD_LEVEL_FAST_1},
229eda14cbcSMatt Macy 	{-2, ZIO_ZSTD_LEVEL_FAST_2},
230eda14cbcSMatt Macy 	{-3, ZIO_ZSTD_LEVEL_FAST_3},
231eda14cbcSMatt Macy 	{-4, ZIO_ZSTD_LEVEL_FAST_4},
232eda14cbcSMatt Macy 	{-5, ZIO_ZSTD_LEVEL_FAST_5},
233eda14cbcSMatt Macy 	{-6, ZIO_ZSTD_LEVEL_FAST_6},
234eda14cbcSMatt Macy 	{-7, ZIO_ZSTD_LEVEL_FAST_7},
235eda14cbcSMatt Macy 	{-8, ZIO_ZSTD_LEVEL_FAST_8},
236eda14cbcSMatt Macy 	{-9, ZIO_ZSTD_LEVEL_FAST_9},
237eda14cbcSMatt Macy 	{-10, ZIO_ZSTD_LEVEL_FAST_10},
238eda14cbcSMatt Macy 	{-20, ZIO_ZSTD_LEVEL_FAST_20},
239eda14cbcSMatt Macy 	{-30, ZIO_ZSTD_LEVEL_FAST_30},
240eda14cbcSMatt Macy 	{-40, ZIO_ZSTD_LEVEL_FAST_40},
241eda14cbcSMatt Macy 	{-50, ZIO_ZSTD_LEVEL_FAST_50},
242eda14cbcSMatt Macy 	{-60, ZIO_ZSTD_LEVEL_FAST_60},
243eda14cbcSMatt Macy 	{-70, ZIO_ZSTD_LEVEL_FAST_70},
244eda14cbcSMatt Macy 	{-80, ZIO_ZSTD_LEVEL_FAST_80},
245eda14cbcSMatt Macy 	{-90, ZIO_ZSTD_LEVEL_FAST_90},
246eda14cbcSMatt Macy 	{-100, ZIO_ZSTD_LEVEL_FAST_100},
247eda14cbcSMatt Macy 	{-500, ZIO_ZSTD_LEVEL_FAST_500},
248eda14cbcSMatt Macy 	{-1000, ZIO_ZSTD_LEVEL_FAST_1000},
249eda14cbcSMatt Macy };
250eda14cbcSMatt Macy 
251eda14cbcSMatt Macy /*
252eda14cbcSMatt Macy  * This variable represents the maximum count of the pool based on the number
253eda14cbcSMatt Macy  * of CPUs plus some buffer. We default to cpu count * 4, see init_zstd.
254eda14cbcSMatt Macy  */
255eda14cbcSMatt Macy static int pool_count = 16;
256eda14cbcSMatt Macy 
257eda14cbcSMatt Macy #define	ZSTD_POOL_MAX		pool_count
258eda14cbcSMatt Macy #define	ZSTD_POOL_TIMEOUT	60 * 2
259eda14cbcSMatt Macy 
260eda14cbcSMatt Macy static struct zstd_fallback_mem zstd_dctx_fallback;
261eda14cbcSMatt Macy static struct zstd_pool *zstd_mempool_cctx;
262eda14cbcSMatt Macy static struct zstd_pool *zstd_mempool_dctx;
263eda14cbcSMatt Macy 
2642617128aSMartin Matuska /*
2652617128aSMartin Matuska  * The library zstd code expects these if ADDRESS_SANITIZER gets defined,
2662617128aSMartin Matuska  * and while ASAN does this, KASAN defines that and does not. So to avoid
2672617128aSMartin Matuska  * changing the external code, we do this.
2682617128aSMartin Matuska  */
269c03c5b1cSMartin Matuska #if defined(ZFS_ASAN_ENABLED)
2702617128aSMartin Matuska #define	ADDRESS_SANITIZER 1
2712617128aSMartin Matuska #endif
2722617128aSMartin Matuska #if defined(_KERNEL) && defined(ADDRESS_SANITIZER)
2732617128aSMartin Matuska void __asan_unpoison_memory_region(void const volatile *addr, size_t size);
2742617128aSMartin Matuska void __asan_poison_memory_region(void const volatile *addr, size_t size);
2752617128aSMartin Matuska void __asan_unpoison_memory_region(void const volatile *addr, size_t size) {};
2762617128aSMartin Matuska void __asan_poison_memory_region(void const volatile *addr, size_t size) {};
2772617128aSMartin Matuska #endif
2782617128aSMartin Matuska 
2797877fdebSMatt Macy 
2807877fdebSMatt Macy static void
2817877fdebSMatt Macy zstd_mempool_reap(struct zstd_pool *zstd_mempool)
2827877fdebSMatt Macy {
2837877fdebSMatt Macy 	struct zstd_pool *pool;
2847877fdebSMatt Macy 
2857877fdebSMatt Macy 	if (!zstd_mempool || !ZSTDSTAT(zstd_stat_buffers)) {
2867877fdebSMatt Macy 		return;
2877877fdebSMatt Macy 	}
2887877fdebSMatt Macy 
2897877fdebSMatt Macy 	/* free obsolete slots */
2907877fdebSMatt Macy 	for (int i = 0; i < ZSTD_POOL_MAX; i++) {
2917877fdebSMatt Macy 		pool = &zstd_mempool[i];
2927877fdebSMatt Macy 		if (pool->mem && mutex_tryenter(&pool->barrier)) {
2937877fdebSMatt Macy 			/* Free memory if unused object older than 2 minutes */
2947877fdebSMatt Macy 			if (pool->mem && gethrestime_sec() > pool->timeout) {
2957877fdebSMatt Macy 				vmem_free(pool->mem, pool->size);
2967877fdebSMatt Macy 				ZSTDSTAT_SUB(zstd_stat_buffers, 1);
2977877fdebSMatt Macy 				ZSTDSTAT_SUB(zstd_stat_size, pool->size);
2987877fdebSMatt Macy 				pool->mem = NULL;
2997877fdebSMatt Macy 				pool->size = 0;
3007877fdebSMatt Macy 				pool->timeout = 0;
3017877fdebSMatt Macy 			}
3027877fdebSMatt Macy 			mutex_exit(&pool->barrier);
3037877fdebSMatt Macy 		}
3047877fdebSMatt Macy 	}
3057877fdebSMatt Macy }
3067877fdebSMatt Macy 
307eda14cbcSMatt Macy /*
308eda14cbcSMatt Macy  * Try to get a cached allocated buffer from memory pool or allocate a new one
309eda14cbcSMatt Macy  * if necessary. If a object is older than 2 minutes and does not fit the
310eda14cbcSMatt Macy  * requested size, it will be released and a new cached entry will be allocated.
311eda14cbcSMatt Macy  * If other pooled objects are detected without being used for 2 minutes, they
312eda14cbcSMatt Macy  * will be released, too.
313eda14cbcSMatt Macy  *
314eda14cbcSMatt Macy  * The concept is that high frequency memory allocations of bigger objects are
315eda14cbcSMatt Macy  * expensive. So if a lot of work is going on, allocations will be kept for a
316eda14cbcSMatt Macy  * while and can be reused in that time frame.
317eda14cbcSMatt Macy  *
318eda14cbcSMatt Macy  * The scheduled release will be updated every time a object is reused.
319eda14cbcSMatt Macy  */
3207877fdebSMatt Macy 
321eda14cbcSMatt Macy static void *
322eda14cbcSMatt Macy zstd_mempool_alloc(struct zstd_pool *zstd_mempool, size_t size)
323eda14cbcSMatt Macy {
324eda14cbcSMatt Macy 	struct zstd_pool *pool;
325eda14cbcSMatt Macy 	struct zstd_kmem *mem = NULL;
326eda14cbcSMatt Macy 
327eda14cbcSMatt Macy 	if (!zstd_mempool) {
328eda14cbcSMatt Macy 		return (NULL);
329eda14cbcSMatt Macy 	}
330eda14cbcSMatt Macy 
331eda14cbcSMatt Macy 	/* Seek for preallocated memory slot and free obsolete slots */
332eda14cbcSMatt Macy 	for (int i = 0; i < ZSTD_POOL_MAX; i++) {
333eda14cbcSMatt Macy 		pool = &zstd_mempool[i];
334eda14cbcSMatt Macy 		/*
33516038816SMartin Matuska 		 * This lock is simply a marker for a pool object being in use.
336eda14cbcSMatt Macy 		 * If it's already hold, it will be skipped.
337eda14cbcSMatt Macy 		 *
338eda14cbcSMatt Macy 		 * We need to create it before checking it to avoid race
339eda14cbcSMatt Macy 		 * conditions caused by running in a threaded context.
340eda14cbcSMatt Macy 		 *
341eda14cbcSMatt Macy 		 * The lock is later released by zstd_mempool_free.
342eda14cbcSMatt Macy 		 */
343eda14cbcSMatt Macy 		if (mutex_tryenter(&pool->barrier)) {
344eda14cbcSMatt Macy 			/*
345eda14cbcSMatt Macy 			 * Check if objects fits the size, if so we take it and
346eda14cbcSMatt Macy 			 * update the timestamp.
347eda14cbcSMatt Macy 			 */
3487877fdebSMatt Macy 			if (pool->mem && size <= pool->size) {
349eda14cbcSMatt Macy 				pool->timeout = gethrestime_sec() +
350eda14cbcSMatt Macy 				    ZSTD_POOL_TIMEOUT;
351eda14cbcSMatt Macy 				mem = pool->mem;
3527877fdebSMatt Macy 				return (mem);
353eda14cbcSMatt Macy 			}
354eda14cbcSMatt Macy 			mutex_exit(&pool->barrier);
355eda14cbcSMatt Macy 		}
356eda14cbcSMatt Macy 	}
357eda14cbcSMatt Macy 
358eda14cbcSMatt Macy 	/*
359eda14cbcSMatt Macy 	 * If no preallocated slot was found, try to fill in a new one.
360eda14cbcSMatt Macy 	 *
361eda14cbcSMatt Macy 	 * We run a similar algorithm twice here to avoid pool fragmentation.
362eda14cbcSMatt Macy 	 * The first one may generate holes in the list if objects get released.
363eda14cbcSMatt Macy 	 * We always make sure that these holes get filled instead of adding new
364eda14cbcSMatt Macy 	 * allocations constantly at the end.
365eda14cbcSMatt Macy 	 */
366eda14cbcSMatt Macy 	for (int i = 0; i < ZSTD_POOL_MAX; i++) {
367eda14cbcSMatt Macy 		pool = &zstd_mempool[i];
368eda14cbcSMatt Macy 		if (mutex_tryenter(&pool->barrier)) {
369eda14cbcSMatt Macy 			/* Object is free, try to allocate new one */
370eda14cbcSMatt Macy 			if (!pool->mem) {
371eda14cbcSMatt Macy 				mem = vmem_alloc(size, KM_SLEEP);
3724a58b4abSMateusz Guzik 				if (mem) {
3734a58b4abSMateusz Guzik 					ZSTDSTAT_ADD(zstd_stat_buffers, 1);
3744a58b4abSMateusz Guzik 					ZSTDSTAT_ADD(zstd_stat_size, size);
375eda14cbcSMatt Macy 					pool->mem = mem;
3764a58b4abSMateusz Guzik 					pool->size = size;
377eda14cbcSMatt Macy 					/* Keep track for later release */
378eda14cbcSMatt Macy 					mem->pool = pool;
379eda14cbcSMatt Macy 					mem->kmem_type = ZSTD_KMEM_POOL;
380eda14cbcSMatt Macy 					mem->kmem_size = size;
381eda14cbcSMatt Macy 				}
382eda14cbcSMatt Macy 			}
383eda14cbcSMatt Macy 
384eda14cbcSMatt Macy 			if (size <= pool->size) {
385eda14cbcSMatt Macy 				/* Update timestamp */
386eda14cbcSMatt Macy 				pool->timeout = gethrestime_sec() +
387eda14cbcSMatt Macy 				    ZSTD_POOL_TIMEOUT;
388eda14cbcSMatt Macy 
389eda14cbcSMatt Macy 				return (pool->mem);
390eda14cbcSMatt Macy 			}
391eda14cbcSMatt Macy 
392eda14cbcSMatt Macy 			mutex_exit(&pool->barrier);
393eda14cbcSMatt Macy 		}
394eda14cbcSMatt Macy 	}
395eda14cbcSMatt Macy 
396eda14cbcSMatt Macy 	/*
397eda14cbcSMatt Macy 	 * If the pool is full or the allocation failed, try lazy allocation
398eda14cbcSMatt Macy 	 * instead.
399eda14cbcSMatt Macy 	 */
400eda14cbcSMatt Macy 	if (!mem) {
401eda14cbcSMatt Macy 		mem = vmem_alloc(size, KM_NOSLEEP);
402eda14cbcSMatt Macy 		if (mem) {
403eda14cbcSMatt Macy 			mem->pool = NULL;
404eda14cbcSMatt Macy 			mem->kmem_type = ZSTD_KMEM_DEFAULT;
405eda14cbcSMatt Macy 			mem->kmem_size = size;
406eda14cbcSMatt Macy 		}
407eda14cbcSMatt Macy 	}
408eda14cbcSMatt Macy 
409eda14cbcSMatt Macy 	return (mem);
410eda14cbcSMatt Macy }
411eda14cbcSMatt Macy 
412eda14cbcSMatt Macy /* Mark object as released by releasing the barrier mutex */
413eda14cbcSMatt Macy static void
414eda14cbcSMatt Macy zstd_mempool_free(struct zstd_kmem *z)
415eda14cbcSMatt Macy {
416eda14cbcSMatt Macy 	mutex_exit(&z->pool->barrier);
417eda14cbcSMatt Macy }
418eda14cbcSMatt Macy 
419eda14cbcSMatt Macy /* Convert ZFS internal enum to ZSTD level */
420eda14cbcSMatt Macy static int
421eda14cbcSMatt Macy zstd_enum_to_level(enum zio_zstd_levels level, int16_t *zstd_level)
422eda14cbcSMatt Macy {
423eda14cbcSMatt Macy 	if (level > 0 && level <= ZIO_ZSTD_LEVEL_19) {
424eda14cbcSMatt Macy 		*zstd_level = zstd_levels[level - 1].zstd_level;
425eda14cbcSMatt Macy 		return (0);
426eda14cbcSMatt Macy 	}
427eda14cbcSMatt Macy 	if (level >= ZIO_ZSTD_LEVEL_FAST_1 &&
428eda14cbcSMatt Macy 	    level <= ZIO_ZSTD_LEVEL_FAST_1000) {
429eda14cbcSMatt Macy 		*zstd_level = zstd_levels[level - ZIO_ZSTD_LEVEL_FAST_1
430eda14cbcSMatt Macy 		    + ZIO_ZSTD_LEVEL_19].zstd_level;
431eda14cbcSMatt Macy 		return (0);
432eda14cbcSMatt Macy 	}
433eda14cbcSMatt Macy 
434eda14cbcSMatt Macy 	/* Invalid/unknown zfs compression enum - this should never happen. */
435eda14cbcSMatt Macy 	return (1);
436eda14cbcSMatt Macy }
437eda14cbcSMatt Macy 
438e3aa18adSMartin Matuska #ifndef IN_LIBSA
439e3aa18adSMartin Matuska size_t
440e3aa18adSMartin Matuska zfs_zstd_compress_wrap(void *s_start, void *d_start, size_t s_len, size_t d_len,
441e3aa18adSMartin Matuska     int level)
442e3aa18adSMartin Matuska {
443e3aa18adSMartin Matuska 	int16_t zstd_level;
444e3aa18adSMartin Matuska 	if (zstd_enum_to_level(level, &zstd_level)) {
445e3aa18adSMartin Matuska 		ZSTDSTAT_BUMP(zstd_stat_com_inval);
446e3aa18adSMartin Matuska 		return (s_len);
447e3aa18adSMartin Matuska 	}
448e3aa18adSMartin Matuska 	/*
449e3aa18adSMartin Matuska 	 * A zstd early abort heuristic.
450e3aa18adSMartin Matuska 	 *
451e3aa18adSMartin Matuska 	 * - Zeroth, if this is <= zstd-3, or < zstd_abort_size (currently
452e3aa18adSMartin Matuska 	 *   128k), don't try any of this, just go.
453e3aa18adSMartin Matuska 	 *   (because experimentally that was a reasonable cutoff for a perf win
454e3aa18adSMartin Matuska 	 *   with tiny ratio change)
455e3aa18adSMartin Matuska 	 * - First, we try LZ4 compression, and if it doesn't early abort, we
456e3aa18adSMartin Matuska 	 *   jump directly to whatever compression level we intended to try.
457e3aa18adSMartin Matuska 	 * - Second, we try zstd-1 - if that errors out (usually, but not
458e3aa18adSMartin Matuska 	 *   exclusively, if it would overflow), we give up early.
459e3aa18adSMartin Matuska 	 *
460e3aa18adSMartin Matuska 	 *   If it works, instead we go on and compress anyway.
461e3aa18adSMartin Matuska 	 *
462e3aa18adSMartin Matuska 	 * Why two passes? LZ4 alone gets you a lot of the way, but on highly
463e3aa18adSMartin Matuska 	 * compressible data, it was losing up to 8.5% of the compressed
464e3aa18adSMartin Matuska 	 * savings versus no early abort, and all the zstd-fast levels are
465e3aa18adSMartin Matuska 	 * worse indications on their own than LZ4, and don't improve the LZ4
466e3aa18adSMartin Matuska 	 * pass noticably if stacked like this.
467e3aa18adSMartin Matuska 	 */
468e3aa18adSMartin Matuska 	size_t actual_abort_size = zstd_abort_size;
469e3aa18adSMartin Matuska 	if (zstd_earlyabort_pass > 0 && zstd_level >= zstd_cutoff_level &&
470e3aa18adSMartin Matuska 	    s_len >= actual_abort_size) {
471e3aa18adSMartin Matuska 		int pass_len = 1;
472e3aa18adSMartin Matuska 		pass_len = lz4_compress_zfs(s_start, d_start, s_len, d_len, 0);
473e3aa18adSMartin Matuska 		if (pass_len < d_len) {
474e3aa18adSMartin Matuska 			ZSTDSTAT_BUMP(zstd_stat_lz4pass_allowed);
475e3aa18adSMartin Matuska 			goto keep_trying;
476e3aa18adSMartin Matuska 		}
477e3aa18adSMartin Matuska 		ZSTDSTAT_BUMP(zstd_stat_lz4pass_rejected);
478e3aa18adSMartin Matuska 
479e3aa18adSMartin Matuska 		pass_len = zfs_zstd_compress(s_start, d_start, s_len, d_len,
480e3aa18adSMartin Matuska 		    ZIO_ZSTD_LEVEL_1);
481e3aa18adSMartin Matuska 		if (pass_len == s_len || pass_len <= 0 || pass_len > d_len) {
482e3aa18adSMartin Matuska 			ZSTDSTAT_BUMP(zstd_stat_zstdpass_rejected);
483e3aa18adSMartin Matuska 			return (s_len);
484e3aa18adSMartin Matuska 		}
485e3aa18adSMartin Matuska 		ZSTDSTAT_BUMP(zstd_stat_zstdpass_allowed);
486e3aa18adSMartin Matuska 	} else {
487e3aa18adSMartin Matuska 		ZSTDSTAT_BUMP(zstd_stat_passignored);
488e3aa18adSMartin Matuska 		if (s_len < actual_abort_size) {
489e3aa18adSMartin Matuska 			ZSTDSTAT_BUMP(zstd_stat_passignored_size);
490e3aa18adSMartin Matuska 		}
491e3aa18adSMartin Matuska 	}
492e3aa18adSMartin Matuska keep_trying:
493e3aa18adSMartin Matuska 	return (zfs_zstd_compress(s_start, d_start, s_len, d_len, level));
494e3aa18adSMartin Matuska 
495e3aa18adSMartin Matuska }
49621b492edSMartin Matuska 
497eda14cbcSMatt Macy /* Compress block using zstd */
498eda14cbcSMatt Macy size_t
499eda14cbcSMatt Macy zfs_zstd_compress(void *s_start, void *d_start, size_t s_len, size_t d_len,
500eda14cbcSMatt Macy     int level)
501eda14cbcSMatt Macy {
502eda14cbcSMatt Macy 	size_t c_len;
503eda14cbcSMatt Macy 	int16_t zstd_level;
504eda14cbcSMatt Macy 	zfs_zstdhdr_t *hdr;
505eda14cbcSMatt Macy 	ZSTD_CCtx *cctx;
506eda14cbcSMatt Macy 
507eda14cbcSMatt Macy 	hdr = (zfs_zstdhdr_t *)d_start;
508eda14cbcSMatt Macy 
509eda14cbcSMatt Macy 	/* Skip compression if the specified level is invalid */
510eda14cbcSMatt Macy 	if (zstd_enum_to_level(level, &zstd_level)) {
511eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_com_inval);
512eda14cbcSMatt Macy 		return (s_len);
513eda14cbcSMatt Macy 	}
514eda14cbcSMatt Macy 
515eda14cbcSMatt Macy 	ASSERT3U(d_len, >=, sizeof (*hdr));
516eda14cbcSMatt Macy 	ASSERT3U(d_len, <=, s_len);
517eda14cbcSMatt Macy 	ASSERT3U(zstd_level, !=, 0);
518eda14cbcSMatt Macy 
519eda14cbcSMatt Macy 	cctx = ZSTD_createCCtx_advanced(zstd_malloc);
520eda14cbcSMatt Macy 
521eda14cbcSMatt Macy 	/*
522eda14cbcSMatt Macy 	 * Out of kernel memory, gently fall through - this will disable
523eda14cbcSMatt Macy 	 * compression in zio_compress_data
524eda14cbcSMatt Macy 	 */
525eda14cbcSMatt Macy 	if (!cctx) {
526eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_com_alloc_fail);
527eda14cbcSMatt Macy 		return (s_len);
528eda14cbcSMatt Macy 	}
529eda14cbcSMatt Macy 
530eda14cbcSMatt Macy 	/* Set the compression level */
531eda14cbcSMatt Macy 	ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, zstd_level);
532eda14cbcSMatt Macy 
533eda14cbcSMatt Macy 	/* Use the "magicless" zstd header which saves us 4 header bytes */
534eda14cbcSMatt Macy 	ZSTD_CCtx_setParameter(cctx, ZSTD_c_format, ZSTD_f_zstd1_magicless);
535eda14cbcSMatt Macy 
536eda14cbcSMatt Macy 	/*
537eda14cbcSMatt Macy 	 * Disable redundant checksum calculation and content size storage since
538eda14cbcSMatt Macy 	 * this is already done by ZFS itself.
539eda14cbcSMatt Macy 	 */
540eda14cbcSMatt Macy 	ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 0);
541eda14cbcSMatt Macy 	ZSTD_CCtx_setParameter(cctx, ZSTD_c_contentSizeFlag, 0);
542eda14cbcSMatt Macy 
543eda14cbcSMatt Macy 	c_len = ZSTD_compress2(cctx,
544eda14cbcSMatt Macy 	    hdr->data,
545eda14cbcSMatt Macy 	    d_len - sizeof (*hdr),
546eda14cbcSMatt Macy 	    s_start, s_len);
547eda14cbcSMatt Macy 
548eda14cbcSMatt Macy 	ZSTD_freeCCtx(cctx);
549eda14cbcSMatt Macy 
550eda14cbcSMatt Macy 	/* Error in the compression routine, disable compression. */
551eda14cbcSMatt Macy 	if (ZSTD_isError(c_len)) {
552eda14cbcSMatt Macy 		/*
553eda14cbcSMatt Macy 		 * If we are aborting the compression because the saves are
554eda14cbcSMatt Macy 		 * too small, that is not a failure. Everything else is a
555eda14cbcSMatt Macy 		 * failure, so increment the compression failure counter.
556eda14cbcSMatt Macy 		 */
557e3aa18adSMartin Matuska 		int err = ZSTD_getErrorCode(c_len);
558e3aa18adSMartin Matuska 		if (err != ZSTD_error_dstSize_tooSmall) {
559eda14cbcSMatt Macy 			ZSTDSTAT_BUMP(zstd_stat_com_fail);
560e3aa18adSMartin Matuska 			dprintf("Error: %s", ZSTD_getErrorString(err));
561eda14cbcSMatt Macy 		}
562eda14cbcSMatt Macy 		return (s_len);
563eda14cbcSMatt Macy 	}
564eda14cbcSMatt Macy 
565eda14cbcSMatt Macy 	/*
566eda14cbcSMatt Macy 	 * Encode the compressed buffer size at the start. We'll need this in
567eda14cbcSMatt Macy 	 * decompression to counter the effects of padding which might be added
568eda14cbcSMatt Macy 	 * to the compressed buffer and which, if unhandled, would confuse the
569eda14cbcSMatt Macy 	 * hell out of our decompression function.
570eda14cbcSMatt Macy 	 */
571eda14cbcSMatt Macy 	hdr->c_len = BE_32(c_len);
572eda14cbcSMatt Macy 
573eda14cbcSMatt Macy 	/*
574eda14cbcSMatt Macy 	 * Check version for overflow.
575eda14cbcSMatt Macy 	 * The limit of 24 bits must not be exceeded. This allows a maximum
576eda14cbcSMatt Macy 	 * version 1677.72.15 which we don't expect to be ever reached.
577eda14cbcSMatt Macy 	 */
578eda14cbcSMatt Macy 	ASSERT3U(ZSTD_VERSION_NUMBER, <=, 0xFFFFFF);
579eda14cbcSMatt Macy 
580eda14cbcSMatt Macy 	/*
581eda14cbcSMatt Macy 	 * Encode the compression level as well. We may need to know the
582eda14cbcSMatt Macy 	 * original compression level if compressed_arc is disabled, to match
583eda14cbcSMatt Macy 	 * the compression settings to write this block to the L2ARC.
584eda14cbcSMatt Macy 	 *
585eda14cbcSMatt Macy 	 * Encode the actual level, so if the enum changes in the future, we
586eda14cbcSMatt Macy 	 * will be compatible.
587eda14cbcSMatt Macy 	 *
588eda14cbcSMatt Macy 	 * The upper 24 bits store the ZSTD version to be able to provide
589eda14cbcSMatt Macy 	 * future compatibility, since new versions might enhance the
590eda14cbcSMatt Macy 	 * compression algorithm in a way, where the compressed data will
591eda14cbcSMatt Macy 	 * change.
592eda14cbcSMatt Macy 	 *
593eda14cbcSMatt Macy 	 * As soon as such incompatibility occurs, handling code needs to be
594eda14cbcSMatt Macy 	 * added, differentiating between the versions.
595eda14cbcSMatt Macy 	 */
59621b492edSMartin Matuska 	zfs_set_hdrversion(hdr, ZSTD_VERSION_NUMBER);
59721b492edSMartin Matuska 	zfs_set_hdrlevel(hdr, level);
598eda14cbcSMatt Macy 	hdr->raw_version_level = BE_32(hdr->raw_version_level);
599eda14cbcSMatt Macy 
600eda14cbcSMatt Macy 	return (c_len + sizeof (*hdr));
601eda14cbcSMatt Macy }
6024f0c9b76SWarner Losh #endif
603eda14cbcSMatt Macy 
604eda14cbcSMatt Macy /* Decompress block using zstd and return its stored level */
605eda14cbcSMatt Macy int
606eda14cbcSMatt Macy zfs_zstd_decompress_level(void *s_start, void *d_start, size_t s_len,
607eda14cbcSMatt Macy     size_t d_len, uint8_t *level)
608eda14cbcSMatt Macy {
609eda14cbcSMatt Macy 	ZSTD_DCtx *dctx;
610eda14cbcSMatt Macy 	size_t result;
611eda14cbcSMatt Macy 	int16_t zstd_level;
612eda14cbcSMatt Macy 	uint32_t c_len;
613eda14cbcSMatt Macy 	const zfs_zstdhdr_t *hdr;
614eda14cbcSMatt Macy 	zfs_zstdhdr_t hdr_copy;
615eda14cbcSMatt Macy 
616eda14cbcSMatt Macy 	hdr = (const zfs_zstdhdr_t *)s_start;
617eda14cbcSMatt Macy 	c_len = BE_32(hdr->c_len);
618eda14cbcSMatt Macy 
619eda14cbcSMatt Macy 	/*
620eda14cbcSMatt Macy 	 * Make a copy instead of directly converting the header, since we must
621eda14cbcSMatt Macy 	 * not modify the original data that may be used again later.
622eda14cbcSMatt Macy 	 */
623eda14cbcSMatt Macy 	hdr_copy.raw_version_level = BE_32(hdr->raw_version_level);
62421b492edSMartin Matuska 	uint8_t curlevel = zfs_get_hdrlevel(&hdr_copy);
625eda14cbcSMatt Macy 
626eda14cbcSMatt Macy 	/*
627eda14cbcSMatt Macy 	 * NOTE: We ignore the ZSTD version for now. As soon as any
62816038816SMartin Matuska 	 * incompatibility occurs, it has to be handled accordingly.
629eda14cbcSMatt Macy 	 * The version can be accessed via `hdr_copy.version`.
630eda14cbcSMatt Macy 	 */
631eda14cbcSMatt Macy 
632eda14cbcSMatt Macy 	/*
633eda14cbcSMatt Macy 	 * Convert and check the level
634eda14cbcSMatt Macy 	 * An invalid level is a strong indicator for data corruption! In such
635eda14cbcSMatt Macy 	 * case return an error so the upper layers can try to fix it.
636eda14cbcSMatt Macy 	 */
63721b492edSMartin Matuska 	if (zstd_enum_to_level(curlevel, &zstd_level)) {
638eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_dec_inval);
639eda14cbcSMatt Macy 		return (1);
640eda14cbcSMatt Macy 	}
641eda14cbcSMatt Macy 
642eda14cbcSMatt Macy 	ASSERT3U(d_len, >=, s_len);
64321b492edSMartin Matuska 	ASSERT3U(curlevel, !=, ZIO_COMPLEVEL_INHERIT);
644eda14cbcSMatt Macy 
645eda14cbcSMatt Macy 	/* Invalid compressed buffer size encoded at start */
646eda14cbcSMatt Macy 	if (c_len + sizeof (*hdr) > s_len) {
647eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_dec_header_inval);
648eda14cbcSMatt Macy 		return (1);
649eda14cbcSMatt Macy 	}
650eda14cbcSMatt Macy 
651eda14cbcSMatt Macy 	dctx = ZSTD_createDCtx_advanced(zstd_dctx_malloc);
652eda14cbcSMatt Macy 	if (!dctx) {
653eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_dec_alloc_fail);
654eda14cbcSMatt Macy 		return (1);
655eda14cbcSMatt Macy 	}
656eda14cbcSMatt Macy 
657eda14cbcSMatt Macy 	/* Set header type to "magicless" */
658eda14cbcSMatt Macy 	ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1_magicless);
659eda14cbcSMatt Macy 
660eda14cbcSMatt Macy 	/* Decompress the data and release the context */
661eda14cbcSMatt Macy 	result = ZSTD_decompressDCtx(dctx, d_start, d_len, hdr->data, c_len);
662eda14cbcSMatt Macy 	ZSTD_freeDCtx(dctx);
663eda14cbcSMatt Macy 
664eda14cbcSMatt Macy 	/*
665eda14cbcSMatt Macy 	 * Returns 0 on success (decompression function returned non-negative)
666eda14cbcSMatt Macy 	 * and non-zero on failure (decompression function returned negative.
667eda14cbcSMatt Macy 	 */
668eda14cbcSMatt Macy 	if (ZSTD_isError(result)) {
669eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_dec_fail);
670eda14cbcSMatt Macy 		return (1);
671eda14cbcSMatt Macy 	}
672eda14cbcSMatt Macy 
673eda14cbcSMatt Macy 	if (level) {
67421b492edSMartin Matuska 		*level = curlevel;
675eda14cbcSMatt Macy 	}
676eda14cbcSMatt Macy 
677eda14cbcSMatt Macy 	return (0);
678eda14cbcSMatt Macy }
679eda14cbcSMatt Macy 
680eda14cbcSMatt Macy /* Decompress datablock using zstd */
681eda14cbcSMatt Macy int
682eda14cbcSMatt Macy zfs_zstd_decompress(void *s_start, void *d_start, size_t s_len, size_t d_len,
683eda14cbcSMatt Macy     int level __maybe_unused)
684eda14cbcSMatt Macy {
685eda14cbcSMatt Macy 
686eda14cbcSMatt Macy 	return (zfs_zstd_decompress_level(s_start, d_start, s_len, d_len,
687eda14cbcSMatt Macy 	    NULL));
688eda14cbcSMatt Macy }
689eda14cbcSMatt Macy 
6904f0c9b76SWarner Losh #ifndef IN_LIBSA
691eda14cbcSMatt Macy /* Allocator for zstd compression context using mempool_allocator */
692eda14cbcSMatt Macy static void *
693eda14cbcSMatt Macy zstd_alloc(void *opaque __maybe_unused, size_t size)
694eda14cbcSMatt Macy {
695eda14cbcSMatt Macy 	size_t nbytes = sizeof (struct zstd_kmem) + size;
696eda14cbcSMatt Macy 	struct zstd_kmem *z = NULL;
697eda14cbcSMatt Macy 
698eda14cbcSMatt Macy 	z = (struct zstd_kmem *)zstd_mempool_alloc(zstd_mempool_cctx, nbytes);
699eda14cbcSMatt Macy 
700eda14cbcSMatt Macy 	if (!z) {
701eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_alloc_fail);
702eda14cbcSMatt Macy 		return (NULL);
703eda14cbcSMatt Macy 	}
704eda14cbcSMatt Macy 
705eda14cbcSMatt Macy 	return ((void*)z + (sizeof (struct zstd_kmem)));
706eda14cbcSMatt Macy }
7074f0c9b76SWarner Losh #endif
708eda14cbcSMatt Macy 
709eda14cbcSMatt Macy /*
710eda14cbcSMatt Macy  * Allocator for zstd decompression context using mempool_allocator with
711eda14cbcSMatt Macy  * fallback to reserved memory if allocation fails
712eda14cbcSMatt Macy  */
713eda14cbcSMatt Macy static void *
714eda14cbcSMatt Macy zstd_dctx_alloc(void *opaque __maybe_unused, size_t size)
715eda14cbcSMatt Macy {
716eda14cbcSMatt Macy 	size_t nbytes = sizeof (struct zstd_kmem) + size;
717eda14cbcSMatt Macy 	struct zstd_kmem *z = NULL;
718eda14cbcSMatt Macy 	enum zstd_kmem_type type = ZSTD_KMEM_DEFAULT;
719eda14cbcSMatt Macy 
720eda14cbcSMatt Macy 	z = (struct zstd_kmem *)zstd_mempool_alloc(zstd_mempool_dctx, nbytes);
721eda14cbcSMatt Macy 	if (!z) {
722eda14cbcSMatt Macy 		/* Try harder, decompression shall not fail */
723eda14cbcSMatt Macy 		z = vmem_alloc(nbytes, KM_SLEEP);
724eda14cbcSMatt Macy 		if (z) {
725eda14cbcSMatt Macy 			z->pool = NULL;
726eda14cbcSMatt Macy 		}
727eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_alloc_fail);
728eda14cbcSMatt Macy 	} else {
729eda14cbcSMatt Macy 		return ((void*)z + (sizeof (struct zstd_kmem)));
730eda14cbcSMatt Macy 	}
731eda14cbcSMatt Macy 
732eda14cbcSMatt Macy 	/* Fallback if everything fails */
733eda14cbcSMatt Macy 	if (!z) {
734eda14cbcSMatt Macy 		/*
735eda14cbcSMatt Macy 		 * Barrier since we only can handle it in a single thread. All
736eda14cbcSMatt Macy 		 * other following threads need to wait here until decompression
737eda14cbcSMatt Macy 		 * is completed. zstd_free will release this barrier later.
738eda14cbcSMatt Macy 		 */
739eda14cbcSMatt Macy 		mutex_enter(&zstd_dctx_fallback.barrier);
740eda14cbcSMatt Macy 
741eda14cbcSMatt Macy 		z = zstd_dctx_fallback.mem;
742eda14cbcSMatt Macy 		type = ZSTD_KMEM_DCTX;
743eda14cbcSMatt Macy 		ZSTDSTAT_BUMP(zstd_stat_alloc_fallback);
744eda14cbcSMatt Macy 	}
745eda14cbcSMatt Macy 
746eda14cbcSMatt Macy 	/* Allocation should always be successful */
747eda14cbcSMatt Macy 	if (!z) {
748eda14cbcSMatt Macy 		return (NULL);
749eda14cbcSMatt Macy 	}
750eda14cbcSMatt Macy 
751eda14cbcSMatt Macy 	z->kmem_type = type;
752eda14cbcSMatt Macy 	z->kmem_size = nbytes;
753eda14cbcSMatt Macy 
754eda14cbcSMatt Macy 	return ((void*)z + (sizeof (struct zstd_kmem)));
755eda14cbcSMatt Macy }
756eda14cbcSMatt Macy 
757eda14cbcSMatt Macy /* Free allocated memory by its specific type */
758eda14cbcSMatt Macy static void
759eda14cbcSMatt Macy zstd_free(void *opaque __maybe_unused, void *ptr)
760eda14cbcSMatt Macy {
761eda14cbcSMatt Macy 	struct zstd_kmem *z = (ptr - sizeof (struct zstd_kmem));
762eda14cbcSMatt Macy 	enum zstd_kmem_type type;
763eda14cbcSMatt Macy 
764eda14cbcSMatt Macy 	ASSERT3U(z->kmem_type, <, ZSTD_KMEM_COUNT);
765eda14cbcSMatt Macy 	ASSERT3U(z->kmem_type, >, ZSTD_KMEM_UNKNOWN);
766eda14cbcSMatt Macy 
767eda14cbcSMatt Macy 	type = z->kmem_type;
768eda14cbcSMatt Macy 	switch (type) {
769eda14cbcSMatt Macy 	case ZSTD_KMEM_DEFAULT:
770eda14cbcSMatt Macy 		vmem_free(z, z->kmem_size);
771eda14cbcSMatt Macy 		break;
772eda14cbcSMatt Macy 	case ZSTD_KMEM_POOL:
773eda14cbcSMatt Macy 		zstd_mempool_free(z);
774eda14cbcSMatt Macy 		break;
775eda14cbcSMatt Macy 	case ZSTD_KMEM_DCTX:
776eda14cbcSMatt Macy 		mutex_exit(&zstd_dctx_fallback.barrier);
777eda14cbcSMatt Macy 		break;
778eda14cbcSMatt Macy 	default:
779eda14cbcSMatt Macy 		break;
780eda14cbcSMatt Macy 	}
781eda14cbcSMatt Macy }
782eda14cbcSMatt Macy 
783eda14cbcSMatt Macy /* Allocate fallback memory to ensure safe decompression */
784eda14cbcSMatt Macy static void __init
785eda14cbcSMatt Macy create_fallback_mem(struct zstd_fallback_mem *mem, size_t size)
786eda14cbcSMatt Macy {
787eda14cbcSMatt Macy 	mem->mem_size = size;
788eda14cbcSMatt Macy 	mem->mem = vmem_zalloc(mem->mem_size, KM_SLEEP);
789eda14cbcSMatt Macy 	mutex_init(&mem->barrier, NULL, MUTEX_DEFAULT, NULL);
790eda14cbcSMatt Macy }
791eda14cbcSMatt Macy 
792eda14cbcSMatt Macy /* Initialize memory pool barrier mutexes */
793eda14cbcSMatt Macy static void __init
794eda14cbcSMatt Macy zstd_mempool_init(void)
795eda14cbcSMatt Macy {
796*15f0b8c3SMartin Matuska 	zstd_mempool_cctx =
797eda14cbcSMatt Macy 	    kmem_zalloc(ZSTD_POOL_MAX * sizeof (struct zstd_pool), KM_SLEEP);
798*15f0b8c3SMartin Matuska 	zstd_mempool_dctx =
799eda14cbcSMatt Macy 	    kmem_zalloc(ZSTD_POOL_MAX * sizeof (struct zstd_pool), KM_SLEEP);
800eda14cbcSMatt Macy 
801eda14cbcSMatt Macy 	for (int i = 0; i < ZSTD_POOL_MAX; i++) {
802eda14cbcSMatt Macy 		mutex_init(&zstd_mempool_cctx[i].barrier, NULL,
803eda14cbcSMatt Macy 		    MUTEX_DEFAULT, NULL);
804eda14cbcSMatt Macy 		mutex_init(&zstd_mempool_dctx[i].barrier, NULL,
805eda14cbcSMatt Macy 		    MUTEX_DEFAULT, NULL);
806eda14cbcSMatt Macy 	}
807eda14cbcSMatt Macy }
808eda14cbcSMatt Macy 
809eda14cbcSMatt Macy /* Initialize zstd-related memory handling */
810eda14cbcSMatt Macy static int __init
811eda14cbcSMatt Macy zstd_meminit(void)
812eda14cbcSMatt Macy {
813eda14cbcSMatt Macy 	zstd_mempool_init();
814eda14cbcSMatt Macy 
815eda14cbcSMatt Macy 	/*
816eda14cbcSMatt Macy 	 * Estimate the size of the fallback decompression context.
817eda14cbcSMatt Macy 	 * The expected size on x64 with current ZSTD should be about 160 KB.
818eda14cbcSMatt Macy 	 */
819eda14cbcSMatt Macy 	create_fallback_mem(&zstd_dctx_fallback,
820eda14cbcSMatt Macy 	    P2ROUNDUP(ZSTD_estimateDCtxSize() + sizeof (struct zstd_kmem),
821eda14cbcSMatt Macy 	    PAGESIZE));
822eda14cbcSMatt Macy 
823eda14cbcSMatt Macy 	return (0);
824eda14cbcSMatt Macy }
825eda14cbcSMatt Macy 
826eda14cbcSMatt Macy /* Release object from pool and free memory */
827716fd348SMartin Matuska static void
828eda14cbcSMatt Macy release_pool(struct zstd_pool *pool)
829eda14cbcSMatt Macy {
830eda14cbcSMatt Macy 	mutex_destroy(&pool->barrier);
831eda14cbcSMatt Macy 	vmem_free(pool->mem, pool->size);
832eda14cbcSMatt Macy 	pool->mem = NULL;
833eda14cbcSMatt Macy 	pool->size = 0;
834eda14cbcSMatt Macy }
835eda14cbcSMatt Macy 
836eda14cbcSMatt Macy /* Release memory pool objects */
837716fd348SMartin Matuska static void
838eda14cbcSMatt Macy zstd_mempool_deinit(void)
839eda14cbcSMatt Macy {
840eda14cbcSMatt Macy 	for (int i = 0; i < ZSTD_POOL_MAX; i++) {
841eda14cbcSMatt Macy 		release_pool(&zstd_mempool_cctx[i]);
842eda14cbcSMatt Macy 		release_pool(&zstd_mempool_dctx[i]);
843eda14cbcSMatt Macy 	}
844eda14cbcSMatt Macy 
845eda14cbcSMatt Macy 	kmem_free(zstd_mempool_dctx, ZSTD_POOL_MAX * sizeof (struct zstd_pool));
846eda14cbcSMatt Macy 	kmem_free(zstd_mempool_cctx, ZSTD_POOL_MAX * sizeof (struct zstd_pool));
847eda14cbcSMatt Macy 	zstd_mempool_dctx = NULL;
848eda14cbcSMatt Macy 	zstd_mempool_cctx = NULL;
849eda14cbcSMatt Macy }
850eda14cbcSMatt Macy 
851c40487d4SMatt Macy /* release unused memory from pool */
852c40487d4SMatt Macy 
853c40487d4SMatt Macy void
854c40487d4SMatt Macy zfs_zstd_cache_reap_now(void)
855c40487d4SMatt Macy {
85636639c39SMateusz Guzik 
85736639c39SMateusz Guzik 	/*
85836639c39SMateusz Guzik 	 * Short-circuit if there are no buffers to begin with.
85936639c39SMateusz Guzik 	 */
86036639c39SMateusz Guzik 	if (ZSTDSTAT(zstd_stat_buffers) == 0)
86136639c39SMateusz Guzik 		return;
86236639c39SMateusz Guzik 
863c40487d4SMatt Macy 	/*
864c40487d4SMatt Macy 	 * calling alloc with zero size seeks
865c40487d4SMatt Macy 	 * and releases old unused objects
866c40487d4SMatt Macy 	 */
8677877fdebSMatt Macy 	zstd_mempool_reap(zstd_mempool_cctx);
8687877fdebSMatt Macy 	zstd_mempool_reap(zstd_mempool_dctx);
869c40487d4SMatt Macy }
870c40487d4SMatt Macy 
871eda14cbcSMatt Macy extern int __init
872eda14cbcSMatt Macy zstd_init(void)
873eda14cbcSMatt Macy {
874eda14cbcSMatt Macy 	/* Set pool size by using maximum sane thread count * 4 */
875eda14cbcSMatt Macy 	pool_count = (boot_ncpus * 4);
876eda14cbcSMatt Macy 	zstd_meminit();
877eda14cbcSMatt Macy 
878eda14cbcSMatt Macy 	/* Initialize kstat */
879eda14cbcSMatt Macy 	zstd_ksp = kstat_create("zfs", 0, "zstd", "misc",
880eda14cbcSMatt Macy 	    KSTAT_TYPE_NAMED, sizeof (zstd_stats) / sizeof (kstat_named_t),
881eda14cbcSMatt Macy 	    KSTAT_FLAG_VIRTUAL);
882eda14cbcSMatt Macy 	if (zstd_ksp != NULL) {
883eda14cbcSMatt Macy 		zstd_ksp->ks_data = &zstd_stats;
884eda14cbcSMatt Macy 		kstat_install(zstd_ksp);
885e3aa18adSMartin Matuska #ifdef _KERNEL
886e3aa18adSMartin Matuska 		zstd_ksp->ks_update = kstat_zstd_update;
887e3aa18adSMartin Matuska #endif
888eda14cbcSMatt Macy 	}
889eda14cbcSMatt Macy 
890eda14cbcSMatt Macy 	return (0);
891eda14cbcSMatt Macy }
892eda14cbcSMatt Macy 
893716fd348SMartin Matuska extern void
894eda14cbcSMatt Macy zstd_fini(void)
895eda14cbcSMatt Macy {
896eda14cbcSMatt Macy 	/* Deinitialize kstat */
897eda14cbcSMatt Macy 	if (zstd_ksp != NULL) {
898eda14cbcSMatt Macy 		kstat_delete(zstd_ksp);
899eda14cbcSMatt Macy 		zstd_ksp = NULL;
900eda14cbcSMatt Macy 	}
901eda14cbcSMatt Macy 
902eda14cbcSMatt Macy 	/* Release fallback memory */
903eda14cbcSMatt Macy 	vmem_free(zstd_dctx_fallback.mem, zstd_dctx_fallback.mem_size);
904eda14cbcSMatt Macy 	mutex_destroy(&zstd_dctx_fallback.barrier);
905eda14cbcSMatt Macy 
906eda14cbcSMatt Macy 	/* Deinit memory pool */
907eda14cbcSMatt Macy 	zstd_mempool_deinit();
908eda14cbcSMatt Macy }
909eda14cbcSMatt Macy 
910eda14cbcSMatt Macy #if defined(_KERNEL)
911716fd348SMartin Matuska #ifdef __FreeBSD__
912eda14cbcSMatt Macy module_init(zstd_init);
913eda14cbcSMatt Macy module_exit(zstd_fini);
914716fd348SMartin Matuska #endif
915eda14cbcSMatt Macy 
916be181ee2SMartin Matuska ZFS_MODULE_PARAM(zfs, zstd_, earlyabort_pass, UINT, ZMOD_RW,
917e3aa18adSMartin Matuska 	"Enable early abort attempts when using zstd");
918e3aa18adSMartin Matuska ZFS_MODULE_PARAM(zfs, zstd_, abort_size, UINT, ZMOD_RW,
919e3aa18adSMartin Matuska 	"Minimal size of block to attempt early abort");
920eda14cbcSMatt Macy #endif
921