summaryrefslogtreecommitdiff
path: root/fs/smb/client/compress.c
blob: 17baa9ebc639ecf9a201c3498e0d83fc04dae92e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
// SPDX-License-Identifier: GPL-2.0-only
/*
 * Copyright (C) 2024, SUSE LLC
 *
 * Authors: Enzo Matsumiya <ematsumiya@suse.de>
 *
 * This file implements I/O compression support for SMB2 messages (SMB 3.1.1 only).
 * See compress/ for implementation details of each algorithm.
 *
 * References:
 * MS-SMB2 "3.1.4.4 Compressing the Message"
 * MS-SMB2 "3.1.5.3 Decompressing the Chained Message"
 * MS-XCA - for details of the supported algorithms
 */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/uio.h>

#include "../common/smb2pdu.h"
#include "cifsglob.h"
#include "cifs_debug.h"

#include "compress/lz77.h"
#include "compress.h"

#define SAMPLING_READ_SIZE	(16)
#define SAMPLING_INTERVAL	(256)
#define BUCKET_SIZE		(256)
/*
 * The size of the sample is based on a statistical sampling rule of thumb.
 * The common way is to perform sampling tests as long as the number of
 * elements in each cell is at least 5.
 *
 * Instead of 5, we choose 32 to obtain more accurate results.
 * If the data contain the maximum number of symbols, which is 256, we obtain a
 * sample size bound by 8192.
 *
 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
 * from up to 512 locations.
 */
#define MAX_SAMPLE_SIZE		(8192 * SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
//				  ^ == LZ77 window size

struct bucket_item {
	size_t count;
};

struct heuristic_ctx {
	/* Partial copy of input data */
	const u8 *sample;
	size_t sample_size;

	/* Buckets store counters for each byte value
	 *
	 * For statistical analysis of the input data we consider bytes that form a
	 * Galois Field of 256 objects. Each object has an attribute count, ie. how
	 * many times the object appeared in the sample.
	 */
	struct bucket_item bucket[BUCKET_SIZE];
	struct bucket_item aux_bucket[BUCKET_SIZE];

	struct list_head list;
};

/*
 * Shannon Entropy calculation.
 *
 * Pure byte distribution analysis fails to determine compressibility of data.
 * Try calculating entropy to estimate the average minimum number of bits
 * needed to encode the sampled data.
 *
 * For convenience, return the percentage of needed bits, instead of amount of
 * bits directly.
 *
 * @ENTROPY_LEVEL_OK - below that threshold, sample has low byte entropy
 *		       and can be compressible with high probability
 *
 * @ENTROPY_LEVEL_HIGH - data are not compressible with high probability
 *
 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
 */
#define ENTROPY_LEVEL_OK 65
#define ENTROPY_LEVEL_HIGH 80

/*
 * For increasead precision in shannon_entropy calculation,
 * let's do pow(n, M) to save more digits after comma:
 *
 * - maximum int bit length is 64
 * - ilog2(MAX_SAMPLE_SIZE) -> 13
 * - 13 * 4 = 52 < 64 -> M = 4
 *
 * So use pow(n, 4).
 */
static inline u32 ilog2_w(u64 n)
{
	return ilog2(n * n * n * n);
}

static u32 shannon_entropy(struct heuristic_ctx *ctx)
{
	const size_t max = 8 * ilog2_w(2);
	size_t i, p, p_base, sz_base, sum = 0;

	sz_base = ilog2_w(ctx->sample_size);

	for (i = 0; i < 256 && ctx->bucket[i].count > 0; i++) {
		p = ctx->bucket[i].count;
		p_base = ilog2_w(p);
		sum += p * (sz_base - p_base);
	}

	sum /= ctx->sample_size;

	return sum * 100 / max;
}

#define RADIX_BASE 4U
#define COUNTERS_SIZE (1U << RADIX_BASE)

static __always_inline u8 get4bits(u64 num, int shift)
{
	/* Reverse order */
	return ((COUNTERS_SIZE - 1) - ((num >> shift) % COUNTERS_SIZE));
}

/*
 * Use 4 bits as radix base
 * Use 16 u32 counters for calculating new position in buf array
 *
 * @array     - array that will be sorted
 * @aux	      - buffer array to store sorting results
 *              must be equal in size to @array
 * @num       - array size
 */
