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