Skip to contentSkip to conversation

smb: common: compress: add memory access helpers to compress.h

PATCH Superseded Enzo Matsumiya 1 participant 10 messages Jul 13

Subsystems (2)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/10 smb: common: compress: add memory access helpers to compress.h

Add memory access helpers + some other common definitions to be used by SMB2 compression (both server and client, and all algorithms).

Changes:
- update affected call paths in lz77.c and compress.c
- update server/compress.* and client/compress.* to include compress.h only

---
 fs/smb/client/compress.c          |   3 +-
 fs/smb/client/compress.h          |  11 ---
 fs/smb/common/compress/compress.c |   9 +-
 fs/smb/common/compress/compress.h | 126 ++++++++++++++++++++++++++++
 fs/smb/common/compress/lz77.c     | 134 +++++++-----------------------
 fs/smb/server/compress.c          |   3 -
 6 files changed, 156 insertions(+), 130 deletions(-)
fs/smb/client/compress.c +1 -2
index 8f0860970741..5591a8d85037 100644
@@ -18,11 +18,10 @@
 #include <linux/sort.h>
 
 #include "cifsglob.h"
-#include "../common/smb2pdu.h"
 #include "cifsproto.h"
 #include "smb2proto.h"
 
-#include "../common/compress/lz77.h"
+#include "../common/compress/compress.h"
 #include "compress.h"
 
 /*
fs/smb/client/compress.h +0 -11
index e08e6d339d21..fc8c8d502e45 100644
@@ -17,24 +17,14 @@
 
 #include <linux/uio.h>
 #include <linux/kernel.h>
-#include "../common/smb2pdu.h"
-#include "../common/compress/compress.h"
 #include "cifsglob.h"
 
-/* sizeof(smb2_compression_hdr) - sizeof(OriginalPayloadSize) */
-#define SMB_COMPRESS_HDR_LEN		16
-/* sizeof(smb2_compression_payload_hdr) - sizeof(OriginalPayloadSize) */
-#define SMB_COMPRESS_PAYLOAD_HDR_LEN	8
-#define SMB_COMPRESS_MIN_LEN		PAGE_SIZE
-
 #ifdef CONFIG_CIFS_COMPRESSION
 typedef int (*compress_send_fn)(struct TCP_Server_Info *, int, struct smb_rqst *);
 
-
 int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq,
 		 compress_send_fn send_fn);
 bool should_compress(const struct cifs_tcon *tcon, const struct smb_rqst *rq);
