xref: /freebsd/sys/contrib/openzfs/module/zcommon/zfs_fletcher.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
14  * Use is subject to license terms.
15  * Copyright (C) 2016 Gvozden Nešković. All rights reserved.
16  */
17 /*
18  * Copyright 2013 Saso Kiselkov. All rights reserved.
19  */
20 
21 /*
22  * Copyright (c) 2016 by Delphix. All rights reserved.
23  */
24 
25 /*
26  * Fletcher Checksums
27  * ------------------
28  *
29  * ZFS's 2nd and 4th order Fletcher checksums are defined by the following
30  * recurrence relations:
31  *
32  *	a  = a    + f
33  *	 i    i-1    i-1
34  *
35  *	b  = b    + a
36  *	 i    i-1    i
37  *
38  *	c  = c    + b		(fletcher-4 only)
39  *	 i    i-1    i
40  *
41  *	d  = d    + c		(fletcher-4 only)
42  *	 i    i-1    i
43  *
44  * Where
45  *	a_0 = b_0 = c_0 = d_0 = 0
46  * and
47  *	f_0 .. f_(n-1) are the input data.
48  *
49  * Using standard techniques, these translate into the following series:
50  *
51  *	     __n_			     __n_
52  *	     \   |			     \   |
53  *	a  =  >     f			b  =  >     i * f
54  *	 n   /___|   n - i		 n   /___|	 n - i
55  *	     i = 1			     i = 1
56  *
57  *
58  *	     __n_			     __n_
59  *	     \   |  i*(i+1)		     \   |  i*(i+1)*(i+2)
60  *	c  =  >     ------- f		d  =  >     ------------- f
61  *	 n   /___|     2     n - i	 n   /___|	  6	   n - i
62  *	     i = 1			     i = 1
63  *
64  * For fletcher-2, the f_is are 64-bit, and [ab]_i are 64-bit accumulators.
65  * Since the additions are done mod (2^64), errors in the high bits may not
66  * be noticed.  For this reason, fletcher-2 is deprecated.
67  *
68  * For fletcher-4, the f_is are 32-bit, and [abcd]_i are 64-bit accumulators.
69  * A conservative estimate of how big the buffer can get before we overflow
70  * can be estimated using f_i = 0xffffffff for all i:
71  *
72  * % bc
73  *  f=2^32-1;d=0; for (i = 1; d<2^64; i++) { d += f*i*(i+1)*(i+2)/6 }; (i-1)*4
74  * 2264
75  *  quit
76  * %
77  *
78  * So blocks of up to 2k will not overflow.  Our largest block size is
79  * 128k, which has 32k 4-byte words, so we can compute the largest possible
80  * accumulators, then divide by 2^64 to figure the max amount of overflow:
81  *
82  * % bc
83  *  a=b=c=d=0; f=2^32-1; for (i=1; i<=32*1024; i++) { a+=f; b+=a; c+=b; d+=c }
84  *  a/2^64;b/2^64;c/2^64;d/2^64
85  * 0
86  * 0
87  * 1365
88  * 11186858
89  *  quit
90  * %
91  *
92  * So a and b cannot overflow.  To make sure each bit of input has some
93  * effect on the contents of c and d, we can look at what the factors of
94  * the coefficients in the equations for c_n and d_n are.  The number of 2s
95  * in the factors determines the lowest set bit in the multiplier.  Running
96  * through the cases for n*(n+1)/2 reveals that the highest power of 2 is
97  * 2^14, and for n*(n+1)*(n+2)/6 it is 2^15.  So while some data may overflow
98  * the 64-bit accumulators, every bit of every f_i effects every accumulator,
99  * even for 128k blocks.
100  *
101  * If we wanted to make a stronger version of fletcher4 (fletcher4c?),
102  * we could do our calculations mod (2^32 - 1) by adding in the carries
103  * periodically, and store the number of carries in the top 32-bits.
104  *
105  * --------------------
106  * Checksum Performance
107  * --------------------
108  *
109  * There are two interesting components to checksum performance: cached and
110  * uncached performance.  With cached data, fletcher-2 is about four times
111  * faster than fletcher-4.  With uncached data, the performance difference is
112  * negligible, since the cost of a cache fill dominates the processing time.
113  * Even though fletcher-4 is slower than fletcher-2, it is still a pretty
114  * efficient pass over the data.
115  *
116  * In normal operation, the data which is being checksummed is in a buffer
117  * which has been filled either by:
118  *
119  *	1. a compression step, which will be mostly cached, or
120  *	2. a memcpy() or copyin(), which will be uncached
121  *	   (because the copy is cache-bypassing).
122  *
123  * For both cached and uncached data, both fletcher checksums are much faster
124  * than sha-256, and slower than 'off', which doesn't touch the data at all.
125  */
126 
127 #include <sys/types.h>
128 #include <sys/sysmacros.h>
129 #include <sys/byteorder.h>
130 #include <sys/simd.h>
131 #include <sys/spa.h>
132 #include <sys/zio_checksum.h>
133 #include <sys/zfs_context.h>
134 #include <zfs_fletcher.h>
135 
136 #define	FLETCHER_MIN_SIMD_SIZE	64
137 
138 static void fletcher_4_scalar_init(fletcher_4_ctx_t *ctx);
139 static void fletcher_4_scalar_fini(fletcher_4_ctx_t *ctx, zio_cksum_t *zcp);
140 static void fletcher_4_scalar_native(fletcher_4_ctx_t *ctx,
141     const void *buf, uint64_t size);
142 static void fletcher_4_scalar_byteswap(fletcher_4_ctx_t *ctx,
143     const void *buf, uint64_t size);
144 static boolean_t fletcher_4_scalar_valid(void);
145 
146 static const fletcher_4_ops_t fletcher_4_scalar_ops = {
147 	.init_native = fletcher_4_scalar_init,
148 	.fini_native = fletcher_4_scalar_fini,
149 	.compute_native = fletcher_4_scalar_native,
150 	.init_byteswap = fletcher_4_scalar_init,
151 	.fini_byteswap = fletcher_4_scalar_fini,
152 	.compute_byteswap = fletcher_4_scalar_byteswap,
153 	.valid = fletcher_4_scalar_valid,
154 	.uses_fpu = B_FALSE,
155 	.name = "scalar"
156 };
157 
158 static fletcher_4_ops_t fletcher_4_fastest_impl = {
159 	.name = "fastest",
160 	.valid = fletcher_4_scalar_valid
161 };
162 
163 static const fletcher_4_ops_t *fletcher_4_impls[] = {
164 	&fletcher_4_scalar_ops,
165 	&fletcher_4_superscalar_ops,
166 	&fletcher_4_superscalar4_ops,
167 #if HAVE_SIMD(SSE2)
168 	&fletcher_4_sse2_ops,
169 #endif
170 #if HAVE_SIMD(SSE2) && HAVE_SIMD(SSSE3)
171 	&fletcher_4_ssse3_ops,
172 #endif
173 #if HAVE_SIMD(AVX) && HAVE_SIMD(AVX2)
174 	&fletcher_4_avx2_ops,
175 #endif
176 #if defined(__x86_64) && HAVE_SIMD(AVX512F)
177 	&fletcher_4_avx512f_ops,
178 #endif
179 #if defined(__x86_64) && HAVE_SIMD(AVX512BW)
180 	&fletcher_4_avx512bw_ops,
181 #endif
182 #if defined(__aarch64__) && !defined(__FreeBSD__)
183 	&fletcher_4_aarch64_neon_ops,
184 #endif
185 };
186 
187 /* Hold all supported implementations */
188 static uint32_t fletcher_4_supp_impls_cnt = 0;
189 static fletcher_4_ops_t *fletcher_4_supp_impls[ARRAY_SIZE(fletcher_4_impls)];
190 
191 /* Select fletcher4 implementation */
192 #define	IMPL_FASTEST	(UINT32_MAX)
193 #define	IMPL_CYCLE	(UINT32_MAX - 1)
194 #define	IMPL_SCALAR	(0)
195 
196 static uint32_t fletcher_4_impl_chosen = IMPL_FASTEST;
197 
198 #define	IMPL_READ(i)	(*(volatile uint32_t *) &(i))
199 
200 static struct fletcher_4_impl_selector {
201 	const char	*fis_name;
202 	uint32_t	fis_sel;
203 } fletcher_4_impl_selectors[] = {
204 	{ "cycle",	IMPL_CYCLE },
205 	{ "fastest",	IMPL_FASTEST },
206 	{ "scalar",	IMPL_SCALAR }
207 };
208 
209 #if defined(_KERNEL)
210 static kstat_t *fletcher_4_kstat;
211 
212 static struct fletcher_4_kstat {
213 	uint64_t native;
214 	uint64_t byteswap;
215 } fletcher_4_stat_data[ARRAY_SIZE(fletcher_4_impls) + 1];
216 #endif
217 
218 /* Indicate that benchmark has been completed */
219 static boolean_t fletcher_4_initialized = B_FALSE;
220 
221 void
fletcher_init(zio_cksum_t * zcp)222 fletcher_init(zio_cksum_t *zcp)
223 {
224 	ZIO_SET_CHECKSUM(zcp, 0, 0, 0, 0);
225 }
226 
227 int
fletcher_2_incremental_native(void * buf,size_t size,void * data)228 fletcher_2_incremental_native(void *buf, size_t size, void *data)
229 {
230 	zio_cksum_t *zcp = data;
231 
232 	const uint64_t *ip = buf;
233 	const uint64_t *ipend = ip + (size / sizeof (uint64_t));
234 	uint64_t a0, b0, a1, b1;
235 
236 	a0 = zcp->zc_word[0];
237 	a1 = zcp->zc_word[1];
238 	b0 = zcp->zc_word[2];
239 	b1 = zcp->zc_word[3];
240 
241 	for (; ip < ipend; ip += 2) {
242 		a0 += ip[0];
243 		a1 += ip[1];
244 		b0 += a0;
245 		b1 += a1;
246 	}
247 
248 	ZIO_SET_CHECKSUM(zcp, a0, a1, b0, b1);
249 	return (0);
250 }
251 
252 void
fletcher_2_native(const void * buf,uint64_t size,const void * ctx_template,zio_cksum_t * zcp)253 fletcher_2_native(const void *buf, uint64_t size,
254     const void *ctx_template, zio_cksum_t *zcp)
255 {
256 	(void) ctx_template;
257 	fletcher_init(zcp);
258 	(void) fletcher_2_incremental_native((void *) buf, size, zcp);
259 }
260 
261 int
fletcher_2_incremental_byteswap(void * buf,size_t size,void * data)262 fletcher_2_incremental_byteswap(void *buf, size_t size, void *data)
263 {
264 	zio_cksum_t *zcp = data;
265 
266 	const uint64_t *ip = buf;
267 	const uint64_t *ipend = ip + (size / sizeof (uint64_t));
268 	uint64_t a0, b0, a1, b1;
269 
270 	a0 = zcp->zc_word[0];
271 	a1 = zcp->zc_word[1];
272 	b0 = zcp->zc_word[2];
273 	b1 = zcp->zc_word[3];
274 
275 	for (; ip < ipend; ip += 2) {
276 		a0 += BSWAP_64(ip[0]);
277 		a1 += BSWAP_64(ip[1]);
278 		b0 += a0;
279 		b1 += a1;
280 	}
281 
282 	ZIO_SET_CHECKSUM(zcp, a0, a1, b0, b1);
283 	return (0);
284 }
285 
286 void
fletcher_2_byteswap(const void * buf,uint64_t size,const void * ctx_template,zio_cksum_t * zcp)287 fletcher_2_byteswap(const void *buf, uint64_t size,
288     const void *ctx_template, zio_cksum_t *zcp)
289 {
290 	(void) ctx_template;
291 	fletcher_init(zcp);
292 	(void) fletcher_2_incremental_byteswap((void *) buf, size, zcp);
293 }
294 
295 static void
fletcher_4_scalar_init(fletcher_4_ctx_t * ctx)296 fletcher_4_scalar_init(fletcher_4_ctx_t *ctx)
297 {
298 	ZIO_SET_CHECKSUM(&ctx->scalar, 0, 0, 0, 0);
299 }
300 
301 static void
fletcher_4_scalar_fini(fletcher_4_ctx_t * ctx,zio_cksum_t * zcp)302 fletcher_4_scalar_fini(fletcher_4_ctx_t *ctx, zio_cksum_t *zcp)
303 {
304 	memcpy(zcp, &ctx->scalar, sizeof (zio_cksum_t));
305 }
306 
307 static void
fletcher_4_scalar_native(fletcher_4_ctx_t * ctx,const void * buf,uint64_t size)308 fletcher_4_scalar_native(fletcher_4_ctx_t *ctx, const void *buf,
309     uint64_t size)
310 {
311 	const uint32_t *ip = buf;
312 	const uint32_t *ipend = ip + (size / sizeof (uint32_t));
313 	uint64_t a, b, c, d;
314 
315 	a = ctx->scalar.zc_word[0];
316 	b = ctx->scalar.zc_word[1];
317 	c = ctx->scalar.zc_word[2];
318 	d = ctx->scalar.zc_word[3];
319 
320 	for (; ip < ipend; ip++) {
321 		a += ip[0];
322 		b += a;
323 		c += b;
324 		d += c;
325 	}
326 
327 	ZIO_SET_CHECKSUM(&ctx->scalar, a, b, c, d);
328 }
329 
330 static void
fletcher_4_scalar_byteswap(fletcher_4_ctx_t * ctx,const void * buf,uint64_t size)331 fletcher_4_scalar_byteswap(fletcher_4_ctx_t *ctx, const void *buf,
332     uint64_t size)
333 {
334 	const uint32_t *ip = buf;
335 	const uint32_t *ipend = ip + (size / sizeof (uint32_t));
336 	uint64_t a, b, c, d;
337 
338 	a = ctx->scalar.zc_word[0];
339 	b = ctx->scalar.zc_word[1];
340 	c = ctx->scalar.zc_word[2];
341 	d = ctx->scalar.zc_word[3];
342 
343 	for (; ip < ipend; ip++) {
344 		a += BSWAP_32(ip[0]);
345 		b += a;
346 		c += b;
347 		d += c;
348 	}
349 
350 	ZIO_SET_CHECKSUM(&ctx->scalar, a, b, c, d);
351 }
352 
353 static boolean_t
fletcher_4_scalar_valid(void)354 fletcher_4_scalar_valid(void)
355 {
356 	return (B_TRUE);
357 }
358 
359 int
fletcher_4_impl_set(const char * val)360 fletcher_4_impl_set(const char *val)
361 {
362 	int err = -EINVAL;
363 	uint32_t impl = IMPL_READ(fletcher_4_impl_chosen);
364 	size_t i, val_len;
365 
366 	val_len = strlen(val);
367 	while ((val_len > 0) && !!isspace(val[val_len-1])) /* trim '\n' */
368 		val_len--;
369 
370 	/* check mandatory implementations */
371 	for (i = 0; i < ARRAY_SIZE(fletcher_4_impl_selectors); i++) {
372 		const char *name = fletcher_4_impl_selectors[i].fis_name;
373 
374 		if (val_len == strlen(name) &&
375 		    strncmp(val, name, val_len) == 0) {
376 			impl = fletcher_4_impl_selectors[i].fis_sel;
377 			err = 0;
378 			break;
379 		}
380 	}
381 
382 	if (err != 0 && fletcher_4_initialized) {
383 		/* check all supported implementations */
384 		for (i = 0; i < fletcher_4_supp_impls_cnt; i++) {
385 			const char *name = fletcher_4_supp_impls[i]->name;
386 
387 			if (val_len == strlen(name) &&
388 			    strncmp(val, name, val_len) == 0) {
389 				impl = i;
390 				err = 0;
391 				break;
392 			}
393 		}
394 	}
395 
396 	if (err == 0) {
397 		atomic_swap_32(&fletcher_4_impl_chosen, impl);
398 		membar_producer();
399 	}
400 
401 	return (err);
402 }
403 
404 /*
405  * Returns the Fletcher 4 operations for checksums.   When a SIMD
406  * implementation is not allowed in the current context, then fallback
407  * to the fastest generic implementation.
408  */
409 static inline const fletcher_4_ops_t *
fletcher_4_impl_get(void)410 fletcher_4_impl_get(void)
411 {
412 	if (!kfpu_allowed())
413 		return (&fletcher_4_superscalar4_ops);
414 
415 	const fletcher_4_ops_t *ops = NULL;
416 	uint32_t impl = IMPL_READ(fletcher_4_impl_chosen);
417 
418 	switch (impl) {
419 	case IMPL_FASTEST:
420 		ASSERT(fletcher_4_initialized);
421 		ops = &fletcher_4_fastest_impl;
422 		break;
423 	case IMPL_CYCLE:
424 		/* Cycle through supported implementations */
425 		ASSERT(fletcher_4_initialized);
426 		ASSERT3U(fletcher_4_supp_impls_cnt, >, 0);
427 		static uint32_t cycle_count = 0;
428 		uint32_t idx = (++cycle_count) % fletcher_4_supp_impls_cnt;
429 		ops = fletcher_4_supp_impls[idx];
430 		break;
431 	default:
432 		ASSERT3U(fletcher_4_supp_impls_cnt, >, 0);
433 		ASSERT3U(impl, <, fletcher_4_supp_impls_cnt);
434 		ops = fletcher_4_supp_impls[impl];
435 		break;
436 	}
437 
438 	ASSERT3P(ops, !=, NULL);
439 
440 	return (ops);
441 }
442 
443 static inline void
fletcher_4_native_impl(const void * buf,uint64_t size,zio_cksum_t * zcp)444 fletcher_4_native_impl(const void *buf, uint64_t size, zio_cksum_t *zcp)
445 {
446 	fletcher_4_ctx_t ctx;
447 	const fletcher_4_ops_t *ops = fletcher_4_impl_get();
448 
449 	if (ops->uses_fpu == B_TRUE) {
450 		kfpu_begin();
451 	}
452 	ops->init_native(&ctx);
453 	ops->compute_native(&ctx, buf, size);
454 	ops->fini_native(&ctx, zcp);
455 	if (ops->uses_fpu == B_TRUE) {
456 		kfpu_end();
457 	}
458 }
459 
460 void
fletcher_4_native(const void * buf,uint64_t size,const void * ctx_template,zio_cksum_t * zcp)461 fletcher_4_native(const void *buf, uint64_t size,
462     const void *ctx_template, zio_cksum_t *zcp)
463 {
464 	(void) ctx_template;
465 	const uint64_t p2size = P2ALIGN_TYPED(size, FLETCHER_MIN_SIMD_SIZE,
466 	    uint64_t);
467 
468 	ASSERT(IS_P2ALIGNED(size, sizeof (uint32_t)));
469 
470 	if (size == 0 || p2size == 0) {
471 		ZIO_SET_CHECKSUM(zcp, 0, 0, 0, 0);
472 
473 		if (size > 0)
474 			fletcher_4_scalar_native((fletcher_4_ctx_t *)zcp,
475 			    buf, size);
476 	} else {
477 		fletcher_4_native_impl(buf, p2size, zcp);
478 
479 		if (p2size < size)
480 			fletcher_4_scalar_native((fletcher_4_ctx_t *)zcp,
481 			    (char *)buf + p2size, size - p2size);
482 	}
483 }
484 
485 void
fletcher_4_native_varsize(const void * buf,uint64_t size,zio_cksum_t * zcp)486 fletcher_4_native_varsize(const void *buf, uint64_t size, zio_cksum_t *zcp)
487 {
488 	ZIO_SET_CHECKSUM(zcp, 0, 0, 0, 0);
489 	fletcher_4_scalar_native((fletcher_4_ctx_t *)zcp, buf, size);
490 }
491 
492 void
fletcher_4_byteswap_varsize(const void * buf,uint64_t size,zio_cksum_t * zcp)493 fletcher_4_byteswap_varsize(const void *buf, uint64_t size, zio_cksum_t *zcp)
494 {
495 	ZIO_SET_CHECKSUM(zcp, 0, 0, 0, 0);
496 	fletcher_4_scalar_byteswap((fletcher_4_ctx_t *)zcp, buf, size);
497 }
498 
499 static inline void
fletcher_4_byteswap_impl(const void * buf,uint64_t size,zio_cksum_t * zcp)500 fletcher_4_byteswap_impl(const void *buf, uint64_t size, zio_cksum_t *zcp)
501 {
502 	fletcher_4_ctx_t ctx;
503 	const fletcher_4_ops_t *ops = fletcher_4_impl_get();
504 
505 	if (ops->uses_fpu == B_TRUE) {
506 		kfpu_begin();
507 	}
508 	ops->init_byteswap(&ctx);
509 	ops->compute_byteswap(&ctx, buf, size);
510 	ops->fini_byteswap(&ctx, zcp);
511 	if (ops->uses_fpu == B_TRUE) {
512 		kfpu_end();
513 	}
514 }
515 
516 void
fletcher_4_byteswap(const void * buf,uint64_t size,const void * ctx_template,zio_cksum_t * zcp)517 fletcher_4_byteswap(const void *buf, uint64_t size,
518     const void *ctx_template, zio_cksum_t *zcp)
519 {
520 	(void) ctx_template;
521 	const uint64_t p2size = P2ALIGN_TYPED(size, FLETCHER_MIN_SIMD_SIZE,
522 	    uint64_t);
523 
524 	ASSERT(IS_P2ALIGNED(size, sizeof (uint32_t)));
525 
526 	if (size == 0 || p2size == 0) {
527 		ZIO_SET_CHECKSUM(zcp, 0, 0, 0, 0);
528 
529 		if (size > 0)
530 			fletcher_4_scalar_byteswap((fletcher_4_ctx_t *)zcp,
531 			    buf, size);
532 	} else {
533 		fletcher_4_byteswap_impl(buf, p2size, zcp);
534 
535 		if (p2size < size)
536 			fletcher_4_scalar_byteswap((fletcher_4_ctx_t *)zcp,
537 			    (char *)buf + p2size, size - p2size);
538 	}
539 }
540 
541 /* Incremental Fletcher 4 */
542 
543 #define	ZFS_FLETCHER_4_INC_MAX_SIZE	(8ULL << 20)
544 
545 static inline void
fletcher_4_incremental_combine(zio_cksum_t * zcp,const uint64_t size,const zio_cksum_t * nzcp)546 fletcher_4_incremental_combine(zio_cksum_t *zcp, const uint64_t size,
547     const zio_cksum_t *nzcp)
548 {
549 	const uint64_t c1 = size / sizeof (uint32_t);
550 	const uint64_t c2 = c1 * (c1 + 1) / 2;
551 	const uint64_t c3 = c2 * (c1 + 2) / 3;
552 
553 	/*
554 	 * Value of 'c3' overflows on buffer sizes close to 16MiB. For that
555 	 * reason we split incremental fletcher4 computation of large buffers
556 	 * to steps of (ZFS_FLETCHER_4_INC_MAX_SIZE) size.
557 	 */
558 	ASSERT3U(size, <=, ZFS_FLETCHER_4_INC_MAX_SIZE);
559 
560 	zcp->zc_word[3] += nzcp->zc_word[3] + c1 * zcp->zc_word[2] +
561 	    c2 * zcp->zc_word[1] + c3 * zcp->zc_word[0];
562 	zcp->zc_word[2] += nzcp->zc_word[2] + c1 * zcp->zc_word[1] +
563 	    c2 * zcp->zc_word[0];
564 	zcp->zc_word[1] += nzcp->zc_word[1] + c1 * zcp->zc_word[0];
565 	zcp->zc_word[0] += nzcp->zc_word[0];
566 }
567 
568 static inline void
fletcher_4_incremental_impl(boolean_t native,const void * buf,uint64_t size,zio_cksum_t * zcp)569 fletcher_4_incremental_impl(boolean_t native, const void *buf, uint64_t size,
570     zio_cksum_t *zcp)
571 {
572 	while (size > 0) {
573 		zio_cksum_t nzc;
574 		uint64_t len = MIN(size, ZFS_FLETCHER_4_INC_MAX_SIZE);
575 
576 		if (native)
577 			fletcher_4_native(buf, len, NULL, &nzc);
578 		else
579 			fletcher_4_byteswap(buf, len, NULL, &nzc);
580 
581 		fletcher_4_incremental_combine(zcp, len, &nzc);
582 
583 		size -= len;
584 		buf += len;
585 	}
586 }
587 
588 int
fletcher_4_incremental_native(void * buf,size_t size,void * data)589 fletcher_4_incremental_native(void *buf, size_t size, void *data)
590 {
591 	zio_cksum_t *zcp = data;
592 	/* Use scalar impl to directly update cksum of small blocks */
593 	if (size < SPA_MINBLOCKSIZE)
594 		fletcher_4_scalar_native((fletcher_4_ctx_t *)zcp, buf, size);
595 	else
596 		fletcher_4_incremental_impl(B_TRUE, buf, size, zcp);
597 	return (0);
598 }
599 
600 int
fletcher_4_incremental_byteswap(void * buf,size_t size,void * data)601 fletcher_4_incremental_byteswap(void *buf, size_t size, void *data)
602 {
603 	zio_cksum_t *zcp = data;
604 	/* Use scalar impl to directly update cksum of small blocks */
605 	if (size < SPA_MINBLOCKSIZE)
606 		fletcher_4_scalar_byteswap((fletcher_4_ctx_t *)zcp, buf, size);
607 	else
608 		fletcher_4_incremental_impl(B_FALSE, buf, size, zcp);
609 	return (0);
610 }
611 
612 #if defined(_KERNEL)
613 /*
614  * Fletcher 4 kstats
615  */
616 static int
fletcher_4_kstat_headers(char * buf,size_t size)617 fletcher_4_kstat_headers(char *buf, size_t size)
618 {
619 	ssize_t off = 0;
620 
621 	off += snprintf(buf + off, size, "%-17s", "implementation");
622 	off += snprintf(buf + off, size - off, "%-15s", "native");
623 	(void) snprintf(buf + off, size - off, "%-15s\n", "byteswap");
624 
625 	return (0);
626 }
627 
628 static int
fletcher_4_kstat_data(char * buf,size_t size,void * data)629 fletcher_4_kstat_data(char *buf, size_t size, void *data)
630 {
631 	struct fletcher_4_kstat *fastest_stat =
632 	    &fletcher_4_stat_data[fletcher_4_supp_impls_cnt];
633 	struct fletcher_4_kstat *curr_stat = (struct fletcher_4_kstat *)data;
634 	ssize_t off = 0;
635 
636 	if (curr_stat == fastest_stat) {
637 		off += snprintf(buf + off, size - off, "%-17s", "fastest");
638 		off += snprintf(buf + off, size - off, "%-15s",
639 		    fletcher_4_supp_impls[fastest_stat->native]->name);
640 		(void) snprintf(buf + off, size - off, "%-15s\n",
641 		    fletcher_4_supp_impls[fastest_stat->byteswap]->name);
642 	} else {
643 		ptrdiff_t id = curr_stat - fletcher_4_stat_data;
644 
645 		off += snprintf(buf + off, size - off, "%-17s",
646 		    fletcher_4_supp_impls[id]->name);
647 		off += snprintf(buf + off, size - off, "%-15llu",
648 		    (u_longlong_t)curr_stat->native);
649 		(void) snprintf(buf + off, size - off, "%-15llu\n",
650 		    (u_longlong_t)curr_stat->byteswap);
651 	}
652 
653 	return (0);
654 }
655 
656 static void *
fletcher_4_kstat_addr(kstat_t * ksp,loff_t n)657 fletcher_4_kstat_addr(kstat_t *ksp, loff_t n)
658 {
659 	if (n <= fletcher_4_supp_impls_cnt)
660 		ksp->ks_private = (void *) (fletcher_4_stat_data + n);
661 	else
662 		ksp->ks_private = NULL;
663 
664 	return (ksp->ks_private);
665 }
666 #endif
667 
668 #define	FLETCHER_4_FASTEST_FN_COPY(type, src)				  \
669 {									  \
670 	fletcher_4_fastest_impl.init_ ## type = src->init_ ## type;	  \
671 	fletcher_4_fastest_impl.fini_ ## type = src->fini_ ## type;	  \
672 	fletcher_4_fastest_impl.compute_ ## type = src->compute_ ## type; \
673 	fletcher_4_fastest_impl.uses_fpu = src->uses_fpu;		  \
674 }
675 
676 #define	FLETCHER_4_BENCH_NS	(MSEC2NSEC(1))		/* 1ms */
677 
678 typedef void fletcher_checksum_func_t(const void *, uint64_t, const void *,
679 					zio_cksum_t *);
680 
681 #if defined(_KERNEL)
682 static void
fletcher_4_benchmark_impl(boolean_t native,char * data,uint64_t data_size)683 fletcher_4_benchmark_impl(boolean_t native, char *data, uint64_t data_size)
684 {
685 
686 	struct fletcher_4_kstat *fastest_stat =
687 	    &fletcher_4_stat_data[fletcher_4_supp_impls_cnt];
688 	hrtime_t start;
689 	uint64_t run_bw, run_time_ns, best_run = 0;
690 	zio_cksum_t zc;
691 	uint32_t i, l, sel_save = IMPL_READ(fletcher_4_impl_chosen);
692 
693 	fletcher_checksum_func_t *fletcher_4_test = native ?
694 	    fletcher_4_native : fletcher_4_byteswap;
695 
696 	for (i = 0; i < fletcher_4_supp_impls_cnt; i++) {
697 		struct fletcher_4_kstat *stat = &fletcher_4_stat_data[i];
698 		uint64_t run_count = 0;
699 
700 		/* temporary set an implementation */
701 		fletcher_4_impl_chosen = i;
702 
703 		kpreempt_disable();
704 		start = gethrtime();
705 		do {
706 			for (l = 0; l < 32; l++, run_count++)
707 				fletcher_4_test(data, data_size, NULL, &zc);
708 
709 			run_time_ns = gethrtime() - start;
710 		} while (run_time_ns < FLETCHER_4_BENCH_NS);
711 		kpreempt_enable();
712 
713 		run_bw = data_size * run_count * NANOSEC;
714 		run_bw /= run_time_ns;	/* B/s */
715 
716 		if (native)
717 			stat->native = run_bw;
718 		else
719 			stat->byteswap = run_bw;
720 
721 		if (run_bw > best_run) {
722 			best_run = run_bw;
723 
724 			if (native) {
725 				fastest_stat->native = i;
726 				FLETCHER_4_FASTEST_FN_COPY(native,
727 				    fletcher_4_supp_impls[i]);
728 			} else {
729 				fastest_stat->byteswap = i;
730 				FLETCHER_4_FASTEST_FN_COPY(byteswap,
731 				    fletcher_4_supp_impls[i]);
732 			}
733 		}
734 	}
735 
736 	/* restore original selection */
737 	atomic_swap_32(&fletcher_4_impl_chosen, sel_save);
738 }
739 #endif /* _KERNEL */
740 
741 /*
742  * Initialize and benchmark all supported implementations.
743  */
744 static void
fletcher_4_benchmark(void)745 fletcher_4_benchmark(void)
746 {
747 	fletcher_4_ops_t *curr_impl;
748 	int i, c;
749 
750 	/* Move supported implementations into fletcher_4_supp_impls */
751 	for (i = 0, c = 0; i < ARRAY_SIZE(fletcher_4_impls); i++) {
752 		curr_impl = (fletcher_4_ops_t *)fletcher_4_impls[i];
753 
754 		if (curr_impl->valid && curr_impl->valid())
755 			fletcher_4_supp_impls[c++] = curr_impl;
756 	}
757 	membar_producer();	/* complete fletcher_4_supp_impls[] init */
758 	fletcher_4_supp_impls_cnt = c;	/* number of supported impl */
759 
760 #if defined(_KERNEL)
761 	static const size_t data_size = 1 << SPA_OLD_MAXBLOCKSHIFT; /* 128kiB */
762 	char *databuf = vmem_alloc(data_size, KM_SLEEP);
763 
764 	for (i = 0; i < data_size / sizeof (uint64_t); i++)
765 		((uint64_t *)databuf)[i] = (uintptr_t)(databuf+i); /* warm-up */
766 
767 	fletcher_4_benchmark_impl(B_FALSE, databuf, data_size);
768 	fletcher_4_benchmark_impl(B_TRUE, databuf, data_size);
769 
770 	vmem_free(databuf, data_size);
771 #else
772 	/*
773 	 * Skip the benchmark in user space to avoid impacting libzpool
774 	 * consumers (zdb, zhack, zinject, ztest).  The last implementation
775 	 * is assumed to be the fastest and used by default.
776 	 */
777 	memcpy(&fletcher_4_fastest_impl,
778 	    fletcher_4_supp_impls[fletcher_4_supp_impls_cnt - 1],
779 	    sizeof (fletcher_4_fastest_impl));
780 	fletcher_4_fastest_impl.name = "fastest";
781 	membar_producer();
782 #endif /* _KERNEL */
783 }
784 
785 void
fletcher_4_init(void)786 fletcher_4_init(void)
787 {
788 	/* Determine the fastest available implementation. */
789 	fletcher_4_benchmark();
790 
791 #if defined(_KERNEL)
792 	/* Install kstats for all implementations */
793 	fletcher_4_kstat = kstat_create("zfs", 0, "fletcher_4_bench", "misc",
794 	    KSTAT_TYPE_RAW, 0, KSTAT_FLAG_VIRTUAL);
795 	if (fletcher_4_kstat != NULL) {
796 		fletcher_4_kstat->ks_data = NULL;
797 		fletcher_4_kstat->ks_ndata = UINT32_MAX;
798 		kstat_set_raw_ops(fletcher_4_kstat,
799 		    fletcher_4_kstat_headers,
800 		    fletcher_4_kstat_data,
801 		    fletcher_4_kstat_addr);
802 		kstat_install(fletcher_4_kstat);
803 	}
804 #endif
805 
806 	/* Finish initialization */
807 	fletcher_4_initialized = B_TRUE;
808 }
809 
810 void
fletcher_4_fini(void)811 fletcher_4_fini(void)
812 {
813 #if defined(_KERNEL)
814 	if (fletcher_4_kstat != NULL) {
815 		kstat_delete(fletcher_4_kstat);
816 		fletcher_4_kstat = NULL;
817 	}
818 #endif
819 }
820 
821 /* ABD adapters */
822 
823 static void
abd_fletcher_4_init(zio_abd_checksum_data_t * cdp)824 abd_fletcher_4_init(zio_abd_checksum_data_t *cdp)
825 {
826 	const fletcher_4_ops_t *ops = fletcher_4_impl_get();
827 	cdp->acd_private = (void *) ops;
828 
829 	if (ops->uses_fpu == B_TRUE) {
830 		kfpu_begin();
831 	}
832 	if (cdp->acd_byteorder == ZIO_CHECKSUM_NATIVE)
833 		ops->init_native(cdp->acd_ctx);
834 	else
835 		ops->init_byteswap(cdp->acd_ctx);
836 
837 }
838 
839 static void
abd_fletcher_4_fini(zio_abd_checksum_data_t * cdp)840 abd_fletcher_4_fini(zio_abd_checksum_data_t *cdp)
841 {
842 	fletcher_4_ops_t *ops = (fletcher_4_ops_t *)cdp->acd_private;
843 
844 	ASSERT(ops);
845 
846 	if (cdp->acd_byteorder == ZIO_CHECKSUM_NATIVE)
847 		ops->fini_native(cdp->acd_ctx, cdp->acd_zcp);
848 	else
849 		ops->fini_byteswap(cdp->acd_ctx, cdp->acd_zcp);
850 
851 	if (ops->uses_fpu == B_TRUE) {
852 		kfpu_end();
853 	}
854 }
855 
856 
857 static void
abd_fletcher_4_simd2scalar(boolean_t native,void * data,size_t size,zio_abd_checksum_data_t * cdp)858 abd_fletcher_4_simd2scalar(boolean_t native, void *data, size_t size,
859     zio_abd_checksum_data_t *cdp)
860 {
861 	zio_cksum_t *zcp = cdp->acd_zcp;
862 
863 	ASSERT3U(size, <, FLETCHER_MIN_SIMD_SIZE);
864 
865 	abd_fletcher_4_fini(cdp);
866 	cdp->acd_private = (void *)&fletcher_4_scalar_ops;
867 
868 	if (native)
869 		fletcher_4_incremental_native(data, size, zcp);
870 	else
871 		fletcher_4_incremental_byteswap(data, size, zcp);
872 }
873 
874 static int
abd_fletcher_4_iter(void * data,size_t size,void * private)875 abd_fletcher_4_iter(void *data, size_t size, void *private)
876 {
877 	zio_abd_checksum_data_t *cdp = (zio_abd_checksum_data_t *)private;
878 	fletcher_4_ctx_t *ctx = cdp->acd_ctx;
879 	fletcher_4_ops_t *ops = (fletcher_4_ops_t *)cdp->acd_private;
880 	boolean_t native = cdp->acd_byteorder == ZIO_CHECKSUM_NATIVE;
881 	uint64_t asize = P2ALIGN_TYPED(size, FLETCHER_MIN_SIMD_SIZE, uint64_t);
882 
883 	ASSERT(IS_P2ALIGNED(size, sizeof (uint32_t)));
884 
885 	if (asize > 0) {
886 		if (native)
887 			ops->compute_native(ctx, data, asize);
888 		else
889 			ops->compute_byteswap(ctx, data, asize);
890 
891 		size -= asize;
892 		data = (char *)data + asize;
893 	}
894 
895 	if (size > 0) {
896 		ASSERT3U(size, <, FLETCHER_MIN_SIMD_SIZE);
897 		/* At this point we have to switch to scalar impl */
898 		abd_fletcher_4_simd2scalar(native, data, size, cdp);
899 	}
900 
901 	return (0);
902 }
903 
904 zio_abd_checksum_func_t fletcher_4_abd_ops = {
905 	.acf_init = abd_fletcher_4_init,
906 	.acf_fini = abd_fletcher_4_fini,
907 	.acf_iter = abd_fletcher_4_iter
908 };
909 
910 #if defined(_KERNEL)
911 
912 #define	IMPL_FMT(impl, i)	(((impl) == (i)) ? "[%s] " : "%s ")
913 
914 #if defined(__linux__)
915 
916 static int
fletcher_4_param_get(char * buffer,zfs_kernel_param_t * unused)917 fletcher_4_param_get(char *buffer, zfs_kernel_param_t *unused)
918 {
919 	const uint32_t impl = IMPL_READ(fletcher_4_impl_chosen);
920 	char *fmt;
921 	int cnt = 0;
922 
923 	/* list fastest */
924 	fmt = IMPL_FMT(impl, IMPL_FASTEST);
925 	cnt += kmem_scnprintf(buffer + cnt, PAGE_SIZE - cnt, fmt, "fastest");
926 
927 	/* list all supported implementations */
928 	for (uint32_t i = 0; i < fletcher_4_supp_impls_cnt; ++i) {
929 		fmt = IMPL_FMT(impl, i);
930 		cnt += kmem_scnprintf(buffer + cnt, PAGE_SIZE - cnt, fmt,
931 		    fletcher_4_supp_impls[i]->name);
932 	}
933 
934 	return (cnt);
935 }
936 
937 static int
fletcher_4_param_set(const char * val,zfs_kernel_param_t * unused)938 fletcher_4_param_set(const char *val, zfs_kernel_param_t *unused)
939 {
940 	return (fletcher_4_impl_set(val));
941 }
942 
943 #else
944 
945 #include <sys/sbuf.h>
946 
947 static int
fletcher_4_param(ZFS_MODULE_PARAM_ARGS)948 fletcher_4_param(ZFS_MODULE_PARAM_ARGS)
949 {
950 	int err;
951 
952 	if (req->newptr == NULL) {
953 		const uint32_t impl = IMPL_READ(fletcher_4_impl_chosen);
954 		const int init_buflen = 64;
955 		const char *fmt;
956 		struct sbuf *s;
957 
958 		s = sbuf_new_for_sysctl(NULL, NULL, init_buflen, req);
959 
960 		/* list fastest */
961 		fmt = IMPL_FMT(impl, IMPL_FASTEST);
962 		(void) sbuf_printf(s, fmt, "fastest");
963 
964 		/* list all supported implementations */
965 		for (uint32_t i = 0; i < fletcher_4_supp_impls_cnt; ++i) {
966 			fmt = IMPL_FMT(impl, i);
967 			(void) sbuf_printf(s, fmt,
968 			    fletcher_4_supp_impls[i]->name);
969 		}
970 
971 		err = sbuf_finish(s);
972 		sbuf_delete(s);
973 
974 		return (err);
975 	}
976 
977 	char buf[16];
978 
979 	err = sysctl_handle_string(oidp, buf, sizeof (buf), req);
980 	if (err)
981 		return (err);
982 	return (-fletcher_4_impl_set(buf));
983 }
984 
985 #endif
986 
987 #undef IMPL_FMT
988 
989 /*
990  * Choose a fletcher 4 implementation in ZFS.
991  * Users can choose "cycle" to exercise all implementations, but this is
992  * for testing purpose therefore it can only be set in user space.
993  */
994 ZFS_MODULE_VIRTUAL_PARAM_CALL(zfs, zfs_, fletcher_4_impl,
995     fletcher_4_param_set, fletcher_4_param_get, ZMOD_RW,
996 	"Select fletcher 4 implementation.");
997 
998 EXPORT_SYMBOL(fletcher_init);
999 EXPORT_SYMBOL(fletcher_2_incremental_native);
1000 EXPORT_SYMBOL(fletcher_2_incremental_byteswap);
1001 EXPORT_SYMBOL(fletcher_4_init);
1002 EXPORT_SYMBOL(fletcher_4_fini);
1003 EXPORT_SYMBOL(fletcher_2_native);
1004 EXPORT_SYMBOL(fletcher_2_byteswap);
1005 EXPORT_SYMBOL(fletcher_4_native);
1006 EXPORT_SYMBOL(fletcher_4_native_varsize);
1007 EXPORT_SYMBOL(fletcher_4_byteswap);
1008 EXPORT_SYMBOL(fletcher_4_incremental_native);
1009 EXPORT_SYMBOL(fletcher_4_incremental_byteswap);
1010 EXPORT_SYMBOL(fletcher_4_abd_ops);
1011 #endif
1012