Optimize RAIDZ expansion
[zfs.git] / module / zfs / zle.c
blob7810161966dceabfa82f48562aecc3050e660cab
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or https://opensource.org/licenses/CDDL-1.0.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
28 * Zero-length encoding. This is a fast and simple algorithm to eliminate
29 * runs of zeroes. Each chunk of compressed data begins with a length byte, b.
30 * If b < n (where n is the compression parameter) then the next b + 1 bytes
31 * are literal values. If b >= n then the next (256 - b + 1) bytes are zero.
33 #include <sys/types.h>
34 #include <sys/sysmacros.h>
35 #include <sys/zio_compress.h>
37 static size_t
38 zfs_zle_compress_buf(void *s_start, void *d_start, size_t s_len,
39 size_t d_len, int n)
41 uchar_t *src = s_start;
42 uchar_t *dst = d_start;
43 uchar_t *s_end = src + s_len;
44 uchar_t *d_end = dst + d_len;
46 while (src < s_end && dst < d_end - 1) {
47 uchar_t *first = src;
48 uchar_t *len = dst++;
49 if (src[0] == 0) {
50 uchar_t *last = src + (256 - n);
51 while (src < MIN(last, s_end) && src[0] == 0)
52 src++;
53 *len = src - first - 1 + n;
54 } else {
55 uchar_t *last = src + n;
56 if (d_end - dst < n)
57 break;
58 while (src < MIN(last, s_end) - 1 && (src[0] | src[1]))
59 *dst++ = *src++;
60 if (src[0])
61 *dst++ = *src++;
62 *len = src - first - 1;
65 return (src == s_end ? dst - (uchar_t *)d_start : s_len);
68 static int
69 zfs_zle_decompress_buf(void *s_start, void *d_start, size_t s_len,
70 size_t d_len, int n)
72 uchar_t *src = s_start;
73 uchar_t *dst = d_start;
74 uchar_t *s_end = src + s_len;
75 uchar_t *d_end = dst + d_len;
77 while (src < s_end && dst < d_end) {
78 int len = 1 + *src++;
79 if (len <= n) {
80 if (src + len > s_end || dst + len > d_end)
81 return (-1);
82 while (len-- != 0)
83 *dst++ = *src++;
84 } else {
85 len -= n;
86 if (dst + len > d_end)
87 return (-1);
88 while (len-- != 0)
89 *dst++ = 0;
92 return (dst == d_end ? 0 : -1);
95 ZFS_COMPRESS_WRAP_DECL(zfs_zle_compress)
96 ZFS_DECOMPRESS_WRAP_DECL(zfs_zle_decompress)