-
 #else /* !CONFIG_CIFS_COMPRESSION */
 static inline int smb_compress(void *unused1, void *unused2, void *unused3)
 {
@@ -45,6 +35,5 @@ static inline bool should_compress(void *unused1, void *unused2)
 {
 	return false;
 }
-
 #endif /* !CONFIG_CIFS_COMPRESSION */
 #endif /* _SMB_COMPRESS_H */
fs/smb/common/compress/compress.c +1 -8
index b07a317597a4..088e0d0d2792 100644
@@ -7,15 +7,8 @@
 #include <linux/module.h>
 #include <linux/overflow.h>
 #include <linux/string.h>
-#include <linux/unaligned.h>
 
 #include "compress.h"
-#include "lz77.h"
-
-#define SMB2_COMPRESSION_CHAINED_HDR_LEN \
-	offsetof(struct smb2_compression_hdr, CompressionAlgorithm)
-#define SMB2_COMPRESSION_PAYLOAD_BASE_LEN \
-	(sizeof(struct smb2_compression_payload_hdr) - sizeof(__le32))
 
 /*
  * A NONE payload carries bytes verbatim. Keep both cursors and remaining
@@ -75,7 +68,7 @@ static int smb_decompress_lz77_payload(const u8 **src, u32 *slen, u8 **dst,
 	if (len < sizeof(__le32) || len > *slen)
 		return -EINVAL;
 
-	orig_size = get_unaligned_le32(*src);
+	orig_size = mem_read32(*src);
 	if (orig_size > *dlen)
 		return -EINVAL;
 
fs/smb/common/compress/compress.h +126 -0

137 lines not on this page · raw message

fs/smb/common/compress/lz77.c +28 -106

284 lines not on this page · raw message

fs/smb/server/compress.c +0 -3
index f8cf515b9c30..8c910f996e04 100644
@@ -10,9 +10,6 @@
 
 #include "compress.h"
 #include "smb_common.h"
-#include "../common/compress/lz77.h"
-
-#define SMB_COMPRESS_MIN_LEN	PAGE_SIZE
 
 /**
  * ksmbd_decompress_request() - replace a compressed request with its SMB2 PDU
Signature · 1 line
2.54.0
#1 lore raw

PATCH 2/10 smb: client: compress: rework compression heuristics

- add enum with *COMPRESSIBLE values
- is_compressible() is now check_compressible(), and is called from smb_compress() instead of should_compress(); the latter only does the basic checks (write >= 4K)
- compressibility check now also may return 'MAYBE_COMPRESSIBLE', for cases when even with deeper analysis, it can't return a decisive result
- rewrite Shannon entropy computation (original code was copied over from btrfs, so it carelessly used their parameters)
- divide heuristics checks in stages:
1. check if buffer is filled with same byte (RLE)
2. check if partial RLE (first ~1% of buffer repeats same byte)
3. check whole buffer entropy
4. split buffer in 64k chunks and check entropy and byte distribution (based on hardcoded thresholds)
- remove collect_sample() and collect_step() helpers, heuristics checks are run on the entire buffer now
- remove calc_byte_distribution(), as it's a redundant entropy check

---
 fs/smb/client/compress.c | 440 ++++++++++++++++++++++-----------------
 1 file changed, 244 insertions(+), 196 deletions(-)
fs/smb/client/compress.c +244 -196
index 5591a8d85037..7c08e2b843c2 100644
@@ -1,6 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0-only
 /*
- * Copyright (C) 2024, SUSE LLC
+ * Copyright (C) 2024-2026, SUSE LLC
  *
  * Authors: Enzo Matsumiya <[email protected]>
  *
@@ -24,242 +24,277 @@
 #include "../common/compress/compress.h"
 #include "compress.h"
 
-/*
- * The heuristic_*() functions below try to determine data compressibility.
+/**
+ * freq_count() - Count symbols (bytes) frequencies in a buffer.
+ * @buf:	uncompressed buffer
+ * @len:	size of @buf
+ * @mem:	(caller-allocated) auxiliary memory for parallel accumulators
+ * @count:	on exit, set to unique byte count (alphabet size) in @buf
  *
- * Derived from fs/btrfs/compression.c, changing coding style, some parameters, and removing
- * unused parts.
+ * This function counts all bytes' unique count and frequencies.
+ * Expect @mem to be 1024 * sizeof(u32) long and zeroed.
+ * Final frequencies will be stored on first 256 elements of @mem.
  *
- * Read that file for better and more detailed explanation of the calculations.
+ * Function is optimized for OoO CPUs (straightforward iterative count is about 2-3x slower).
  *
- * The algorithms are ran in a collected sample of the input (uncompressed) data.
- * The sample is formed of 2K reads in PAGE_SIZE intervals, with a maximum size of 4M.
+ * Return: max frequency found in @buf.
  *
- * Parsing the sample goes from "low-hanging fruits" (fastest algorithms, likely compressible)
- * to "need more analysis" (likely uncompressible).
+ * (*) This is an adapted version of FSE's https://github.com/Cyan4973/FiniteStateEntropy
  */
+static noinline u32 freq_count(const u8 *buf, const u32 len, u32 *mem, u32 *count)
+{
+	const u8 *p = buf, *end = p + len;
+	u32 c = 0, max_freq = 0;
+	u32 v = mem_read32(p);
+	u32 *acc1 = mem;
+	u32 *acc2 = acc1 + 256;
+	u32 *acc3 = acc2 + 256;
+	u32 *acc4 = acc3 + 256;
+
+	p += sizeof(u32);
+
+	/* Count by stripes of 16 bytes. */
+	while (p < end - 15) {
+		u32 cached = v;
+
+		v = mem_read32(p);
+		p += 4;
+		acc1[(u8)cached]++;
+		acc2[(u8)(cached>>8)]++;
+		acc3[(u8)(cached>>16)]++;
+		acc4[(u8)(cached>>24)]++;
+
+		cached = v;
+		v = mem_read32(p);
+		p += 4;
+		acc1[(u8)cached]++;
+		acc2[(u8)(cached>>8)]++;
+		acc3[(u8)(cached>>16)]++;
+		acc4[(u8)(cached>>24)]++;
+
+		cached = v;
+		v = mem_read32(p);
+		p += 4;
+		acc1[(u8)cached]++;
+		acc2[(u8)(cached>>8)]++;
+		acc3[(u8)(cached>>16)]++;
+		acc4[(u8)(cached>>24)]++;
+
+		cached = v;
+		v = mem_read32(p);
+		p += 4;
+		acc1[(u8)cached]++;
+		acc2[(u8)(cached>>8)]++;
+		acc3[(u8)(cached>>16)]++;
+		acc4[(u8)(cached>>24)]++;
+	}
 
-struct bucket {
-	unsigned int count;
-};
+	p -= 4;
+
+	/* Count lefotver symbols. */
+	while (p < end)
+		acc1[*p++]++;
+
+	/*
+	 * Combine accumulators + store.
+	 *
+	 * Avoid dereferencing @count here because performance.
+	 */
+	for (v = 0; v < 256; v++) {
+		acc1[v] += acc2[v] + acc3[v] + acc4[v];
+
+		if (acc1[v]) {
+			c++;
+			if (acc1[v] > max_freq)
+				max_freq = acc1[v];
+		}
+	}
 
-static inline size_t pow4(size_t n)
-{
-	return n * n * n * n;
+	if (count)
+		*count = c;
+
+	return max_freq;
 }
 
-/*
- * has_low_entropy() - Compute Shannon entropy of the sampled data.
- * @bkt:	Bytes counts of the sample.
- * @slen:	Size of the sample.
+/**
+ * calc_entropy() - Compute Shannon entropy of a sample symbols' frequencies.
+ * @freqs:	frequency counts of the sample
+ * @len:	size of the sample
+ * @scale:	scale for final result
  *
- * Return: true if the level (percentage of number of bits that would be required to
- *	   compress the data) is below the minimum threshold.
+ * @freqs may include zero freq symbols.
+ * The final sum is multiplied by @factor to fit callers' precision requirements.
  *
- * Note:
- * There _is_ an entropy level here that's > 65 (minimum threshold) that would indicate a
- * possibility of compression, but compressing, or even further analysing, it would waste so much
- * resources that it's simply not worth it.
+ * Valid results interpretation for @factor == 1:
+ *   < 6: definitely compressible
+ * 6 - 7: probably compressible, but needs other parameters/heuristics for decisive result
+ *   > 7: probably uncompressible -- other parameters/heuristics _might_ evaluate to "somewhat
+ *	  compressible", but usually not much
  *
- * Also Shannon entropy is the last computed heuristic; if we got this far and ended up
- * with uncertainty, just stay on the safe side and call it uncompressible.
+ * Return: approximate number of bits (scaled to @scale) per byte that would be required to
+ * compress the data.
  */
-static bool has_low_entropy(struct bucket *bkt, size_t slen)
+static __always_inline u32 calc_entropy(const u32 *freqs, const u32 len, const u32 scale)
 {
-	const size_t threshold = 65, max_entropy = 8 * ilog2(16);
-	size_t i, p, p2, len, sum = 0;
-
-	len = ilog2(pow4(slen));
+	const u32 len2 = ilog2(len);
+	size_t i, p, sum = 0;
 
-	for (i = 0; i < 256 && bkt[i].count > 0; i++) {
-		p = bkt[i].count;
-		p2 = ilog2(pow4(p));
-		sum += p * (len - p2);
+	for (i = 0; i < 256; i++) {
+		/* 0 freq won't skew the results (ilog2(n) also returns 0 if n < 2) */
+		p = freqs[i];
+		sum += p * (len2 - ilog2(p));
 	}
 
-	sum /= slen;
-
-	return ((sum * 100 / max_entropy) <= threshold);
+	return (sum * scale / len);
 }
 
-#define BYTE_DIST_BAD		0
-#define BYTE_DIST_GOOD		1
-#define BYTE_DIST_MAYBE		2
 /*
- * calc_byte_distribution() - Compute byte distribution on the sampled data.
- * @bkt:	Byte counts of the sample.
- * @slen:	Size of the sample.
- *
- * Return:
- * BYTE_DIST_BAD:	A "hard no" for compression -- a computed uniform distribution of
- *			the bytes (e.g. random or encrypted data).
- * BYTE_DIST_GOOD:	High probability (normal (Gaussian) distribution) of the data being
- *			compressible.
- * BYTE_DIST_MAYBE:	When computed byte distribution resulted in "low > n < high"
- *			grounds.  has_low_entropy() should be used for a final decision.
+ * Heuristic limit values.
+ * These are based on 64k blocks.
  */
-static int calc_byte_distribution(struct bucket *bkt, size_t slen)
-{
-	const size_t low = 64, high = 200, threshold = slen * 90 / 100;
-	size_t sum = 0;
-	int i;
-
-	for (i = 0; i < low; i++)
-		sum += bkt[i].count;
-
-	if (sum > threshold)
-		return BYTE_DIST_BAD;
-
-	for (; i < high && bkt[i].count > 0; i++) {
-		sum += bkt[i].count;
-		if (sum > threshold)
-			break;
-	}
-
-	if (i <= low)
-		return BYTE_DIST_GOOD;
-
-	if (i >= high)
-		return BYTE_DIST_BAD;
-
-	return BYTE_DIST_MAYBE;
-}
-
-static bool is_mostly_ascii(const struct bucket *bkt)
-{
-	size_t count = 0;
-	int i;
-
-	for (i = 0; i < 256; i++)
-		if (bkt[i].count > 0)
-			/* Too many non-ASCII (0-63) bytes. */
-			if (++count > 64)
-				return false;
-
-	return true;
-}
-
-static bool has_repeated_data(const u8 *sample, size_t len)
-{
-	size_t s = len / 2;
-
-	return (!memcmp(&sample[0], &sample[s], s));
-}
-
-static int cmp_bkt(const void *_a, const void *_b)
-{
-	const struct bucket *a = _a, *b = _b;
-
-	/* Reverse sort. */
-	if (a->count > b->count)
-		return -1;
-
-	return 1;
-}
+static const u32 heuristic_freq_hi	= 8000;
+static const u32 heuristic_freq_lo	= 5000;
+static const u32 heuristic_entropy_hi	= 800;
+static const u32 heuristic_entropy_mid	= 700;
+static const u32 heuristic_entropy_lo	= 600;
+static const u32 heuristic_alphabet_hi	= 256;
+static const u32 heuristic_alphabet_lo	= 128;
+
+enum {
+	UNCOMPRESSIBLE = 0,
+	COMPRESSIBLE,
+	MAYBE_COMPRESSIBLE,
+};
 
 /*
- * Collect some 2K samples with 2K gaps between.
+ * Computes entropy and byte dominance of @buf, on a 64k block basis.
+ *
+ * Return: one of the *COMPRESSIBLE values
  */
-static int collect_sample(const struct iov_iter *source, ssize_t max, u8 *sample)
+static int check_compressible_chunks(const u8 *buf, const u32 len, u32 *freqs)
 {
-	struct iov_iter iter = *source;
-	size_t s = 0;
-
-	while (iov_iter_count(&iter) >= SZ_2K) {
-		size_t part = umin(umin(iov_iter_count(&iter), SZ_2K), max);
-		size_t n;
-
-		n = copy_from_iter(sample + s, part, &iter);
-		if (n != part)
-			return -EFAULT;
+	int score = 0, boost = 0, n = 0;
+	const u32 freqs_size = 1024 * sizeof(u32);
+	const u32 max_samples = 64;
+	const u32 max_sample_len = (len / max_samples);
+	const u32 nsamples = umin(max_samples, len / max_sample_len);
+	const s32 half_samples = nsamples / 2;
+	const u8 *end = buf + len;
+
+	while (buf < end) {
+		u32 alphabet = 0;
+		const u32 remaining = end - buf;
+		const u32 slen = umin(max_sample_len, remaining);
+		const u32 max_freq = freq_count(buf, slen, freqs, &alphabet);
+		const u32 entropy = calc_entropy(freqs, slen, 100);
+
+		if (entropy < heuristic_entropy_mid && max_freq > heuristic_freq_hi)
+			score++;
+		else if (entropy >= heuristic_entropy_mid && max_freq < heuristic_freq_lo)
+			score--;
+
+		if (alphabet < heuristic_alphabet_hi) {
+			boost++;
+			if (alphabet < heuristic_alphabet_lo)
+				boost++;
+		}
+
+		/* Reward/penalty for really good/bad entropy. */
+		if (entropy > heuristic_entropy_hi)
+			boost -= 2;
+		else if (entropy < heuristic_entropy_lo)
+			boost += 2;
+
+		memset(freqs, 0, freqs_size);
+		buf += slen;
+		n++;
+	}
 
-		s += n;
-		max -= n;
+	/* Check how much the heuristics above impacted (at least) half of @buf. */
+	if (score + boost > 0 && score + boost < half_samples)
+		return MAYBE_COMPRESSIBLE;
 
-		if (iov_iter_count(&iter) < PAGE_SIZE - SZ_2K)
-			break;
+	if (score + boost > -half_samples) {
+		if (score > half_samples || score + boost > half_samples)
+			return COMPRESSIBLE;
 
-		iov_iter_advance(&iter, SZ_2K);
+		return MAYBE_COMPRESSIBLE;
 	}
 
-	return s;
+	return UNCOMPRESSIBLE;
 }
 
 /*
- * is_compressible() - Determines if a chunk of data is compressible.
- * @data: Iterator containing uncompressed data.
+ * Check @buf heuristics (entropy/distribution) to determine its compressibility level.
+ *
+ * Tests shows that this function is quite reliable in predicting data compressibility, matching
+ * very close with the behaviour of LZ77 compression success and failures.
  *
- * Return: true if @data is compressible, false otherwise.
+ * This function allocates memory, callers must check for -ENOMEM.
  *
- * Tests shows that this function is quite reliable in predicting data compressibility,
- * matching close to 1:1 with the behaviour of LZ77 compression success and failures.
+ * Return: one of the *COMPRESSIBLE values on success, -errno otherwise.
  */
-static bool is_compressible(const struct iov_iter *data)
+static __must_check int check_compressible(const u8 *buf, u32 len)
 {
-	const size_t read_size = SZ_2K, bkt_size = 256, max = SZ_4M;
-	struct bucket *bkt = NULL;
-	size_t len;
-	u8 *sample;
-	bool ret = false;
-	int i;
-
-	/* Preventive double check -- already checked in should_compress(). */
-	len = iov_iter_count(data);
-	if (unlikely(len < read_size))
-		return ret;
-
-	if (len - read_size > max)
-		len = max;
-
-	sample = kvzalloc(len, GFP_KERNEL);
-	if (!sample) {
-		WARN_ON_ONCE(1);
-
-		return ret;
-	}
-
-	/* Sample 2K bytes per page of the uncompressed data. */
-	i = collect_sample(data, len, sample);
-	if (i <= 0) {
-		WARN_ON_ONCE(1);
+	u32 entropy, *freqs, rle = 0, rle_boost = 0;
+	const u32 min_reps = (len / 100); /* ~1% of @len */
+	const u8 *p;
+	int ret;
 
-		goto out;
-	}
+	if (unlikely(!buf || !len))
+		return -EINVAL;
 
-	len = i;
-	ret = true;
+	/* Stage 1: RLE (@buf is filled with same byte, a.k.a Run-Length Encoding). */
+	p = memchr_inv(buf, *buf, len);
+	if (!p)
+		/* Full RLE */
+		return 1;
 
-	if (has_repeated_data(sample, len))
-		goto out;
+	/* Stage 2: partial/starting RLE (repeating bytes cover are at least @min_reps long). */
+	if (p - buf >= min_reps) {
+		rle = (p - buf);
 
-	bkt = kzalloc_objs(*bkt, bkt_size);
-	if (!bkt) {
-		WARN_ON_ONCE(1);
-		ret = false;
+		buf += rle;
+		len -= rle;
 
-		goto out;
+		rle_boost = rle >> (ilog2(len) - 1);
 	}
 
-	for (i = 0; i < len; i++)
-		bkt[sample[i]].count++;
-
-	if (is_mostly_ascii(bkt))
-		goto out;
-
-	/* Sort in descending order */
-	sort(bkt, bkt_size, sizeof(*bkt), cmp_bkt, NULL);
-
-	i = calc_byte_distribution(bkt, len);
-	if (i != BYTE_DIST_MAYBE) {
-		ret = !!i;
-
-		goto out;
+	freqs = kcalloc(1024, sizeof(*freqs), GFP_KERNEL);
+	if (!freqs)
+		return -ENOMEM;
+
+	/*
+	 * Stage 3: whole buffer entropy check (decisive results if too high or too low).
+	 *
+	 * Don't care about max freq or alphabet size here.
+	 */
+	(void)freq_count(buf, len, freqs, NULL);
+	entropy = calc_entropy(freqs, len, 1);
+	ret = MAYBE_COMPRESSIBLE;
+
+	if (entropy >= 8)
+		ret = UNCOMPRESSIBLE;
+	else if (entropy < 6 || (rle_boost && entropy - rle_boost <= 6) || len <= SZ_64K)
+		ret = COMPRESSIBLE;
+
+	if (ret == MAYBE_COMPRESSIBLE) {
+		memset(freqs, 0, sizeof(u32) * 1024);
+
+		/*
+		 * Stage 4: break down buffer into 64k chunks for more detailed analysis.
+		 *
+		 * Note that it's quite common to go from MAYBE_COMPRESSIBLE -> COMPRESSIBLE after
+		 * chunks analysis.
+		 *
+		 * OTOH, getting again MAYBE_COMPRESSIBLE really means 'uncompressible' for
+		 * compressors that focus on speed (e.g. LZ77).
+		 * Compressors focused on compression ratio might yield a good compression.
+		 */
+		ret = check_compressible_chunks(buf, len, freqs);
 	}
 
-	ret = has_low_entropy(bkt, len);
-out:
-	kvfree(sample);
-	kfree(bkt);
+	kfree(freqs);
 
 	return ret;
 }
@@ -275,7 +310,6 @@ static bool is_compressible(const struct iov_iter *data)
  * - server has enabled compression for the share
  * - it's a read or write request
  * - (write only) request length is >= SMB_COMPRESS_MIN_LEN
- * - (write only) is_compressible() returns 1
  *
  * Return false otherwise.
  */
@@ -295,10 +329,7 @@ bool should_compress(const struct cifs_tcon *tcon, const struct smb_rqst *rq)
 	if (shdr->Command == SMB2_WRITE) {
 		const struct smb2_write_req *wreq = rq->rq_iov->iov_base;
 
-		if (le32_to_cpu(wreq->Length) < SMB_COMPRESS_MIN_LEN)
-			return false;
-
-		return is_compressible(&rq->rq_iter);
+		return (le32_to_cpu(wreq->Length) >= SMB_COMPRESS_MIN_LEN);
 	}
 
 	return (shdr->Command == SMB2_READ);
@@ -332,6 +363,23 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s
 		goto err_free;
 	}
 
+	/*
+	 * Even though smb_lz77_compress() runs quite fast on uncompressible data (it ends up
+	 * usually just parsing the input buffer), this is much faster.
+	 *
+	 * So to keep things balanced (compress performance vs prediction accuracy), let's drop the
+	 * uncompressible low-hanging fruits here and let smb_lz77_compress() handle the
+	 * exceptions/rare cases.
+	 */
+	ret = check_compressible(src, slen);
+
+	/* XXX: do something with MAYBE_COMPRESSIBLE */
+	if (ret != COMPRESSIBLE) {
+		if (ret >= 0)
+			ret = send_fn(server, 1, rq);
+		goto err_free;
+	}
+
 	dlen = smb_lz77_compressed_alloc_size(slen);
 	dst = kvzalloc(dlen, GFP_KERNEL);
 	if (!dst) {
Signature · 1 line
2.54.0
#2 lore raw

PATCH 3/10 smb: client: compress: disable compression on reconnects

In reply to Enzo Matsumiya

Windows Server resets the connection if it gets a compressed request that it couldn't decompress.

Some encoded payloads might decode differently on the server, or vice-versa, due to different implementation details (not really a bug), or an actual bug on either implementation.

To prevent an infinite retry on such failed sends, simply disable compression for that server when a reconnect is about to happen.

---
 fs/smb/client/connect.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
fs/smb/client/connect.c +14 -0
index 85aec302c89e..324452bc0437 100644
@@ -401,6 +401,20 @@ static int __cifs_reconnect(struct TCP_Server_Info *server,
 		try_to_freeze();
 		cifs_server_lock(server);
 
+		/*
+		 * Servers might disconnect us when they can't decompress a compressed request we
+		 * sent.
+		 * When this happens, as a failsafe measure, disable compression entirely to avoid
+		 * an endless retry.
+		 *
+		 * TODO: implement a more flexible alternative, e.g. identify and retry sending the
+		 * failed request uncompressed, without having to disable compression entirely.
+		 */
+		if (server->compression.enabled) {
+			cifs_server_dbg(VFS | ONCE, "disabling compression (failsafe)\n");
+			memset(&server->compression, 0, sizeof(server->compression));
+		}
+
 		if (!cifs_swn_set_server_dstaddr(server) &&
 		    !SERVER_IS_CHAN(server)) {
 			/* resolve the hostname again to make sure that IP address is up-to-date */
Signature · 1 line
2.54.0
#3 lore raw

PATCH 4/10 smb: common: compress: do chained and unchained compression in a single function

In reply to Enzo Matsumiya

Rename smb_compression_compress_chained() to smb_compression_compress(), and allow it to handle both unchained and chained compressions.

Also, for both unchained and chained cases, MS-SMB2 spec allows the compressed request to have a leading uncompressed chunk (between header and compressed payload).

smb_compression_compress_chained() fully compressed @dst without allowing such flexibility.

Add a @uncomp and @uncomp_len to allow callers to include an external uncompressed chunk in the final payload, or copy those bytes from @src (@uncomp == NULL && @uncomp_len > 0).

Other changes:
- drop smb_compression_builder::first field -- add all payload headers with Flags = "NONE", setup the first flag "CHAINED" at the end
- server/compress.c:
- use smb_compression_compress() with @uncomp == NULL and

    @uncomp_len == 0 (ksmbd always compresses the whole data)

- TODO: rework caller to use the generic function (instead of calling smb_lz77_compress() separately)

---
 fs/smb/common/compress/compress.c | 114 ++++++++++++++++++++++--------
 fs/smb/common/compress/compress.h |   6 +-
 fs/smb/server/compress.c          |  11 +--
 3 files changed, 94 insertions(+), 37 deletions(-)
fs/smb/common/compress/compress.c +85 -29
index 088e0d0d2792..9f87d31e9986 100644
@@ -213,7 +213,6 @@ EXPORT_SYMBOL_GPL(smb_compression_decompress);
 struct smb_compression_builder {
 	u8 *pos;
 	u32 remaining;
-	bool first;
 };
 
 /*
@@ -236,14 +235,12 @@ smb_compression_add_payload(struct smb_compression_builder *builder,
 
 	payload = (struct smb2_compression_payload_hdr *)builder->pos;
 	payload->CompressionAlgorithm = alg;
-	payload->Flags = cpu_to_le16(builder->first ?
-		SMB2_COMPRESSION_FLAG_CHAINED : SMB2_COMPRESSION_FLAG_NONE);
+	payload->Flags = cpu_to_le16(SMB2_COMPRESSION_FLAG_NONE);
 	payload->Length = cpu_to_le32(payload_len +
 		(orig_size ? sizeof(payload->OriginalPayloadSize) : 0));
 
 	builder->pos += hdr_len;
 	builder->remaining -= hdr_len;
-	builder->first = false;
 	return payload;
 }
 
@@ -279,7 +276,7 @@ static int smb_compression_add_none(struct smb_compression_builder *builder,
 }
 
 static int smb_compression_add_lz77(struct smb_compression_builder *builder,
-				    const u8 *src, u32 len)
+				    const u8 *src, u32 len, bool chained)
 {
 	struct smb2_compression_payload_hdr *payload;
 	u32 comp_len;
@@ -288,32 +285,40 @@ static int smb_compression_add_lz77(struct smb_compression_builder *builder,
 	if (builder->remaining <= sizeof(*payload))
 		return -ENOSPC;
 
-	comp_len = builder->remaining - sizeof(*payload);
-	payload = smb_compression_add_payload(builder, SMB3_COMPRESS_LZ77,
-					      comp_len, true);
-	if (!payload)
-		return -ENOSPC;
+	comp_len = builder->remaining;
+	if (chained) {
+		comp_len -= sizeof(*payload);
+		payload = smb_compression_add_payload(builder, SMB3_COMPRESS_LZ77,
+						      comp_len, true);
+		if (!payload)
+			return -ENOSPC;
+	}
 
 	rc = smb_lz77_compress(src, len, builder->pos, &comp_len);
 	if (rc)
 		return rc;
 
-	payload->Length = cpu_to_le32(comp_len +
-				      sizeof(payload->OriginalPayloadSize));
-	payload->OriginalPayloadSize = cpu_to_le32(len);
+	if (chained) {
+		payload->Length = cpu_to_le32(comp_len + sizeof(payload->OriginalPayloadSize));
+		payload->OriginalPayloadSize = cpu_to_le32(len);
+	}
+
 	builder->pos += comp_len;
 	builder->remaining -= comp_len;
 	return 0;
 }
 
 /**
- * smb_compression_compress_chained() - build a chained SMB2 transform
+ * smb_compression_compress() - build a SMB2 compression transform (chained optional)
  * @alg: negotiated general-purpose compression algorithm
+ * @chained: is chained compression was negotiated
  * @allow_pattern: whether Pattern_V1 was negotiated
  * @src: complete uncompressed SMB2 message
  * @slen: size of @src
  * @dst: output buffer for the transform
  * @dlen: input capacity of @dst and output transform size
+ * @uncomp: (optional) uncompressed data to be included in the compressed payload
+ * @uncomp_len: (optional) @uncomp size, or amount of bytes to copy uncompressed from @src
  *
  * Following the algorithm in [MS-SMB2] 3.1.4.4, encode sufficiently long
  * repeated runs at the front and back as Pattern_V1 payloads. Compress a
@@ -323,14 +328,18 @@ static int smb_compression_add_lz77(struct smb_compression_builder *builder,
  * This helper does not decide whether the final transform is smaller than the
  * original message. The transport caller owns that policy decision.
  *
+ * If @uncomp is not NULL, copy @uncomp_len from it, as is, to right after the compression header.
+ * Otherwise, if @uncomp_len is >0, copy that many bytes from @src to right after compression
+ * header.
+ *
  * Return: 0 on success, otherwise a negative errno.
  */
-int smb_compression_compress_chained(__le16 alg, bool allow_pattern,
-				     const void *src, u32 slen,
-				     void *dst, u32 *dlen)
+int smb_compression_compress(__le16 alg, bool chained, bool allow_pattern,
+			     const void *src, u32 slen, void *dst, u32 *dlen,
+			     const void *uncomp, u32 uncomp_len)
 {
-	struct smb2_compression_hdr *hdr = dst;
 	struct smb_compression_builder builder;
+	struct smb2_compression_hdr *hdr;
 	const u8 *input = src;
 	u32 forward = 0, backward = 0, middle_len;
 	int rc;
@@ -339,11 +348,38 @@ int smb_compression_compress_chained(__le16 alg, bool allow_pattern,
 	    *dlen <= SMB2_COMPRESSION_CHAINED_HDR_LEN || !slen)
 		return -EINVAL;
 
-	hdr->ProtocolId = SMB2_COMPRESSION_TRANSFORM_ID;
-	hdr->OriginalCompressedSegmentSize = cpu_to_le32(slen);
+	/* Note that the below is a bug, but (chained && !allow_pattern) is a valid combination */
+	if (WARN_ON_ONCE(!chained && allow_pattern))
+		return -EINVAL;
+
+	/*
+	 * Offset @dst for both unchained and chained cases, header is setup at the end.
+	 *
+	 * Note the layouts:
+	 *
+	 * smb2_compression_hdr			| smb2_compression_payload_hdr
+	 * -------------------------------------|-------------------------------
+	 *   ProtocolId				|
+	 *   OriginalCompressedSegmentSize	|
+	 *   CompressionAlgorithm		| CompressionAlgorithm
+	 *   Flags				| Flags
+	 *   Offset				| Length
+	 *
+	 * By aligning @dst to start at the "first payload header", @uncomp_len fits nicely for
+	 * both unchained and chained cases as well.
+	 */
 	builder.pos = (u8 *)dst + SMB2_COMPRESSION_CHAINED_HDR_LEN;
 	builder.remaining = *dlen - SMB2_COMPRESSION_CHAINED_HDR_LEN;
-	builder.first = true;
+
+	if (uncomp_len) {
+		smb_compression_add_none(&builder, uncomp ?: input, uncomp_len);
+
+		if (!uncomp)
+			input += uncomp_len;
+	}
+
+	if (!chained)
+		goto do_lz;
 
 	if (allow_pattern && slen > 32) {
 		for (forward = 1; forward < slen; forward++) {
@@ -366,16 +402,14 @@ int smb_compression_compress_chained(__le16 alg, bool allow_pattern,
 		if (rc)
 			return rc;
 	}
-
+do_lz:
+	rc = 0;
 	middle_len = slen - forward - backward;
-	if (middle_len > 1024)
-		rc = smb_compression_add_lz77(&builder, input + forward,
-					      middle_len);
-	else if (middle_len)
+	if (middle_len > 1024 || !chained)
+		rc = smb_compression_add_lz77(&builder, input + forward, middle_len, chained);
+	else if (middle_len && chained)
 		rc = smb_compression_add_none(&builder,
 					      input + forward, middle_len);
-	else
-		rc = 0;
 	if (rc)
 		return rc;
 
@@ -387,6 +421,28 @@ int smb_compression_compress_chained(__le16 alg, bool allow_pattern,
 	}
 
 	*dlen = builder.pos - (u8 *)dst;
+
+	/*
+	 * Set header at the end so we overwrite the flag of first payload (when chained).
+	 * Also when chained, if @uncomp_len > 0, that uncompressed chunk is also part of the whole
+	 * payload, so we must account for that.
+	 */
+	hdr = dst;
+	hdr->ProtocolId = SMB2_COMPRESSION_TRANSFORM_ID;
+	hdr->OriginalCompressedSegmentSize = cpu_to_le32(slen);
+	hdr->Flags = cpu_to_le16(SMB2_COMPRESSION_FLAG_NONE);
+
+	if (chained) {
+		hdr->OriginalCompressedSegmentSize += cpu_to_le32(uncomp_len);
+		hdr->Flags = cpu_to_le16(SMB2_COMPRESSION_FLAG_CHAINED);
+	} else if (uncomp_len) {
+		/*
+		 * If we copied an uncompressed chunk, it was added with a "NONE" algorithm,
+		 * so set the correct one when unchained.
+		 */
+		hdr->CompressionAlgorithm = alg;
+	}
+
 	return 0;
 }
-EXPORT_SYMBOL_GPL(smb_compression_compress_chained);
+EXPORT_SYMBOL_GPL(smb_compression_compress);
fs/smb/common/compress/compress.h +3 -3
index 24b558167fe7..6760862de04c 100644
@@ -147,8 +147,8 @@ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)
 
 int smb_compression_decompress(__le16 alg, bool allow_chained,
 			       const void *src, u32 slen, void *dst, u32 dlen);
-int smb_compression_compress_chained(__le16 alg, bool allow_pattern,
-				     const void *src, u32 slen,
-				     void *dst, u32 *dlen);
+int smb_compression_compress(__le16 alg, bool chained, bool allow_pattern,
+			     const void *src, u32 slen, void *dst, u32 *dlen,
+			     const void *uncomp, u32 uncomp_len);
 
 #endif /* _COMMON_SMB_COMPRESS_H */
fs/smb/server/compress.c +6 -5
index 8c910f996e04..32027a15f7ab 100644
@@ -145,11 +145,12 @@ int ksmbd_compress_response(struct ksmbd_work *work)
 
 	if (work->conn->compress_chained) {
 		dst_len = max_dst_len;
-		rc = smb_compression_compress_chained(SMB3_COMPRESS_LZ77,
-						      work->conn->compress_pattern,
-						      src, src_len,
-						      out + sizeof(__be32),
-						      &dst_len);
+		rc = smb_compression_compress(SMB3_COMPRESS_LZ77,
+					      work->conn->compress_chained,
+					      work->conn->compress_pattern,
+					      src, src_len,
+					      out + sizeof(__be32), &dst_len,
+					      NULL, 0);
 		if (rc == -EMSGSIZE || dst_len >= src_len) {
 			rc = 0;
 			goto out;
Signature · 1 line
2.54.0
#4 lore raw

PATCH 5/10 smb: client: compress: enable Pattern_V1 + chained compression

In reply to Enzo Matsumiya

Negotiate Pattern_V1 and LZ77 compression algorithms by default (if 'compress' mount option is set).

Changes:
- drop TCP_Server_Info::compression::requested, rely on ::enabled only
- add smb_compress_alloc_size() helper to compute compressed buffer size, to account for Pattern_V1 payloads as well
- call smb_compression_compress() with SMB2 header as @uncomp

---
 fs/smb/client/cifs_debug.c        | 18 ++++++++++------
 fs/smb/client/cifsglob.h          |  1 -
 fs/smb/client/compress.c          | 36 ++++++++++++++-----------------
 fs/smb/client/connect.c           |  2 +-
 fs/smb/client/sess.c              |  2 +-
 fs/smb/client/smb2pdu.c           | 25 ++++++++++++++-------
 fs/smb/common/compress/compress.h | 28 ++++++++++++++++++++++++
 fs/smb/server/compress.c          |  5 +----
 8 files changed, 75 insertions(+), 42 deletions(-)
fs/smb/client/cifs_debug.c +11 -7
index 4ed4f55a0bb7..36b4b7345c04 100644
@@ -552,14 +552,18 @@ static int cifs_debug_data_proc_show(struct seq_file *m, void *v)
 		}
 
 		seq_puts(m, "\nCompression: ");
-		if (!IS_ENABLED(CONFIG_CIFS_COMPRESSION))
+		if (!IS_ENABLED(CONFIG_CIFS_COMPRESSION)) {
 			seq_puts(m, "no built-in support");
-		else if (!server->compression.requested)
-			seq_puts(m, "disabled on mount");
-		else if (server->compression.enabled)
-			seq_printf(m, "enabled (%s)", compression_alg_str(server->compression.alg));
-		else
-			seq_puts(m, "disabled (not supported by this server)");
+		} else if (!server->compression.enabled) {
+			seq_puts(m, "disabled"); /* XXX: reason? */
+		} else {
+			seq_printf(m, "enabled, chained: %s, algs: ",
+				   str_yes_no(server->compression.chained));
+
+			seq_printf(m, "%s ", compression_alg_str(server->compression.alg));
+			if (server->compression.pattern)
+				seq_printf(m, "%s ", compression_alg_str(SMB3_COMPRESS_PATTERN));
+		}
 
 		/* Show negotiated encryption cipher, even if not required */
 		seq_puts(m, "\nEncryption: ");
fs/smb/client/cifsglob.h +0 -1
index 99f9e6dca62b..a08aa7fc84f4 100644
@@ -787,7 +787,6 @@ struct TCP_Server_Info {
 	unsigned int	rdma_readwrite_threshold;
 	unsigned int	retrans;
 	struct {
-		bool requested; /* "compress" mount option set*/
 		bool enabled; /* actually negotiated with server */
 		bool chained; /* chained transforms were negotiated */
 		bool pattern; /* Pattern_V1 chained payloads were negotiated */
fs/smb/client/compress.c +16 -20
index 7c08e2b843c2..72ac727250f6 100644
@@ -338,8 +338,9 @@ bool should_compress(const struct cifs_tcon *tcon, const struct smb_rqst *rq)
 int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_send_fn send_fn)
 {
 	struct iov_iter iter;
-	u32 slen, dlen;
+	u32 slen, dlen, shdr_len;
 	void *src, *dst = NULL;
+	bool use_pattern;
 	int ret;
 
 	if (!server || !rq || !rq->rq_iov || !rq->rq_iov->iov_base)
@@ -380,32 +381,27 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s
 		goto err_free;
 	}
 
-	dlen = smb_lz77_compressed_alloc_size(slen);
+	use_pattern = server->compression.pattern;
+	shdr_len = rq->rq_iov[0].iov_len;
+	dlen = smb_compress_alloc_size(slen, use_pattern) + shdr_len;
 	dst = kvzalloc(dlen, GFP_KERNEL);
 	if (!dst) {
 		ret = -ENOMEM;
 		goto err_free;
 	}
 
-	ret = smb_lz77_compress(src, slen, dst, &dlen);
+	ret = smb_compression_compress(SMB3_COMPRESS_LZ77, server->compression.chained, use_pattern,
+				       src, slen, dst, &dlen, rq->rq_iov[0].iov_base, shdr_len);
 	if (!ret) {
-		struct smb2_compression_hdr hdr = { 0 };
-		struct smb_rqst comp_rq = { .rq_nvec = 3, };
-		struct kvec iov[3];
-
-		hdr.ProtocolId = SMB2_COMPRESSION_TRANSFORM_ID;
-		hdr.OriginalCompressedSegmentSize = cpu_to_le32(slen);
-		hdr.CompressionAlgorithm = SMB3_COMPRESS_LZ77;
-		hdr.Flags = SMB2_COMPRESSION_FLAG_NONE;
-		hdr.Offset = cpu_to_le32(rq->rq_iov[0].iov_len);
-
-		iov[0].iov_base = &hdr;
-		iov[0].iov_len = sizeof(hdr);
-		iov[1] = rq->rq_iov[0];
-		iov[2].iov_base = dst;
-		iov[2].iov_len = dlen;
-
-		comp_rq.rq_iov = iov;
+		struct smb_rqst comp_rq = { .rq_nvec = 1, };
+		struct kvec iov = {
+			.iov_base = dst,
+			.iov_len = dlen,
+		};
+
+		iov.iov_base = dst;
+		iov.iov_len = dlen;
+		comp_rq.rq_iov = &iov;
 
 		ret = send_fn(server, 1, &comp_rq);
 	} else if (ret == -EMSGSIZE || dlen >= slen) {
fs/smb/client/connect.c +1 -1
index 324452bc0437..dd35abdac334 100644
@@ -1830,7 +1830,7 @@ cifs_get_tcp_session(struct smb3_fs_context *ctx,
 	tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
 	tcp_ses->reconnect_instance = 1;
 	tcp_ses->lstrp = jiffies;
-	tcp_ses->compression.requested = ctx->compress;
+	tcp_ses->compression.enabled = ctx->compress;
 	spin_lock_init(&tcp_ses->req_lock);
 	spin_lock_init(&tcp_ses->srv_lock);
 	spin_lock_init(&tcp_ses->mid_queue_lock);
fs/smb/client/sess.c +1 -1
index de2012cc9cf3..83f4b5d107f6 100644
@@ -552,7 +552,7 @@ cifs_ses_add_channel(struct cifs_ses *ses,
 	ctx->echo_interval = ses->server->echo_interval / HZ;
 	ctx->max_credits = ses->server->max_credits;
 	ctx->min_offload = ses->server->min_offload;
-	ctx->compress = ses->server->compression.requested;
+	ctx->compress = ses->server->compression.enabled;
 	ctx->dfs_conn = ses->server->dfs_conn;
 	ctx->ignore_signature = ses->server->ignore_signature;
 	ctx->leaf_fullpath = ses->server->leaf_fullpath;
fs/smb/client/smb2pdu.c +17 -8
index d058584b8f05..41cdc9f5e692 100644
@@ -785,7 +785,7 @@ assemble_neg_contexts(struct smb2_negotiate_req *req,
 	pneg_ctxt += sizeof(struct smb2_posix_neg_context);
 	neg_context_count++;
 
-	if (server->compression.requested) {
+	if (server->compression.enabled) {
 		build_compression_ctxt((struct smb2_compression_capabilities_context *)
 				pneg_ctxt);
 		ctxt_len = ALIGN(sizeof(struct smb2_compression_capabilities_context), 8);
@@ -835,11 +835,6 @@ static void decode_compress_ctx(struct TCP_Server_Info *server,
 	unsigned int len = le16_to_cpu(ctxt->DataLength);
 	unsigned int count, i;
 
-	server->compression.enabled = false;
-	server->compression.chained = false;
-	server->compression.pattern = false;
-	server->compression.alg = SMB3_COMPRESS_NONE;
-
 	/*
 	 * Caller checked that DataLength remains within SMB boundary. We still
 	 * need to confirm that one CompressionAlgorithms member is accounted
@@ -876,6 +871,12 @@ static void decode_compress_ctx(struct TCP_Server_Info *server,
 	/*
 	 * Pattern_V1 cannot appear in an unchained transform even if a broken
 	 * peer lists it in the algorithm array.
+	 *
+	 * OTOH, the chained flag might have been negotiated without either/both peers having not
+	 * advertised Pattern_V1 algorithm support.
+	 *
+	 * (which doesn't make much sense, but we'll still have to send compressed payloads with
+	 * the chained flag set in "chained && !pattern_v1" cases)
 	 */
 	server->compression.chained =
 		ctxt->Flags == SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED;
@@ -1336,11 +1337,19 @@ SMB2_negotiate(const unsigned int xid,
 	}
 
 	if (server->dialect == SMB311_PROT_ID) {
-		if (rsp->NegotiateContextCount)
+		bool compression_enabled = server->compression.enabled;
+
+		/* Reset compression settings in case of server not supporting it */
+		memset(&server->compression, 0, sizeof(server->compression));
+
+		if (rsp->NegotiateContextCount) {
 			rc = smb311_decode_neg_context(rsp, server,
 						       rsp_iov.iov_len);
-		else
+			if (!rc && compression_enabled && !server->compression.enabled)
+				cifs_server_dbg(VFS, "Server doesn't support compression, disabling\n");
+		} else {
 			cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
+		}
 	}
 
 	if (server->cipher_type && !rc)
fs/smb/common/compress/compress.h +28 -0
index 6760862de04c..e1fad498d567 100644
@@ -145,6 +145,34 @@ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)
 	return alg == SMB3_COMPRESS_LZ77 || alg == SMB3_COMPRESS_PATTERN;
 }
 
+/**
+ * smb_compress_alloc_size() - Compute total allocation size required for compressed (dst) buffer.
+ * @size:		uncompressed size
+ * @use_pattern:	if Pattern_V1 is enabled
+ *
+ * For any case:
+ * - SMB2 compression hdr
+ * - LZ* payload
+ *
+ * If @use_pattern, also account for:
+ * - 2x payload hdr for Pattern_V1
+ * - 2x Pattern_V1 payloads
+ * - 1x NONE payload hdr
+ *
+ * (possible uncompressed leftovers are included in LZ alloc size)
+ */
+static __always_inline u32 smb_compress_alloc_size(const u32 size, const bool use_pattern)
+{
+	u32 alloc_size;
+
+	alloc_size = sizeof(struct smb2_compression_hdr) + smb_lz77_compressed_alloc_size(size);
+	if (use_pattern)
+		alloc_size += (SMB2_COMPRESSION_PAYLOAD_BASE_LEN * 3) +
+			(sizeof(struct smb2_compression_pattern_v1) * 2);
+
+	return alloc_size;
+}
+
 int smb_compression_decompress(__le16 alg, bool allow_chained,
 			       const void *src, u32 slen, void *dst, u32 dlen);
 int smb_compression_compress(__le16 alg, bool chained, bool allow_pattern,
fs/smb/server/compress.c +1 -4
index 32027a15f7ab..e5851d603469 100644
@@ -132,10 +132,7 @@ int ksmbd_compress_response(struct ksmbd_work *work)
 		goto out;
 	}
 
-	max_dst_len = smb_lz77_compressed_alloc_size(src_len) +
-		sizeof(struct smb2_compression_hdr) +
-		3 * sizeof(struct smb2_compression_payload_hdr) +
-		2 * sizeof(struct smb2_compression_pattern_v1);
+	max_dst_len = smb_compress_alloc_size(src_len, work->conn->compress_pattern);
 	out = kvzalloc(sizeof(__be32) + max_dst_len,
 		       KSMBD_DEFAULT_GFP);
 	if (!out) {
Signature · 1 line
2.54.0
#5 lore raw

PATCH 6/10 smb: common: compress: allow smb_lz77_compress() to overcompress

In reply to Enzo Matsumiya

Change smb_lz77_compress() to return 0 on successful compression, leaving it up to callers to decide if @dlen >= @slen is an error (currently returns -EMSGSIZE on such cases).

This allows better compression in certain cases where Pattern_V1 got a good compression already, but LZ77 chunk was overcompressed (which usually yields good compressed data as a whole)

Other changes:
- adjust client and server callers to correctly interpret the new return value

---
 fs/smb/client/compress.c      |  4 ++--
 fs/smb/common/compress/lz77.c |  7 ++-----
 fs/smb/server/compress.c      | 15 ++++-----------
 3 files changed, 8 insertions(+), 18 deletions(-)
fs/smb/client/compress.c +2 -2
index 72ac727250f6..d94bacf3edbd 100644
@@ -392,7 +392,7 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s
 
 	ret = smb_compression_compress(SMB3_COMPRESS_LZ77, server->compression.chained, use_pattern,
 				       src, slen, dst, &dlen, rq->rq_iov[0].iov_base, shdr_len);
-	if (!ret) {
+	if (!ret && dlen < slen) {
 		struct smb_rqst comp_rq = { .rq_nvec = 1, };
 		struct kvec iov = {
 			.iov_base = dst,
@@ -404,7 +404,7 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s
 		comp_rq.rq_iov = &iov;
 
 		ret = send_fn(server, 1, &comp_rq);
-	} else if (ret == -EMSGSIZE || dlen >= slen) {
+	} else if (!ret) {
 		ret = send_fn(server, 1, rq);
 	}
 err_free:
fs/smb/common/compress/lz77.c +2 -5
index e32e2f3040d8..f88f49e01629 100644
@@ -248,19 +248,16 @@ noinline int smb_lz77_compress(const void *src, const u32 slen, void *dst, u32 *
 	} while (srcp < end);
 out:
 	dstp = lz77_encode_literals(anchor, end, dstp, &flag, &flag_count, &flag_pos);
-
 	flag_count = LZ77_FLAG_MAX - flag_count;
 	flag <<= flag_count;
 	flag |= (1UL << flag_count) - 1;
 	mem_write32(flag_pos, flag);
 
+	/* Compression is successful from our POV -- let caller decide if @dlen suits them. */
 	*dlen = dstp - dst;
 	kvfree(htable);
 
-	if (*dlen < slen)
-		return 0;
-
-	return -EMSGSIZE;
+	return 0;
 }
 EXPORT_SYMBOL_GPL(smb_lz77_compress);
 
fs/smb/server/compress.c +4 -11
index e5851d603469..648660f8bfab 100644
@@ -148,12 +148,10 @@ int ksmbd_compress_response(struct ksmbd_work *work)
 					      src, src_len,
 					      out + sizeof(__be32), &dst_len,
 					      NULL, 0);
-		if (rc == -EMSGSIZE || dst_len >= src_len) {
-			rc = 0;
-			goto out;
-		}
-		if (rc)
+		/* if dst_len >= src_len, rc is 0 */
+		if (rc || dst_len >= src_len)
 			goto out;
+
 		compressed_pdu_len = dst_len;
 	} else {
 		/*
@@ -164,12 +162,7 @@ int ksmbd_compress_response(struct ksmbd_work *work)
 		rc = smb_lz77_compress(src, src_len,
 				       out + sizeof(__be32) + sizeof(*chdr),
 				       &dst_len);
-		if (rc == -EMSGSIZE ||
-		    dst_len + sizeof(*chdr) >= src_len) {
-			rc = 0;
-			goto out;
-		}
-		if (rc)
+		if (rc || dst_len + sizeof(*chdr) >= src_len)
 			goto out;
 
 		compressed_pdu_len = sizeof(*chdr) + dst_len;
Signature · 1 line
2.54.0
#6 lore raw

PATCH 7/10 smb: common: compress: smb_lz77_decompress() improvements

In reply to Enzo Matsumiya

LZ77 decompression performance improvements:
- make use of mem_read*() helpers for faster unaligned reads in x86
- change lz77_decode_match_len() to return a pointer as it advances (instead of dereferencing @src every time to update it, which is costlier)
- also use a pointer for nib position instead of 2 separate args (@nibble and @have_nibble)
- decode flags in batches instead of one by one, e.g. a 00001111 flag is read only once now, with decoding operations in sequence (saves a few operations on back-and-forth reading/parsing)
- use memcpy() when copying non-overlapping memory (faster and a much more common case)

---
 fs/smb/common/compress/lz77.c | 272 ++++++++++++++++++++++------------
 1 file changed, 178 insertions(+), 94 deletions(-)
fs/smb/common/compress/lz77.c +178 -94
index f88f49e01629..f86c13736e34 100644
@@ -261,117 +261,201 @@ noinline int smb_lz77_compress(const void *src, const u32 slen, void *dst, u32 *
 }
 EXPORT_SYMBOL_GPL(smb_lz77_compress);
 
-static int lz77_decode_match_len(const u8 **src, const u8 *end, u16 token,
-				 u8 *nibble, bool *have_nibble, u32 *len)
+static __always_inline const void *lz77_decode_match_len(const void *src, const void *end,
+							 const void **nib, u32 *len)
 {
-	u8 extra;
-
-	*len = (token & 0x7) + 3;
-	if ((token & 0x7) != 0x7)
-		return 0;
-
-	if (!*have_nibble) {
-		if (*src >= end)
-			return -EINVAL;
-		*nibble = *(*src)++;
-		extra = *nibble & 0xf;
-		*have_nibble = true;
-	} else {
-		extra = *nibble >> 4;
-		*have_nibble = false;
-	}
-
-	*len += extra;
-	if (extra == 0xf) {
-		u8 b;
+	u32 mlen = *len & 7;
 
-		if (*src >= end)
-			return -EINVAL;
-		b = *(*src)++;
-		if (b != 0xff) {
-			*len += b;
+	/*
+	 * *@len points to the initial match length decoded.
+	 * We'll keep checking + decoding further if extra bits/bytes were used to encode larger
+	 * lengths.
+	 *
+	 * Since we're reading from @src itself, this means any OOB read is an error
+	 * (bug, malformed payload, etc).
+	 */
+	if (mlen == 7) {
+		if (!*nib) {
+			*nib = src;
+			if (unlikely(src >= end))
+				return NULL;
+
+			mlen = mem_read8(src) & 15;
+			src++;
 		} else {
-			u16 w;
-
-			if (end - *src < 2)
-				return -EINVAL;
-			w = mem_read16(*src);
-			*src += 2;
-			if (w) {
-				*len = w + 3;
-			} else {
-				u32 long_len;
-
-				if (end - *src < 4)
-					return -EINVAL;
-				long_len = mem_read32(*src);
-				*src += 4;
-				if (check_add_overflow(long_len, 3, len))
-					return -EINVAL;
+			mlen = mem_read8(*nib) >> 4;
+			*nib = NULL;
+		}
+
+		if (mlen == 15) {
+			if (unlikely(src >= end))
+				return NULL;
+
+			mlen = mem_read8(src);
+			src++;
+
+			if (mlen == 255) {
+				if (unlikely(src + sizeof(u16) > end))
+					return NULL;
+
+				mlen = mem_read16(src);
+				src += sizeof(u16);
+
+				if (mlen == 0) {
+					if (unlikely(src + sizeof(u32) > end))
+						return NULL;
+
+					mlen = mem_read32(src);
+					src += sizeof(u32);
+				}
+
+				/* Unexpected match len < 15 + 7 (decoding bug) */
+				if (unlikely(mlen < 23))
+					return NULL;
+
+				mlen -= (15 + 7);
 			}
+			mlen += 15;
 		}
+		mlen += 7;
 	}
+	mlen += 3;
+	*len = mlen;
 
-	return 0;
+	return src;
 }
 
-int smb_lz77_decompress(const void *src, const u32 slen, void *dst,
-			const u32 dlen)
+noinline int smb_lz77_decompress(const void *src, const u32 slen, void *dst, const u32 dlen)
 {
-	const u8 *sp = src, *send = sp + slen;
-	u8 *dp = dst, *dend = dp + dlen;
-	u32 flags = 0;
-	int flag_count = 0;
-	u8 nibble = 0;
-	bool have_nibble = false;
-
-	while (dp < dend) {
-		u32 len, dist;
-		u16 token;
-
-		if (!flag_count) {
-			if (send - sp < 4)
-				return -EINVAL;
-			flags = mem_read32(sp);
-			sp += 4;
-			flag_count = 32;
-		}
-
-		if (!(flags & 0x80000000)) {
-			if (sp >= send)
-				return -EINVAL;
-			*dp++ = *sp++;
-			flags <<= 1;
-			flag_count--;
-			continue;
-		}
+	const void *srcp, *end, *nib = NULL;
+	void *dstp, *dst_end;
 
-		flags <<= 1;
-		flag_count--;
-
-		if (send - sp < 2)
-			return -EINVAL;
+	srcp = src;
+	end = srcp + slen;
+	dstp = dst;
+	dst_end = dstp + dlen;
 
-		token = mem_read16(sp);
-		sp += 2;
+	do {
+		u32 flag, flag_count = LZ77_FLAG_MAX;
 
-		dist = (token >> 3) + 1;
-		if (dist > dp - (u8 *)dst)
-			return -EINVAL;
+		/*
+		 * Read flag.
+		 *
+		 * LZ77 flags are 32-bit bitmaps where 0s indicates a literal in the stream
+		 * (straight copied from @srcp to @dstp) and 1s indicates a match (decoded from
+		 * @srcp).
+		 *
+		 * Compressed payloads always starts with a flag.
+		 */
+		flag = mem_read32(srcp);
+		srcp += SMB_COMPRESS_RSTEP_SIZE;
 
-		if (lz77_decode_match_len(&sp, send, token, &nibble,
-					  &have_nibble, &len))
-			return -EINVAL;
+		do {
+			u32 m, l;
 
-		if (len > dend - dp)
-			return -EINVAL;
+			/*
+			 * Decode flag.
+			 *
+			 * Each bit in @flag represents a literal (0) or a match (1).
+			 * Instead of processing them as individual bits, do it in batches:
+			 *   (@m matches, @l literals)
+			 *
+			 * Count leading zeroes for that (flip @flag bits to compute matches).
+			 *
+			 * Notes:
+			 * - @flag == 0 means we're are bound by @flag_count literals
+			 * - __builtin_clz() yields UB if arg is 0
+			 * - unlike smb_lz77_compress(), we don't use a 'long' flag here because
+			 *   of CLZ (in order to avoid extra math (sizeof(long) == 8))
+			 * - we can't rely on bit counting alone as bound-checking because the
+			 *   final flag in compressed payload might contain lots of 1s
+			 *   (((1 << (32 - @flag_count)) - 1), cf. smb_lz77_compress()).
+			 *
+			 * Also, matches can be encoded from 2 up to 10 bytes each, and since we
+			 * don't know the size of each match beforehand, we can't determine a
+			 * fixed limit, so we have to check @srcp limits before each match read.
+			 */
+			m = flag ? __builtin_clz(~flag) : 0;
+			flag_count -= m;
+			flag <<= m;
+
+			l = flag ? umin(__builtin_clz(flag), flag_count) : flag_count;
+			flag_count -= l;
+			flag <<= l;
+
+			/* Decoding bug (or, unlikely, __builtin_clz() bug) */
+			if (WARN_ON_ONCE(l + m > LZ77_FLAG_MAX))
+				return -EIO;
+
+			while (m--) {
+				const void *match;
+				u32 dist, len;
+
+				/*
+				 * Final flag done (not a bug).
+				 *
+				 * Note that even if we reached here (@m wasn't 0), we can't rely
+				 * on that value alone as a "true match flag counter" because of
+				 * how the last flag is encoded (cf. smb_lz77_compress()).
+				 */
+				if (unlikely(srcp + sizeof(u16) > end))
+					goto out;
+
+				/* Store match symbol in @len */
+				len = mem_read16(srcp);
+				srcp += sizeof(u16);
+				dist = (len >> 3) + 1;
+				srcp = lz77_decode_match_len(srcp, end, &nib, &len);
+				if (unlikely(!srcp))
+					return -EFAULT;
+
+				/*
+				 * Check bogus match values.
+				 *
+				 * We don't know what compression parameters (e.g. match max dist,
+				 * min len) the server is using, so check against limits allowed
+				 * by spec.
+				 *
+				 * Also check if within @dst boundaries so we can do a straight
+				 * copy.
+				 */
+				if (unlikely(!dist || dist > SZ_8K || dstp - dst < dist))
+					return -EFAULT;
+
+				if (unlikely(len < 3 || len == U32_MAX || dstp + len > dst_end))
+					return -EFAULT;
+
+				/*
+				 * If non-overlapping memory, we can use memcpy() (common case).
+				 * Otherwise, we have to do it byte by byte.
+				 *
+				 * Note @match is always behind @dstp (@dist is at least 1).
+				 */
+				match = dstp - dist;
+				if (likely(len < dist)) {
+					memcpy(dstp, match, len);
+					dstp += len;
+				} else {
+					while (len--)
+						mem_write8(dstp++, mem_read8(match++));
+				}
+			}
 
-		while (len--) {
-			*dp = *(dp - dist);
-			dp++;
-		}
-	}
+			if (l) {
+				if (unlikely(srcp + l > end || dstp + l > dst_end))
+					return -EFAULT;
 
+				memcpy(dstp, srcp, l);
+				srcp += l;
+				dstp += l;
+			}
+		} while (flag_count);
+	} while (srcp + SMB_COMPRESS_RSTEP_SIZE <= end);
+out:
+	/*
+	 * We've now fully parsed the compressed buffer without any processing errors.
+	 * However, it's up to callers to determine the validity of @dst.
+	 */
 	return 0;
 }
 EXPORT_SYMBOL_GPL(smb_lz77_decompress);
Signature · 1 line
2.54.0
#7 lore raw

PATCH 8/10 smb: common: compress: implement LZ77-Huffman

In reply to Enzo Matsumiya

Implement LZ77-Huffman compression algorithm as per MS-XCA.

Huffman encoding adds a few extra passes on top of LZ77-style encoding in order to provide better compression ratio (at bit level rather than byte level).

Refer to MS-XCA spec or code/comments in huffman.* for details.

Changes:
- add huffman.{h,c} with implementation
- adjust server/ and client/ code to support new alg
- compress.c::smb_compression_add_lz77():
rename it to smb_compression_add_lz() and it now takes an @alg arg, so it handles both LZ77 and LZ77-Huffman (which are handled the same way in that regard)
- compress.h::smb_compress_alloc_size(): add @lzalg arg to account for LZ77-Huffman allocation requirements
- rename smb_decompress_lz77_payload() to smb_decompress_lz_payload() so it now handles both LZ77 plain and Huffman variants (handled the same way), it also now takes an @alg argument to determine which one to use
- add LZ77-Huffman to smb_compress_alg_valid()

---
 fs/smb/client/compress.c          |  20 +-
 fs/smb/client/smb2pdu.c           |  22 +-
 fs/smb/common/Makefile            |   2 +-
 fs/smb/common/compress/compress.c |  55 +-
 fs/smb/common/compress/compress.h |  23 +-
 fs/smb/common/compress/huffman.c  | 877 ++++++++++++++++++++++++++++++
 fs/smb/common/compress/huffman.h  |  26 +
 fs/smb/server/compress.c          |   9 +-
 fs/smb/server/smb2pdu.c           |  27 +-
 9 files changed, 1011 insertions(+), 50 deletions(-)
 create mode 100644 fs/smb/common/compress/huffman.c
 create mode 100644 fs/smb/common/compress/huffman.h
fs/smb/client/compress.c +15 -5
index d94bacf3edbd..76a44ce49261 100644
@@ -227,14 +227,16 @@ static int check_compressible_chunks(const u8 *buf, const u32 len, u32 *freqs)
 /*
  * Check @buf heuristics (entropy/distribution) to determine its compressibility level.
  *
+ * If @maybe_ok is false, alias MAYBE_COMPRESSIBLE to UNCOMPRESSIBLE.
+ *
  * Tests shows that this function is quite reliable in predicting data compressibility, matching
- * very close with the behaviour of LZ77 compression success and failures.
+ * very close with the behaviour of LZ* compression success and failures.
  *
  * This function allocates memory, callers must check for -ENOMEM.
  *
  * Return: one of the *COMPRESSIBLE values on success, -errno otherwise.
  */
-static __must_check int check_compressible(const u8 *buf, u32 len)
+static __must_check int check_compressible(const u8 *buf, u32 len, bool maybe_ok)
 {
 	u32 entropy, *freqs, rle = 0, rle_boost = 0;
 	const u32 min_reps = (len / 100); /* ~1% of @len */
@@ -296,6 +298,9 @@ static __must_check int check_compressible(const u8 *buf, u32 len)
 
 	kfree(freqs);
 
+	if (!maybe_ok && ret == MAYBE_COMPRESSIBLE)
+		ret = UNCOMPRESSIBLE;
+
 	return ret;
 }
 
@@ -340,6 +345,7 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s
 	struct iov_iter iter;
 	u32 slen, dlen, shdr_len;
 	void *src, *dst = NULL;
+	__le16 lzalg;
 	bool use_pattern;
 	int ret;
 
@@ -349,6 +355,10 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s
 	if (rq->rq_iov->iov_len != sizeof(struct smb2_write_req))
 		return -EINVAL;
 
+	lzalg = server->compression.alg;
+	if (unlikely(!smb_compress_alg_valid(lzalg, false)))
+		return -EINVAL;
+
 	slen = iov_iter_count(&rq->rq_iter);
 	src = kvzalloc(slen, GFP_KERNEL);
 	if (!src) {
@@ -372,7 +382,7 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s
 	 * uncompressible low-hanging fruits here and let smb_lz77_compress() handle the
 	 * exceptions/rare cases.
 	 */
-	ret = check_compressible(src, slen);
+	ret = check_compressible(src, slen, lzalg == SMB3_COMPRESS_LZ77_HUFF);
 
 	/* XXX: do something with MAYBE_COMPRESSIBLE */
 	if (ret != COMPRESSIBLE) {
@@ -383,14 +393,14 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s
 
 	use_pattern = server->compression.pattern;
 	shdr_len = rq->rq_iov[0].iov_len;
-	dlen = smb_compress_alloc_size(slen, use_pattern) + shdr_len;
+	dlen = smb_compress_alloc_size(slen, use_pattern, lzalg) + shdr_len;
 	dst = kvzalloc(dlen, GFP_KERNEL);
 	if (!dst) {
 		ret = -ENOMEM;
 		goto err_free;
 	}
 
-	ret = smb_compression_compress(SMB3_COMPRESS_LZ77, server->compression.chained, use_pattern,
+	ret = smb_compression_compress(lzalg, server->compression.chained, use_pattern,
 				       src, slen, dst, &dlen, rq->rq_iov[0].iov_base, shdr_len);
 	if (!ret && dlen < slen) {
 		struct smb_rqst comp_rq = { .rq_nvec = 1, };
fs/smb/client/smb2pdu.c +17 -5
index 41cdc9f5e692..ba2c601f290e 100644
@@ -44,6 +44,7 @@
 #include "cached_dir.h"
 #include "compress.h"
 #include "fs_context.h"
+#include "../common/compress/compress.h"
 
 /*
  *  The following table defines the expected "StructureSize" of SMB2 requests
@@ -859,14 +860,25 @@ static void decode_compress_ctx(struct TCP_Server_Info *server,
 	}
 
 	for (i = 0; i < count; i++) {
-		/* Record the intersection supported by the shared SMB codec. */
-		if (ctxt->CompressionAlgorithms[i] == SMB3_COMPRESS_LZ77)
-			server->compression.alg = SMB3_COMPRESS_LZ77;
-		else if (ctxt->CompressionAlgorithms[i] == SMB3_COMPRESS_PATTERN)
+		__le16 alg = ctxt->CompressionAlgorithms[i];
+
+		/*
+		 * Servers only return 1 LZ* algorithm, or + Pattern_V1 if chained.
+		 * server->compression.alg only tracks LZ* algs.
+		 */
+		if (alg == SMB3_COMPRESS_PATTERN)
 			server->compression.pattern = true;
+		else if (smb_compress_alg_valid(alg, false))
+			server->compression.alg = alg;
+		else
+			pr_warn_once("invalid compression algorithm '0x%04x'\n", le16_to_cpu(alg));
 	}
-	if (server->compression.alg != SMB3_COMPRESS_LZ77)
+
+	if (!server->compression.alg) {
+		memset(&server->compression, 0, sizeof(server->compression));
+		pr_warn_once("no LZ compression algorithm negotiated\n");
 		return;
+	}
 
 	/*
 	 * Pattern_V1 cannot appear in an unchained transform even if a broken
fs/smb/common/Makefile +1 -1
index f2c6e09d4e77..35368807da76 100644
@@ -6,4 +6,4 @@
 obj-$(CONFIG_SMBFS) += cifs_md4.o
 obj-$(CONFIG_SMBFS) += smb_compress.o
 
-smb_compress-y := compress/compress.o compress/lz77.o
+smb_compress-y := compress/compress.o compress/lz77.o compress/huffman.o
fs/smb/common/compress/compress.c +34 -21

123 lines not on this page · raw message

fs/smb/common/compress/compress.h +18 -5
index e1fad498d567..93be0ad732f2 100644
@@ -15,6 +15,7 @@
 #include <linux/slab.h>
 
 #include "../smb2pdu.h"
+#include "huffman.h"
 #include "lz77.h"
 
 #define SMB2_COMPRESSION_CHAINED_HDR_LEN \
@@ -139,16 +140,23 @@ static __always_inline u32 smb_compress_hash_ptr(const void *ptr)
  */
 static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)
 {
-	if (alg == SMB3_COMPRESS_NONE)
+	switch (alg) {
+	case SMB3_COMPRESS_NONE:
 		return valid_none;
+	case SMB3_COMPRESS_LZ77:
+	case SMB3_COMPRESS_LZ77_HUFF:
+	case SMB3_COMPRESS_PATTERN:
+		return true;
+	}
 
-	return alg == SMB3_COMPRESS_LZ77 || alg == SMB3_COMPRESS_PATTERN;
+	return false;
 }
 
 /**
  * smb_compress_alloc_size() - Compute total allocation size required for compressed (dst) buffer.
  * @size:		uncompressed size
  * @use_pattern:	if Pattern_V1 is enabled
+ * @lzalg:		LZ* algorithm that will be used
  *
  * For any case:
  * - SMB2 compression hdr
@@ -161,11 +169,16 @@ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)
  *
  * (possible uncompressed leftovers are included in LZ alloc size)
  */
-static __always_inline u32 smb_compress_alloc_size(const u32 size, const bool use_pattern)
+static __always_inline u32 smb_compress_alloc_size(const u32 size, const bool use_pattern,
+						   const __le16 lzalg)
 {
-	u32 alloc_size;
+	u32 alloc_size = sizeof(struct smb2_compression_hdr);
+
+	if (lzalg == SMB3_COMPRESS_LZ77)
+		alloc_size += smb_lz77_compressed_alloc_size(size);
+	else if (lzalg == SMB3_COMPRESS_LZ77_HUFF)
+		alloc_size += smb_huff_compressed_alloc_size(size);
 
-	alloc_size = sizeof(struct smb2_compression_hdr) + smb_lz77_compressed_alloc_size(size);
 	if (use_pattern)
 		alloc_size += (SMB2_COMPRESSION_PAYLOAD_BASE_LEN * 3) +
 			(sizeof(struct smb2_compression_pattern_v1) * 2);
fs/smb/common/compress/huffman.c new file +877 -0

877 lines not on this page · raw message

fs/smb/common/compress/huffman.h new file +26 -0
new file mode 100644
index 000000000000..184de5fb6d59
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2026, SUSE LLC
+ *
+ * Authors: Enzo Matsumiya <[email protected]>
+ *
+ * Implementation of the LZ77+Huffman compression algorithm, as per MS-XCA spec.
+ */
+#ifndef _SMB_COMPRESS_LZ77_HUFF_H
+#define _SMB_COMPRESS_LZ77_HUFF_H
+
+#include <linux/kernel.h>
+
+/*
+ * LZ77-Huffman metadata is Huffman table (256 bytes) at the beginning of every 64k block, so:
+ *
+ * metadata = ((@size / 64k) * 256), or simplified (@size >> 8)
+ */
+static __always_inline u32 smb_huff_compressed_alloc_size(const u32 size)
+{
+	return size + (size >> 8);
+}
+
+int smb_huff_compress(const void *src, const u32 slen, void *dst, u32 *dlen);
+int smb_huff_decompress(const void *src, const u32 slen, void *dst, const u32 dlen);
+#endif /* _SMB_COMPRESS_LZ77_HUFF_H */
fs/smb/server/compress.c +5 -4
index 648660f8bfab..5d6edbb427d7 100644
@@ -98,10 +98,11 @@ int ksmbd_compress_response(struct ksmbd_work *work)
 	struct smb2_hdr *req_hdr;
 	u32 src_len, dst_len, compressed_pdu_len, max_dst_len;
 	u8 *src = NULL, *out = NULL, *p;
+	__le16 alg = work->conn->compress_algorithm;
 	int i, rc;
 
 	if (!work->compress_response || work->encrypted ||
-	    work->conn->compress_algorithm != SMB3_COMPRESS_LZ77)
+	    smb_compress_alg_valid(alg, false))
 		return 0;
 
 	req_hdr = smb_get_msg(work->request_buf);
@@ -132,7 +133,7 @@ int ksmbd_compress_response(struct ksmbd_work *work)
 		goto out;
 	}
 
-	max_dst_len = smb_compress_alloc_size(src_len, work->conn->compress_pattern);
+	max_dst_len = smb_compress_alloc_size(src_len, work->conn->compress_pattern, alg);
 	out = kvzalloc(sizeof(__be32) + max_dst_len,
 		       KSMBD_DEFAULT_GFP);
 	if (!out) {
@@ -142,7 +143,7 @@ int ksmbd_compress_response(struct ksmbd_work *work)
 
 	if (work->conn->compress_chained) {
 		dst_len = max_dst_len;
-		rc = smb_compression_compress(SMB3_COMPRESS_LZ77,
+		rc = smb_compression_compress(alg,
 					      work->conn->compress_chained,
 					      work->conn->compress_pattern,
 					      src, src_len,
@@ -169,7 +170,7 @@ int ksmbd_compress_response(struct ksmbd_work *work)
 		chdr = (struct smb2_compression_hdr *)(out + sizeof(__be32));
 		chdr->ProtocolId = SMB2_COMPRESSION_TRANSFORM_ID;
 		chdr->OriginalCompressedSegmentSize = cpu_to_le32(src_len);
-		chdr->CompressionAlgorithm = SMB3_COMPRESS_LZ77;
+		chdr->CompressionAlgorithm = alg;
 		chdr->Flags = cpu_to_le16(SMB2_COMPRESSION_FLAG_NONE);
 		chdr->Offset = 0;
 	}
fs/smb/server/smb2pdu.c +18 -9
index 5859fa68bb84..3bd62c16ae49 100644
@@ -1130,18 +1130,27 @@ static __le32 decode_compress_ctxt(struct ksmbd_conn *conn,
 		__le16 alg = algs[i];
 
 		/*
-		 * LZ77 is the required general-purpose codec. Pattern_V1 is an
+		 * LZ* are the required general-purpose codecs. Pattern_V1 is an
 		 * optional chained payload type and cannot stand alone.
+		 *
+		 * Use the first LZ algorithm found in the request array.  It's sorted by
+		 * client-preferred order, so don't overwrite it if already set.
 		 */
-		if (alg == SMB3_COMPRESS_LZ77) {
-			conn->compress_algorithm = alg;
-			conn->compress_chained =
-				pneg_ctxt->Flags ==
-				SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED;
-			ksmbd_debug(SMB, "Compression Algorithm ID = 0x%x\n",
-				    le16_to_cpu(alg));
-		} else if (alg == SMB3_COMPRESS_PATTERN) {
+		switch (alg) {
+		case SMB3_COMPRESS_LZ77:
+		case SMB3_COMPRESS_LZ77_HUFF:
+			if (conn->compress_algorithm == SMB3_COMPRESS_NONE) {
+				conn->compress_algorithm = alg;
+				conn->compress_chained =
+					pneg_ctxt->Flags ==
+					SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED;
+				ksmbd_debug(SMB, "Compression Algorithm ID = 0x%x\n",
+					    le16_to_cpu(alg));
+			}
+			break;
+		case SMB3_COMPRESS_PATTERN:
 			conn->compress_pattern = true;
+			break;
 		}
 	}
 
Signature · 1 line
2.54.0
#8 lore raw

PATCH 9/10 smb: client: add support for decompressing READs

In reply to Enzo Matsumiya

Implement decompression support for SMB2 READ messages.

Changes:
- add smb2ops.c::receive_compressed()
- add check_decompress() helper in smb2ops.c
- smb/common/compress/compress.h: add is_compress_hdr() and decompressed_size() helpers
- check for compress header in smb3_is_transform_hdr() as well so we fall into the same path handling offloaded READ decryption

---
 fs/smb/client/smb2ops.c           | 145 +++++++++++++++++++++++++++++-
 fs/smb/client/smb2pdu.c           |   6 ++
 fs/smb/common/compress/compress.h |  27 ++++++
 3 files changed, 177 insertions(+), 1 deletion(-)
fs/smb/client/smb2ops.c +144 -1
index d60bc537ecf1..e05dbf02d3b7 100644
@@ -30,6 +30,8 @@
 #include "fs_context.h"
 #include "cached_dir.h"
 #include "reparse.h"
+#include "../common/compress/compress.h"
+#include "compress.h"
 
 /* Change credits for different ops and return the total number of credits */
 static int
@@ -4714,7 +4716,7 @@ smb3_is_transform_hdr(void *buf)
 {
 	struct smb2_transform_hdr *trhdr = buf;
 
-	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
+	return (trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM) || is_compress_hdr(buf);
 }
 
 static int
@@ -5246,6 +5248,136 @@ receive_encrypted_standard(struct TCP_Server_Info *server,
 	return ret;
 }
 
+static int receive_compressed(struct TCP_Server_Info *server)
+{
+	struct mid_q_entry *mid;
+	void *src, *dst = NULL;
+	u32 slen, dlen;
+	int ret;
+
+	slen = server->pdu_size;
+	src = kvzalloc(slen, GFP_KERNEL);
+	if (unlikely(!src))
+		return -ENOMEM;
+
+	ret = server->total_read;
+	memcpy(src, server->smallbuf, ret);
+
+	ret = cifs_read_from_socket(server, src + ret, slen - ret);
+	if (ret < 0)
+		goto err_free;
+
+	server->total_read += ret;
+
+	dlen = decompressed_size(src);
+	dst = kvzalloc(dlen, GFP_KERNEL);
+	if (unlikely(!dst)) {
+		ret = -ENOMEM;
+
+		goto err_free;
+	}
+
+	ret = smb_compression_decompress(server->compression.alg, server->compression.pattern,
+					 src, slen, dst, dlen);
+	if (likely(!ret)) {
+		const struct smb2_hdr *shdr = dst;
+
+		if (unlikely(shdr->ProtocolId != SMB2_PROTO_NUMBER)) {
+			cifs_dbg(VFS, "decompressed message is not an SMB2 message (got ProtocolId 0x%x)\n",
+				 shdr->ProtocolId);
+			ret = -ECONNRESET;
+			goto err_free;
+		}
+	} else {
+		/*
+		 * We _must_ disconnect on any failed decompression.
+		 * Actually, there's not much we can do to handle different decompression errors
+		 * here, so forcing a reconnect (which will disable compression) is our best option
+		 * as the request should be retried.
+		 */
+		ret = -ECONNRESET;
+		goto err_free;
+	}
+
+	mid = smb2_find_dequeue_mid(server, dst);
+	if (!mid) {
+		ret = -EIO;
+
+		goto err_free;
+	}
+
+	ret = handle_read_data(server, mid, dst, dlen, NULL, 0, true);
+	if (!ret) {
+		struct cifs_io_subrequest *rdata = mid->callback_data;
+#ifdef CONFIG_CIFS_STATS2
+		mid->when_received = jiffies;
+#endif
+		if (server->ops->is_network_name_deleted)
+			server->ops->is_network_name_deleted(dst, server);
+
+		rdata->iov[0].iov_base = dst;
+		rdata->iov[0].iov_len = server->vals->read_rsp_size;
+		mid_execute_callback(server, mid);
+	} else {
+		spin_lock(&server->srv_lock);
+		if (server->tcpStatus == CifsNeedReconnect) {
+			spin_lock(&server->mid_queue_lock);
+			mid->mid_state = MID_RETRY_NEEDED;
+			spin_unlock(&server->mid_queue_lock);
+			spin_unlock(&server->srv_lock);
+
+			mid_execute_callback(server, mid);
+		} else {
+			spin_lock(&server->mid_queue_lock);
+			mid->mid_state = MID_REQUEST_SUBMITTED;
+			mid->deleted_from_q = false;
+			list_add_tail(&mid->qhead, &server->pending_mid_q);
+			spin_unlock(&server->mid_queue_lock);
+			spin_unlock(&server->srv_lock);
+		}
+	}
+
+	release_mid(server, mid);
+err_free:
+	kvfree(src);
+	kvfree(dst);
+
+	if (unlikely(ret == -ECONNRESET)) {
+		spin_lock(&server->srv_lock);
+		server->tcpStatus = CifsNeedReconnect;
+		spin_unlock(&server->srv_lock);
+	}
+
+	return ret;
+}
+
+static inline int check_decompress(struct TCP_Server_Info *server, const void *buf)
+{
+	const u32 len = decompressed_size(buf);
+	u32 max_len;
+
+	if (len == 0)
+		return 0;
+
+	if (WARN_ON_ONCE(!server))
+		return -EINVAL;
+
+	if (unlikely(len < server->vals->read_rsp_size)) {
+		cifs_server_dbg(VFS, "uncompressed message too small (%u, min %zu)\n", len,
+				server->vals->read_rsp_size);
+		return -EINVAL;
+	}
+
+	max_len = 256 + SMB2_COMPRESSION_PAYLOAD_BASE_LEN +
+		  max3(server->maxBuf, server->max_read, server->max_write);
+	if (unlikely(len > max_len)) {
+		cifs_server_dbg(VFS, "uncompressed message too big (%u, max %u)\n", len, max_len);
+		return -EINVAL;
+	}
+
+	return 1;
+}
+
 static int
 smb3_receive_transform(struct TCP_Server_Info *server,
 		       struct mid_q_entry **mids, char **bufs, int *num_mids)
@@ -5254,6 +5386,15 @@ smb3_receive_transform(struct TCP_Server_Info *server,
 	unsigned int pdu_length = server->pdu_size;
 	struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
 	unsigned int orig_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
+	int ret;
+
+	ret = check_decompress(server, buf);
+	if (ret > 0)
+		return receive_compressed(server);
+
+	if (unlikely(ret < 0))
+		/* Reset connection on any error */
+		return -ECONNABORTED;
 
 	if (pdu_length < sizeof(struct smb2_transform_hdr) +
 						sizeof(struct smb2_hdr)) {
@@ -5296,6 +5437,8 @@ static int smb2_next_header(struct TCP_Server_Info *server, char *buf,
 		*noff = le32_to_cpu(t_hdr->OriginalMessageSize);
 		if (unlikely(check_add_overflow(*noff, sizeof(*t_hdr), noff)))
 			return -EINVAL;
+	} else if (hdr->ProtocolId == SMB2_COMPRESSION_TRANSFORM_ID) {
+		*noff = 0;
 	} else {
 		*noff = le32_to_cpu(hdr->NextCommand);
 	}
fs/smb/client/smb2pdu.c +6 -0
index ba2c601f290e..a94f0c0cf8de 100644
@@ -4880,6 +4880,12 @@ smb2_async_readv(struct cifs_io_subrequest *rdata)
 		flags |= CIFS_HAS_CREDITS;
 	}
 
+	if (should_compress(io_parms.tcon, &rqst)) {
+		struct smb2_read_req *req = (struct smb2_read_req *)buf;
+
+		req->Flags |= SMB2_READFLAG_REQUEST_COMPRESSED;
+	}
+
 	rc = cifs_call_async(server, &rqst,
 			     cifs_readv_receive, smb2_readv_callback,
 			     smb3_handle_read_data, rdata, flags,
fs/smb/common/compress/compress.h +27 -0
index 93be0ad732f2..adc8b11910cf 100644
@@ -152,6 +152,33 @@ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)
 	return false;
 }
 
+static __always_inline bool is_compress_hdr(const void *buf)
+{
+	const struct smb2_compression_hdr *hdr = buf;
+
+	if (!buf)
+		return false;
+
+	return (hdr->ProtocolId == SMB2_COMPRESSION_TRANSFORM_ID);
+}
+
+static __always_inline u32 decompressed_size(const void *buf)
+{
+	const struct smb2_compression_hdr *hdr = buf;
+	u32 len;
+
+	if (!buf || !is_compress_hdr(buf))
+		return 0;
+
+	len = le32_to_cpu(hdr->OriginalCompressedSegmentSize);
+
+	/* When unchained, we must account for the offset part (usually SMB2 header) as well. */
+	if (le16_to_cpu(hdr->Flags) == SMB2_COMPRESSION_FLAG_NONE)
+		len += le32_to_cpu(hdr->Offset);
+
+	return len;
+}
+
 /**
  * smb_compress_alloc_size() - Compute total allocation size required for compressed (dst) buffer.
  * @size:		uncompressed size
Signature · 1 line
2.54.0
#9 lore raw

PATCH 10/10 smb: client: mark compression as supported on 64-bit LE only

In reply to Enzo Matsumiya

Other architectures require more tuning + tests, even more so to maintain the same performance.

So for now, mark SMB2 compression as supported only on 64-bit little endian architectures.

---
 fs/smb/client/fs_context.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
fs/smb/client/fs_context.c +8 -2
index abc29500a664..022d12da809c 100644
@@ -1289,8 +1289,14 @@ static int smb3_fs_context_parse_param(struct fs_context *fc,
 			cifs_errorf(fc, "CONFIG_CIFS_COMPRESSION kernel config option is unset\n");
 			goto cifs_parse_mount_err;
 		}
-		ctx->compress = true;
-		cifs_dbg(VFS, "SMB3 compression support is experimental\n");
+
+		/* This is more of a "TODO" than a final statement */
+		if (BITS_PER_LONG < 64 || 0x1234 != cpu_to_le16(0x1234)) {
+			cifs_dbg(VFS, "SMB3 compression is currently only supported on 64-bit little endian architectures, disabling\n");
+		} else {
+			ctx->compress = true;
+			cifs_dbg(VFS, "SMB3 compression support is experimental\n");
+		}
 		break;
 	case Opt_nodfs:
 		ctx->nodfs = 1;
Signature · 1 line
2.54.0