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