2 * Xor Based Zero Run Length Encoding
4 * Copyright 2013 Red Hat, Inc. and/or its affiliates
7 * Orit Wasserman <owasserm@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
13 #include "qemu/osdep.h"
14 #include "qemu/cutils.h"
15 #include "include/migration/migration.h"
23 nzrun = length byte...
25 length = uleb128 encoded integer
27 int xbzrle_encode_buffer(uint8_t *old_buf
, uint8_t *new_buf
, int slen
,
28 uint8_t *dst
, int dlen
)
30 uint32_t zrun_len
= 0, nzrun_len
= 0;
33 uint8_t *nzrun_start
= NULL
;
35 g_assert(!(((uintptr_t)old_buf
| (uintptr_t)new_buf
| slen
) %
44 /* not aligned to sizeof(long) */
45 res
= (slen
- i
) % sizeof(long);
46 while (res
&& old_buf
[i
] == new_buf
[i
]) {
52 /* word at a time for speed */
55 (*(long *)(old_buf
+ i
)) == (*(long *)(new_buf
+ i
))) {
57 zrun_len
+= sizeof(long);
60 /* go over the rest */
61 while (i
< slen
&& old_buf
[i
] == new_buf
[i
]) {
67 /* buffer unchanged */
68 if (zrun_len
== slen
) {
72 /* skip last zero run */
77 d
+= uleb128_encode_small(dst
+ d
, zrun_len
);
80 nzrun_start
= new_buf
+ i
;
86 /* not aligned to sizeof(long) */
87 res
= (slen
- i
) % sizeof(long);
88 while (res
&& old_buf
[i
] != new_buf
[i
]) {
94 /* word at a time for speed, use of 32-bit long okay */
96 /* truncation to 32-bit long okay */
97 unsigned long mask
= (unsigned long)0x0101010101010101ULL
;
100 xor = *(unsigned long *)(old_buf
+ i
)
101 ^ *(unsigned long *)(new_buf
+ i
);
102 if ((xor - mask
) & ~xor & (mask
<< 7)) {
103 /* found the end of an nzrun within the current long */
104 while (old_buf
[i
] != new_buf
[i
]) {
111 nzrun_len
+= sizeof(long);
116 d
+= uleb128_encode_small(dst
+ d
, nzrun_len
);
118 if (d
+ nzrun_len
> dlen
) {
121 memcpy(dst
+ d
, nzrun_start
, nzrun_len
);
129 int xbzrle_decode_buffer(uint8_t *src
, int slen
, uint8_t *dst
, int dlen
)
138 if ((slen
- i
) < 2) {
142 ret
= uleb128_decode_small(src
+ i
, &count
);
143 if (ret
< 0 || (i
&& !count
)) {
155 if ((slen
- i
) < 2) {
159 ret
= uleb128_decode_small(src
+ i
, &count
);
160 if (ret
< 0 || !count
) {
166 if (d
+ count
> dlen
|| i
+ count
> slen
) {
170 memcpy(dst
+ d
, src
+ i
, count
);