static void radix_sort(struct bucket_item *array, struct bucket_item *aux, int num)
{
	size_t buf_num, max_num, addr, new_addr, counters[COUNTERS_SIZE];
	int bitlen, shift, i;

	/*
	 * Try avoid useless loop iterations for small numbers stored in big
	 * counters.  Example: 48 33 4 ... in 64bit array
	 */
	max_num = array[0].count;
	for (i = 1; i < num; i++) {
		buf_num = array[i].count;

		if (buf_num > max_num)
			max_num = buf_num;
	}

	buf_num = ilog2(max_num);
	bitlen = ALIGN(buf_num, RADIX_BASE * 2);

	shift = 0;
	while (shift < bitlen) {
		memset(counters, 0, sizeof(counters));

		for (i = 0; i < num; i++) {
			buf_num = array[i].count;
			addr = get4bits(buf_num, shift);
			counters[addr]++;
		}

		for (i = 1; i < COUNTERS_SIZE; i++)
			counters[i] += counters[i - 1];

		for (i = num - 1; i >= 0; i--) {
			buf_num = array[i].count;
			addr = get4bits(buf_num, shift);
			counters[addr]--;
			new_addr = counters[addr];
			aux[new_addr] = array[i];
		}

		shift += RADIX_BASE;

		/*
		 * Normal radix expects to move data from a temporary array, to
		 * the main one.  But that requires some CPU time. Avoid that
		 * by doing another sort iteration to original array instead of
		 * memcpy()
		 */
		memset(counters, 0, sizeof(counters));

		for (i = 0; i < num; i ++) {
			buf_num = aux[i].count;
			addr = get4bits(buf_num, shift);
			counters[addr]++;
		}

		for (i = 1; i < COUNTERS_SIZE; i++)
			counters[i] += counters[i - 1];

		for (i = num - 1; i >= 0; i--) {
			buf_num = aux[i].count;
			addr = get4bits(buf_num, shift);
			counters[addr]--;
			new_addr = counters[addr];
			array[new_addr] = aux[i];
		}

		shift += RADIX_BASE;
	}
}

/*
 * Count how many bytes cover 90% of the sample.
 *
 * There are several types of structured binary data that use nearly all byte
 * values. The distribution can be uniform and counts in all buckets will be
 * nearly the same (eg. encrypted data). Unlikely to be compressible.
 *
 * Other possibility is normal (Gaussian) distribution, where the data could
 * be potentially compressible, but we have to take a few more steps to decide
 * how much.
 *
 * @BYTE_COVERAGE_LOW  - main part of byte values repeated frequently,
 *		      compression algo can easy fix that
 * @BYTE_COVERAGE_HIGH - data have uniform distribution and with high
 *                    probability is not compressible
 */
#define BYTE_COVERAGE_LOW 64
#define BYTE_COVERAGE_HIGH	200

static int byte_coverage(struct heuristic_ctx *ctx)
{
	const size_t threshold = ctx->sample_size * 90 / 100;
	struct bucket_item *bkt = &ctx->bucket[0];
	size_t sum = 0;
	int i;

	/* Sort in reverse order */
	radix_sort(ctx->bucket, ctx->aux_bucket, BUCKET_SIZE);

	for (i = 0; i < BYTE_COVERAGE_LOW; i++)
		sum += bkt[i].count;

	if (sum > threshold)
		return i;

	for (; i < BYTE_COVERAGE_HIGH && bkt[i].count > 0; i++) {
		sum += bkt[i].count;
		if (sum > threshold)
			break;
	}

	return i;
}

/*
 * Count ASCII bytes in buckets.
 *
 * This heuristic can detect textual data (configs, xml, json, html, etc).
 * Because in most text-like data byte set is restricted to limited number of
 * possible characters, and that restriction in most cases makes data easy to
 * compress.
 *
 * @ASCII_COUNT_THRESHOLD - consider all data within this byte set size:
 *	less - compressible
 *	more - need additional analysis
 */
#define ASCII_COUNT_THRESHOLD 64

static __always_inline u32 ascii_count(const struct heuristic_ctx *ctx)
{
	size_t count = 0;
	int i;

	for (i = 0; i < ASCII_COUNT_THRESHOLD; i++)
		if (ctx->bucket[i].count > 0)
			count++;

	/*
	 * Continue collecting count of byte values in buckets.  If the byte
	 * set size is bigger then the threshold, it's pointless to continue,
	 * the detection technique would fail for this type of data.
	 */
	for (; i < 256; i++) {
		if (ctx->bucket[i].count > 0) {
			count++;
			if (count > ASCII_COUNT_THRESHOLD)
				break;
		}
	}

	return count;
}

static __always_inline struct heuristic_ctx *heuristic_init(const u8 *buf, size_t len)
{
	struct heuristic_ctx *ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
	int i = 0, s = 0;

	if (!ctx)
		return ERR_PTR(-ENOMEM);

	ctx->sample = kzalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
	if (!ctx->sample) {
		kfree(ctx);
		return ERR_PTR(-ENOMEM);
	}

	if (len > MAX_SAMPLE_SIZE)
		len = MAX_SAMPLE_SIZE;

	while (i < len - SAMPLING_READ_SIZE) {
		memcpy((void *)&ctx->sample[s], &buf[i], SAMPLING_READ_SIZE);
		i += SAMPLING_INTERVAL;
		s += SAMPLING_INTERVAL;
	}

	ctx->sample_size = s;

	INIT_LIST_HEAD