1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Generic Reed Solomon encoder / decoder library
4  *
5  * Copyright (C) 2004 Thomas Gleixner (tglx@linutronix.de)
6  *
7  * Reed Solomon code lifted from reed solomon library written by Phil Karn
8  * Copyright 2002 Phil Karn, KA9Q
9  *
10  * Description:
11  *
12  * The generic Reed Solomon library provides runtime configurable
13  * encoding / decoding of RS codes.
14  *
15  * Each user must call init_rs to get a pointer to a rs_control structure
16  * for the given rs parameters. The control struct is unique per instance.
17  * It points to a codec which can be shared by multiple control structures.
18  * If a codec is newly allocated then the polynomial arrays for fast
19  * encoding / decoding are built. This can take some time so make sure not
20  * to call this function from a time critical path.  Usually a module /
21  * driver should initialize the necessary rs_control structure on module /
22  * driver init and release it on exit.
23  *
24  * The encoding puts the calculated syndrome into a given syndrome buffer.
25  *
26  * The decoding is a two step process. The first step calculates the
27  * syndrome over the received (data + syndrome) and calls the second stage,
28  * which does the decoding / error correction itself.  Many hw encoders
29  * provide a syndrome calculation over the received data + syndrome and can
30  * call the second stage directly.
31  */
32 #include <linux/errno.h>
33 #include <linux/kernel.h>
34 #include <linux/init.h>
35 #include <linux/module.h>
36 #include <linux/rslib.h>
37 #include <linux/slab.h>
38 #include <linux/mutex.h>
39 
40 /* This list holds all currently allocated rs codec structures */
41 static LIST_HEAD(codec_list);
42 /* Protection for the list */
43 static DEFINE_MUTEX(rslistlock);
44 
45 /**
46  * codec_init - Initialize a Reed-Solomon codec
47  * @symsize:	symbol size, bits (1-8)
48  * @gfpoly:	Field generator polynomial coefficients
49  * @gffunc:	Field generator function
50  * @fcr:	first root of RS code generator polynomial, index form
51  * @prim:	primitive element to generate polynomial roots
52  * @nroots:	RS code generator polynomial degree (number of roots)
53  * @gfp:	GFP_ flags for allocations
54  *
55  * Allocate a codec structure and the polynom arrays for faster
56  * en/decoding. Fill the arrays according to the given parameters.
57  */
58 static struct rs_codec *codec_init(int symsize, int gfpoly, int (*gffunc)(int),
59 				   int fcr, int prim, int nroots, gfp_t gfp)
60 {
61 	int i, j, sr, root, iprim;
62 	struct rs_codec *rs;
63 
64 	rs = kzalloc(sizeof(*rs), gfp);
65 	if (!rs)
66 		return NULL;
67 
68 	INIT_LIST_HEAD(&rs->list);
69 
70 	rs->mm = symsize;
71 	rs->nn = (1 << symsize) - 1;
72 	rs->fcr = fcr;
73 	rs->prim = prim;
74 	rs->nroots = nroots;
75 	rs->gfpoly = gfpoly;
76 	rs->gffunc = gffunc;
77 
78 	/* Allocate the arrays */
79 	rs->alpha_to = kmalloc(sizeof(uint16_t) * (rs->nn + 1), gfp);
80 	if (rs->alpha_to == NULL)
81 		goto err;
82 
83 	rs->index_of = kmalloc(sizeof(uint16_t) * (rs->nn + 1), gfp);
84 	if (rs->index_of == NULL)
85 		goto err;
86 
87 	rs->genpoly = kmalloc(sizeof(uint16_t) * (rs->nroots + 1), gfp);
88 	if(rs->genpoly == NULL)
89 		goto err;
90 
91 	/* Generate Galois field lookup tables */
92 	rs->index_of[0] = rs->nn;	/* log(zero) = -inf */
93 	rs->alpha_to[rs->nn] = 0;	/* alpha**-inf = 0 */
94 	if (gfpoly) {
95 		sr = 1;
96 		for (i = 0; i < rs->nn; i++) {
97 			rs->index_of[sr] = i;
98 			rs->alpha_to[i] = sr;
99 			sr <<= 1;
100 			if (sr & (1 << symsize))
101 				sr ^= gfpoly;
102 			sr &= rs->nn;
103 		}
104 	} else {
105 		sr = gffunc(0);
106 		for (i = 0; i < rs->nn; i++) {
107 			rs->index_of[sr] = i;
108 			rs->alpha_to[i] = sr;
109 			sr = gffunc(sr);
110 		}
111 	}
112 	/* If it's not primitive, exit */
113 	if(sr != rs->alpha_to[0])
114 		goto err;
115 
116 	/* Find prim-th root of 1, used in decoding */
117 	for(iprim = 1; (iprim % prim) != 0; iprim += rs->nn);
118 	/* prim-th root of 1, index form */
119 	rs->iprim = iprim / prim;
120 
121 	/* Form RS code generator polynomial from its roots */
122 	rs->genpoly[0] = 1;
123 	for (i = 0, root = fcr * prim; i < nroots; i++, root += prim) {
124 		rs->genpoly[i + 1] = 1;
125 		/* Multiply rs->genpoly[] by  @**(root + x) */
126 		for (j = i; j > 0; j--) {
127 			if (rs->genpoly[j] != 0) {
128 				rs->genpoly[j] = rs->genpoly[j -1] ^
129 					rs->alpha_to[rs_modnn(rs,
130 					rs->index_of[rs->genpoly[j]] + root)];
131 			} else
132 				rs->genpoly[j] = rs->genpoly[j - 1];
133 		}
134 		/* rs->genpoly[0] can never be zero */
135 		rs->genpoly[0] =
136 			rs->alpha_to[rs_modnn(rs,
137 				rs->index_of[rs->genpoly[0]] + root)];
138 	}
139 	/* convert rs->genpoly[] to index form for quicker encoding */
140 	for (i = 0; i <= nroots; i++)
141 		rs->genpoly[i] = rs->index_of[rs->genpoly[i]];
142 
143 	rs->users = 1;
144 	list_add(&rs->list, &codec_list);
145 	return rs;
146 
147 err:
148 	kfree(rs->genpoly);
149 	kfree(rs->index_of);
150 	kfree(rs->alpha_to);
151 	kfree(rs);
152 	return NULL;
153 }
154 
155 
156 /**
157  *  free_rs - Free the rs control structure
158  *  @rs:	The control structure which is not longer used by the
159  *		caller
160  *
161  * Free the control structure. If @rs is the last user of the associated
162  * codec, free the codec as well.
163  */
164 void free_rs(struct rs_control *rs)
165 {
166 	struct rs_codec *cd;
167 
168 	if (!rs)
169 		return;
170 
171 	cd = rs->codec;
172 	mutex_lock(&rslistlock);
173 	cd->users--;
174 	if(!cd->users) {
175 		list_del(&cd->list);
176 		kfree(cd->alpha_to);
177 		kfree(cd->index_of);
178 		kfree(cd->genpoly);
179 		kfree(cd);
180 	}
181 	mutex_unlock(&rslistlock);
182 	kfree(rs);
183 }
184 EXPORT_SYMBOL_GPL(free_rs);
185 
186 /**
187  * init_rs_internal - Allocate rs control, find a matching codec or allocate a new one
188  *  @symsize:	the symbol size (number of bits)
189  *  @gfpoly:	the extended Galois field generator polynomial coefficients,
190  *		with the 0th coefficient in the low order bit. The polynomial
191  *		must be primitive;
192  *  @gffunc:	pointer to function to generate the next field element,
193  *		or the multiplicative identity element if given 0.  Used
194  *		instead of gfpoly if gfpoly is 0
195  *  @fcr:	the first consecutive root of the rs code generator polynomial
196  *		in index form
197  *  @prim:	primitive element to generate polynomial roots
198  *  @nroots:	RS code generator polynomial degree (number of roots)
199  *  @gfp:	GFP_ flags for allocations
200  */
201 static struct rs_control *init_rs_internal(int symsize, int gfpoly,
202 					   int (*gffunc)(int), int fcr,
203 					   int prim, int nroots, gfp_t gfp)
204 {
205 	struct list_head *tmp;
206 	struct rs_control *rs;
207 
208 	/* Sanity checks */
209 	if (symsize < 1)
210 		return NULL;
211 	if (fcr < 0 || fcr >= (1<<symsize))
212 		return NULL;
213 	if (prim <= 0 || prim >= (1<<symsize))
214 		return NULL;
215 	if (nroots < 0 || nroots >= (1<<symsize))
216 		return NULL;
217 
218 	rs = kzalloc(sizeof(*rs), GFP_KERNEL);
219 	if (!rs)
220 		return NULL;
221 
222 	mutex_lock(&rslistlock);
223 
224 	/* Walk through the list and look for a matching entry */
225 	list_for_each(tmp, &codec_list) {
226 		struct rs_codec *cd = list_entry(tmp, struct rs_codec, list);
227 
228 		if (symsize != cd->mm)
229 			continue;
230 		if (gfpoly != cd->gfpoly)
231 			continue;
232 		if (gffunc != cd->gffunc)
233 			continue;
234 		if (fcr != cd->fcr)
235 			continue;
236 		if (prim != cd->prim)
237 			continue;
238 		if (nroots != cd->nroots)
239 			continue;
240 		/* We have a matching one already */
241 		cd->users++;
242 		rs->codec = cd;
243 		goto out;
244 	}
245 
246 	/* Create a new one */
247 	rs->codec = codec_init(symsize, gfpoly, gffunc, fcr, prim, nroots, gfp);
248 	if (!rs->codec) {
249 		kfree(rs);
250 		rs = NULL;
251 	}
252 out:
253 	mutex_unlock(&rslistlock);
254 	return rs;
255 }
256 
257 /**
258  * init_rs_gfp - Create a RS control struct and initialize it
259  *  @symsize:	the symbol size (number of bits)
260  *  @gfpoly:	the extended Galois field generator polynomial coefficients,
261  *		with the 0th coefficient in the low order bit. The polynomial
262  *		must be primitive;
263  *  @fcr:	the first consecutive root of the rs code generator polynomial
264  *		in index form
265  *  @prim:	primitive element to generate polynomial roots
266  *  @nroots:	RS code generator polynomial degree (number of roots)
267  *  @gfp:	GFP_ flags for allocations
268  */
269 struct rs_control *init_rs_gfp(int symsize, int gfpoly, int fcr, int prim,
270 			       int nroots, gfp_t gfp)
271 {
272 	return init_rs_internal(symsize, gfpoly, NULL, fcr, prim, nroots, gfp);
273 }
274 EXPORT_SYMBOL_GPL(init_rs_gfp);
275 
276 /**
277  * init_rs_non_canonical - Allocate rs control struct for fields with
278  *                         non-canonical representation
279  *  @symsize:	the symbol size (number of bits)
280  *  @gffunc:	pointer to function to generate the next field element,
281  *		or the multiplicative identity element if given 0.  Used
282  *		instead of gfpoly if gfpoly is 0
283  *  @fcr:	the first consecutive root of the rs code generator polynomial
284  *		in index form
285  *  @prim:	primitive element to generate polynomial roots
286  *  @nroots:	RS code generator polynomial degree (number of roots)
287  */
288 struct rs_control *init_rs_non_canonical(int symsize, int (*gffunc)(int),
289 					 int fcr, int prim, int nroots)
290 {
291 	return init_rs_internal(symsize, 0, gffunc, fcr, prim, nroots,
292 				GFP_KERNEL);
293 }
294 EXPORT_SYMBOL_GPL(init_rs_non_canonical);
295 
296 #ifdef CONFIG_REED_SOLOMON_ENC8
297 /**
298  *  encode_rs8 - Calculate the parity for data values (8bit data width)
299  *  @rsc:	the rs control structure
300  *  @data:	data field of a given type
301  *  @len:	data length
302  *  @par:	parity data, must be initialized by caller (usually all 0)
303  *  @invmsk:	invert data mask (will be xored on data)
304  *
305  *  The parity uses a uint16_t data type to enable
306  *  symbol size > 8. The calling code must take care of encoding of the
307  *  syndrome result for storage itself.
308  */
309 int encode_rs8(struct rs_control *rsc, uint8_t *data, int len, uint16_t *par,
310 	       uint16_t invmsk)
311 {
312 #include "encode_rs.c"
313 }
314 EXPORT_SYMBOL_GPL(encode_rs8);
315 #endif
316 
317 #ifdef CONFIG_REED_SOLOMON_DEC8
318 /**
319  *  decode_rs8 - Decode codeword (8bit data width)
320  *  @rsc:	the rs control structure
321  *  @data:	data field of a given type
322  *  @par:	received parity data field
323  *  @len:	data length
324  *  @s:		syndrome data field (if NULL, syndrome is calculated)
325  *  @no_eras:	number of erasures
326  *  @eras_pos:	position of erasures, can be NULL
327  *  @invmsk:	invert data mask (will be xored on data, not on parity!)
328  *  @corr:	buffer to store correction bitmask on eras_pos
329  *
330  *  The syndrome and parity uses a uint16_t data type to enable
331  *  symbol size > 8. The calling code must take care of decoding of the
332  *  syndrome result and the received parity before calling this code.
333  *  Returns the number of corrected bits or -EBADMSG for uncorrectable errors.
334  */
335 int decode_rs8(struct rs_control *rsc, uint8_t *data, uint16_t *par, int len,
336 	       uint16_t *s, int no_eras, int *eras_pos, uint16_t invmsk,
337 	       uint16_t *corr)
338 {
339 #include "decode_rs.c"
340 }
341 EXPORT_SYMBOL_GPL(decode_rs8);
342 #endif
343 
344 #ifdef CONFIG_REED_SOLOMON_ENC16
345 /**
346  *  encode_rs16 - Calculate the parity for data values (16bit data width)
347  *  @rsc:	the rs control structure
348  *  @data:	data field of a given type
349  *  @len:	data length
350  *  @par:	parity data, must be initialized by caller (usually all 0)
351  *  @invmsk:	invert data mask (will be xored on data, not on parity!)
352  *
353  *  Each field in the data array contains up to symbol size bits of valid data.
354  */
355 int encode_rs16(struct rs_control *rsc, uint16_t *data, int len, uint16_t *par,
356 	uint16_t invmsk)
357 {
358 #include "encode_rs.c"
359 }
360 EXPORT_SYMBOL_GPL(encode_rs16);
361 #endif
362 
363 #ifdef CONFIG_REED_SOLOMON_DEC16
364 /**
365  *  decode_rs16 - Decode codeword (16bit data width)
366  *  @rsc:	the rs control structure
367  *  @data:	data field of a given type
368  *  @par:	received parity data field
369  *  @len:	data length
370  *  @s:		syndrome data field (if NULL, syndrome is calculated)
371  *  @no_eras:	number of erasures
372  *  @eras_pos:	position of erasures, can be NULL
373  *  @invmsk:	invert data mask (will be xored on data, not on parity!)
374  *  @corr:	buffer to store correction bitmask on eras_pos
375  *
376  *  Each field in the data array contains up to symbol size bits of valid data.
377  *  Returns the number of corrected bits or -EBADMSG for uncorrectable errors.
378  */
379 int decode_rs16(struct rs_control *rsc, uint16_t *data, uint16_t *par, int len,
380 		uint16_t *s, int no_eras, int *eras_pos, uint16_t invmsk,
381 		uint16_t *corr)
382 {
383 #include "decode_rs.c"
384 }
385 EXPORT_SYMBOL_GPL(decode_rs16);
386 #endif
387 
388 MODULE_LICENSE("GPL");
389 MODULE_DESCRIPTION("Reed Solomon encoder/decoder");
390 MODULE_AUTHOR("Phil Karn, Thomas Gleixner");
391 
392