/*1-*- linux-c -*-2drbd_receiver.c3This file is part of DRBD by Philipp Reisner and Lars Ellenberg.45Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.6Copyright (C) 1999-2008, Philipp Reisner <[email protected]>.7Copyright (C) 2002-2008, Lars Ellenberg <[email protected]>.89drbd is free software; you can redistribute it and/or modify10it under the terms of the GNU General Public License as published by11the Free Software Foundation; either version 2, or (at your option)12any later version.1314drbd is distributed in the hope that it will be useful,15but WITHOUT ANY WARRANTY; without even the implied warranty of16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the17GNU General Public License for more details.1819You should have received a copy of the GNU General Public License20along with drbd; see the file COPYING. If not, write to21the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.22*/2324#ifndef _DRBD_VLI_H25#define _DRBD_VLI_H2627/*28* At a granularity of 4KiB storage represented per bit,29* and stroage sizes of several TiB,30* and possibly small-bandwidth replication,31* the bitmap transfer time can take much too long,32* if transmitted in plain text.33*34* We try to reduce the transferred bitmap information35* by encoding runlengths of bit polarity.36*37* We never actually need to encode a "zero" (runlengths are positive).38* But then we have to store the value of the first bit.39* The first bit of information thus shall encode if the first runlength40* gives the number of set or unset bits.41*42* We assume that large areas are either completely set or unset,43* which gives good compression with any runlength method,44* even when encoding the runlength as fixed size 32bit/64bit integers.45*46* Still, there may be areas where the polarity flips every few bits,47* and encoding the runlength sequence of those areas with fix size48* integers would be much worse than plaintext.49*50* We want to encode small runlength values with minimum code length,51* while still being able to encode a Huge run of all zeros.52*53* Thus we need a Variable Length Integer encoding, VLI.54*55* For some cases, we produce more code bits than plaintext input.56* We need to send incompressible chunks as plaintext, skip over them57* and then see if the next chunk compresses better.58*59* We don't care too much about "excellent" compression ratio for large60* runlengths (all set/all clear): whether we achieve a factor of 10061* or 1000 is not that much of an issue.62* We do not want to waste too much on short runlengths in the "noisy"63* parts of the bitmap, though.64*65* There are endless variants of VLI, we experimented with:66* * simple byte-based67* * various bit based with different code word length.68*69* To avoid yet an other configuration parameter (choice of bitmap compression70* algorithm) which was difficult to explain and tune, we just chose the one71* variant that turned out best in all test cases.72* Based on real world usage patterns, with device sizes ranging from a few GiB73* to several TiB, file server/mailserver/webserver/mysql/postgress,74* mostly idle to really busy, the all time winner (though sometimes only75* marginally better) is:76*/7778/*79* encoding is "visualised" as80* __little endian__ bitstream, least significant bit first (left most)81*82* this particular encoding is chosen so that the prefix code83* starts as unary encoding the level, then modified so that84* 10 levels can be described in 8bit, with minimal overhead85* for the smaller levels.86*87* Number of data bits follow fibonacci sequence, with the exception of the88* last level (+1 data bit, so it makes 64bit total). The only worse code when89* encoding bit polarity runlength is 1 plain bits => 2 code bits.90prefix data bits max val NÂș data bits910 x 0x2 19210 x 0x4 193110 xx 0x8 2941110 xxx 0x10 39511110 xxx xx 0x30 596111110 xx xxxxxx 0x130 89711111100 xxxxxxxx xxxxx 0x2130 139811111110 xxxxxxxx xxxxxxxx xxxxx 0x202130 219911111101 xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xx 0x400202130 3410011111111 xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx 56101* maximum encodable value: 0x100000400202130 == 2**56 + some */102103/* compression "table":104transmitted x 0.29105as plaintext x ........................106x ........................107x ........................108x 0.59 0.21........................109x ........................................................110x .. c ...................................................111x 0.44.. o ...................................................112x .......... d ...................................................113x .......... e ...................................................114X............. ...................................................115x.............. b ...................................................1162.0x............... i ...................................................117#X................ t ...................................................118#................. s ........................... plain bits ..........119-+-----------------------------------------------------------------------1201 16 32 64121*/122123/* LEVEL: (total bits, prefix bits, prefix value),124* sorted ascending by number of total bits.125* The rest of the code table is calculated at compiletime from this. */126127/* fibonacci data 1, 1, ... */128#define VLI_L_1_1() do { \129LEVEL( 2, 1, 0x00); \130LEVEL( 3, 2, 0x01); \131LEVEL( 5, 3, 0x03); \132LEVEL( 7, 4, 0x07); \133LEVEL(10, 5, 0x0f); \134LEVEL(14, 6, 0x1f); \135LEVEL(21, 8, 0x3f); \136LEVEL(29, 8, 0x7f); \137LEVEL(42, 8, 0xbf); \138LEVEL(64, 8, 0xff); \139} while (0)140141/* finds a suitable level to decode the least significant part of in.142* returns number of bits consumed.143*144* BUG() for bad input, as that would mean a buggy code table. */145static inline int vli_decode_bits(u64 *out, const u64 in)146{147u64 adj = 1;148149#define LEVEL(t,b,v) \150do { \151if ((in & ((1 << b) -1)) == v) { \152*out = ((in & ((~0ULL) >> (64-t))) >> b) + adj; \153return t; \154} \155adj += 1ULL << (t - b); \156} while (0)157158VLI_L_1_1();159160/* NOT REACHED, if VLI_LEVELS code table is defined properly */161BUG();162#undef LEVEL163}164165/* return number of code bits needed,166* or negative error number */167static inline int __vli_encode_bits(u64 *out, const u64 in)168{169u64 max = 0;170u64 adj = 1;171172if (in == 0)173return -EINVAL;174175#define LEVEL(t,b,v) do { \176max += 1ULL << (t - b); \177if (in <= max) { \178if (out) \179*out = ((in - adj) << b) | v; \180return t; \181} \182adj = max + 1; \183} while (0)184185VLI_L_1_1();186187return -EOVERFLOW;188#undef LEVEL189}190191#undef VLI_L_1_1192193/* code from here down is independend of actually used bit code */194195/*196* Code length is determined by some unique (e.g. unary) prefix.197* This encodes arbitrary bit length, not whole bytes: we have a bit-stream,198* not a byte stream.199*/200201/* for the bitstream, we need a cursor */202struct bitstream_cursor {203/* the current byte */204u8 *b;205/* the current bit within *b, nomalized: 0..7 */206unsigned int bit;207};208209/* initialize cursor to point to first bit of stream */210static inline void bitstream_cursor_reset(struct bitstream_cursor *cur, void *s)211{212cur->b = s;213cur->bit = 0;214}215216/* advance cursor by that many bits; maximum expected input value: 64,217* but depending on VLI implementation, it may be more. */218static inline void bitstream_cursor_advance(struct bitstream_cursor *cur, unsigned int bits)219{220bits += cur->bit;221cur->b = cur->b + (bits >> 3);222cur->bit = bits & 7;223}224225/* the bitstream itself knows its length */226struct bitstream {227struct bitstream_cursor cur;228unsigned char *buf;229size_t buf_len; /* in bytes */230231/* for input stream:232* number of trailing 0 bits for padding233* total number of valid bits in stream: buf_len * 8 - pad_bits */234unsigned int pad_bits;235};236237static inline void bitstream_init(struct bitstream *bs, void *s, size_t len, unsigned int pad_bits)238{239bs->buf = s;240bs->buf_len = len;241bs->pad_bits = pad_bits;242bitstream_cursor_reset(&bs->cur, bs->buf);243}244245static inline void bitstream_rewind(struct bitstream *bs)246{247bitstream_cursor_reset(&bs->cur, bs->buf);248memset(bs->buf, 0, bs->buf_len);249}250251/* Put (at most 64) least significant bits of val into bitstream, and advance cursor.252* Ignores "pad_bits".253* Returns zero if bits == 0 (nothing to do).254* Returns number of bits used if successful.255*256* If there is not enough room left in bitstream,257* leaves bitstream unchanged and returns -ENOBUFS.258*/259static inline int bitstream_put_bits(struct bitstream *bs, u64 val, const unsigned int bits)260{261unsigned char *b = bs->cur.b;262unsigned int tmp;263264if (bits == 0)265return 0;266267if ((bs->cur.b + ((bs->cur.bit + bits -1) >> 3)) - bs->buf >= bs->buf_len)268return -ENOBUFS;269270/* paranoia: strip off hi bits; they should not be set anyways. */271if (bits < 64)272val &= ~0ULL >> (64 - bits);273274*b++ |= (val & 0xff) << bs->cur.bit;275276for (tmp = 8 - bs->cur.bit; tmp < bits; tmp += 8)277*b++ |= (val >> tmp) & 0xff;278279bitstream_cursor_advance(&bs->cur, bits);280return bits;281}282283/* Fetch (at most 64) bits from bitstream into *out, and advance cursor.284*285* If more than 64 bits are requested, returns -EINVAL and leave *out unchanged.286*287* If there are less than the requested number of valid bits left in the288* bitstream, still fetches all available bits.289*290* Returns number of actually fetched bits.291*/292static inline int bitstream_get_bits(struct bitstream *bs, u64 *out, int bits)293{294u64 val;295unsigned int n;296297if (bits > 64)298return -EINVAL;299300if (bs->cur.b + ((bs->cur.bit + bs->pad_bits + bits -1) >> 3) - bs->buf >= bs->buf_len)301bits = ((bs->buf_len - (bs->cur.b - bs->buf)) << 3)302- bs->cur.bit - bs->pad_bits;303304if (bits == 0) {305*out = 0;306return 0;307}308309/* get the high bits */310val = 0;311n = (bs->cur.bit + bits + 7) >> 3;312/* n may be at most 9, if cur.bit + bits > 64 */313/* which means this copies at most 8 byte */314if (n) {315memcpy(&val, bs->cur.b+1, n - 1);316val = le64_to_cpu(val) << (8 - bs->cur.bit);317}318319/* we still need the low bits */320val |= bs->cur.b[0] >> bs->cur.bit;321322/* and mask out bits we don't want */323val &= ~0ULL >> (64 - bits);324325bitstream_cursor_advance(&bs->cur, bits);326*out = val;327328return bits;329}330331/* encodes @in as vli into @bs;332333* return values334* > 0: number of bits successfully stored in bitstream335* -ENOBUFS @bs is full336* -EINVAL input zero (invalid)337* -EOVERFLOW input too large for this vli code (invalid)338*/339static inline int vli_encode_bits(struct bitstream *bs, u64 in)340{341u64 code = code;342int bits = __vli_encode_bits(&code, in);343344if (bits <= 0)345return bits;346347return bitstream_put_bits(bs, code, bits);348}349350#endif351352353