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