dm: core: Require users of devres to include the header
[oweals/u-boot.git] / lib / bch.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Generic binary BCH encoding/decoding library
4  *
5  * Copyright © 2011 Parrot S.A.
6  *
7  * Author: Ivan Djelic <ivan.djelic@parrot.com>
8  *
9  * Description:
10  *
11  * This library provides runtime configurable encoding/decoding of binary
12  * Bose-Chaudhuri-Hocquenghem (BCH) codes.
13  *
14  * Call init_bch to get a pointer to a newly allocated bch_control structure for
15  * the given m (Galois field order), t (error correction capability) and
16  * (optional) primitive polynomial parameters.
17  *
18  * Call encode_bch to compute and store ecc parity bytes to a given buffer.
19  * Call decode_bch to detect and locate errors in received data.
20  *
21  * On systems supporting hw BCH features, intermediate results may be provided
22  * to decode_bch in order to skip certain steps. See decode_bch() documentation
23  * for details.
24  *
25  * Option CONFIG_BCH_CONST_PARAMS can be used to force fixed values of
26  * parameters m and t; thus allowing extra compiler optimizations and providing
27  * better (up to 2x) encoding performance. Using this option makes sense when
28  * (m,t) are fixed and known in advance, e.g. when using BCH error correction
29  * on a particular NAND flash device.
30  *
31  * Algorithmic details:
32  *
33  * Encoding is performed by processing 32 input bits in parallel, using 4
34  * remainder lookup tables.
35  *
36  * The final stage of decoding involves the following internal steps:
37  * a. Syndrome computation
38  * b. Error locator polynomial computation using Berlekamp-Massey algorithm
39  * c. Error locator root finding (by far the most expensive step)
40  *
41  * In this implementation, step c is not performed using the usual Chien search.
42  * Instead, an alternative approach described in [1] is used. It consists in
43  * factoring the error locator polynomial using the Berlekamp Trace algorithm
44  * (BTA) down to a certain degree (4), after which ad hoc low-degree polynomial
45  * solving techniques [2] are used. The resulting algorithm, called BTZ, yields
46  * much better performance than Chien search for usual (m,t) values (typically
47  * m >= 13, t < 32, see [1]).
48  *
49  * [1] B. Biswas, V. Herbert. Efficient root finding of polynomials over fields
50  * of characteristic 2, in: Western European Workshop on Research in Cryptology
51  * - WEWoRC 2009, Graz, Austria, LNCS, Springer, July 2009, to appear.
52  * [2] [Zin96] V.A. Zinoviev. On the solution of equations of degree 10 over
53  * finite fields GF(2^q). In Rapport de recherche INRIA no 2829, 1996.
54  */
55
56 #ifndef USE_HOSTCC
57 #include <common.h>
58 #include <ubi_uboot.h>
59 #include <dm/devres.h>
60
61 #include <linux/bitops.h>
62 #else
63 #include <errno.h>
64 #if defined(__FreeBSD__)
65 #include <sys/endian.h>
66 #elif defined(__APPLE__)
67 #include <machine/endian.h>
68 #include <libkern/OSByteOrder.h>
69 #else
70 #include <endian.h>
71 #endif
72 #include <stdint.h>
73 #include <stdlib.h>
74 #include <string.h>
75
76 #undef cpu_to_be32
77 #if defined(__APPLE__)
78 #define cpu_to_be32 OSSwapHostToBigInt32
79 #else
80 #define cpu_to_be32 htobe32
81 #endif
82 #define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
83 #define kmalloc(size, flags)    malloc(size)
84 #define kzalloc(size, flags)    calloc(1, size)
85 #define kfree free
86 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
87 #endif
88
89 #include <asm/byteorder.h>
90 #include <linux/bch.h>
91
92 #if defined(CONFIG_BCH_CONST_PARAMS)
93 #define GF_M(_p)               (CONFIG_BCH_CONST_M)
94 #define GF_T(_p)               (CONFIG_BCH_CONST_T)
95 #define GF_N(_p)               ((1 << (CONFIG_BCH_CONST_M))-1)
96 #else
97 #define GF_M(_p)               ((_p)->m)
98 #define GF_T(_p)               ((_p)->t)
99 #define GF_N(_p)               ((_p)->n)
100 #endif
101
102 #define BCH_ECC_WORDS(_p)      DIV_ROUND_UP(GF_M(_p)*GF_T(_p), 32)
103 #define BCH_ECC_BYTES(_p)      DIV_ROUND_UP(GF_M(_p)*GF_T(_p), 8)
104
105 #ifndef dbg
106 #define dbg(_fmt, args...)     do {} while (0)
107 #endif
108
109 /*
110  * represent a polynomial over GF(2^m)
111  */
112 struct gf_poly {
113         unsigned int deg;    /* polynomial degree */
114         unsigned int c[0];   /* polynomial terms */
115 };
116
117 /* given its degree, compute a polynomial size in bytes */
118 #define GF_POLY_SZ(_d) (sizeof(struct gf_poly)+((_d)+1)*sizeof(unsigned int))
119
120 /* polynomial of degree 1 */
121 struct gf_poly_deg1 {
122         struct gf_poly poly;
123         unsigned int   c[2];
124 };
125
126 #ifdef USE_HOSTCC
127 #if !defined(__DragonFly__) && !defined(__FreeBSD__) && !defined(__APPLE__)
128 static int fls(int x)
129 {
130         int r = 32;
131
132         if (!x)
133                 return 0;
134         if (!(x & 0xffff0000u)) {
135                 x <<= 16;
136                 r -= 16;
137         }
138         if (!(x & 0xff000000u)) {
139                 x <<= 8;
140                 r -= 8;
141         }
142         if (!(x & 0xf0000000u)) {
143                 x <<= 4;
144                 r -= 4;
145         }
146         if (!(x & 0xc0000000u)) {
147                 x <<= 2;
148                 r -= 2;
149         }
150         if (!(x & 0x80000000u)) {
151                 x <<= 1;
152                 r -= 1;
153         }
154         return r;
155 }
156 #endif
157 #endif
158
159 /*
160  * same as encode_bch(), but process input data one byte at a time
161  */
162 static void encode_bch_unaligned(struct bch_control *bch,
163                                  const unsigned char *data, unsigned int len,
164                                  uint32_t *ecc)
165 {
166         int i;
167         const uint32_t *p;
168         const int l = BCH_ECC_WORDS(bch)-1;
169
170         while (len--) {
171                 p = bch->mod8_tab + (l+1)*(((ecc[0] >> 24)^(*data++)) & 0xff);
172
173                 for (i = 0; i < l; i++)
174                         ecc[i] = ((ecc[i] << 8)|(ecc[i+1] >> 24))^(*p++);
175
176                 ecc[l] = (ecc[l] << 8)^(*p);
177         }
178 }
179
180 /*
181  * convert ecc bytes to aligned, zero-padded 32-bit ecc words
182  */
183 static void load_ecc8(struct bch_control *bch, uint32_t *dst,
184                       const uint8_t *src)
185 {
186         uint8_t pad[4] = {0, 0, 0, 0};
187         unsigned int i, nwords = BCH_ECC_WORDS(bch)-1;
188
189         for (i = 0; i < nwords; i++, src += 4)
190                 dst[i] = (src[0] << 24)|(src[1] << 16)|(src[2] << 8)|src[3];
191
192         memcpy(pad, src, BCH_ECC_BYTES(bch)-4*nwords);
193         dst[nwords] = (pad[0] << 24)|(pad[1] << 16)|(pad[2] << 8)|pad[3];
194 }
195
196 /*
197  * convert 32-bit ecc words to ecc bytes
198  */
199 static void store_ecc8(struct bch_control *bch, uint8_t *dst,
200                        const uint32_t *src)
201 {
202         uint8_t pad[4];
203         unsigned int i, nwords = BCH_ECC_WORDS(bch)-1;
204
205         for (i = 0; i < nwords; i++) {
206                 *dst++ = (src[i] >> 24);
207                 *dst++ = (src[i] >> 16) & 0xff;
208                 *dst++ = (src[i] >>  8) & 0xff;
209                 *dst++ = (src[i] >>  0) & 0xff;
210         }
211         pad[0] = (src[nwords] >> 24);
212         pad[1] = (src[nwords] >> 16) & 0xff;
213         pad[2] = (src[nwords] >>  8) & 0xff;
214         pad[3] = (src[nwords] >>  0) & 0xff;
215         memcpy(dst, pad, BCH_ECC_BYTES(bch)-4*nwords);
216 }
217
218 /**
219  * encode_bch - calculate BCH ecc parity of data
220  * @bch:   BCH control structure
221  * @data:  data to encode
222  * @len:   data length in bytes
223  * @ecc:   ecc parity data, must be initialized by caller
224  *
225  * The @ecc parity array is used both as input and output parameter, in order to
226  * allow incremental computations. It should be of the size indicated by member
227  * @ecc_bytes of @bch, and should be initialized to 0 before the first call.
228  *
229  * The exact number of computed ecc parity bits is given by member @ecc_bits of
230  * @bch; it may be less than m*t for large values of t.
231  */
232 void encode_bch(struct bch_control *bch, const uint8_t *data,
233                 unsigned int len, uint8_t *ecc)
234 {
235         const unsigned int l = BCH_ECC_WORDS(bch)-1;
236         unsigned int i, mlen;
237         unsigned long m;
238         uint32_t w, r[l+1];
239         const uint32_t * const tab0 = bch->mod8_tab;
240         const uint32_t * const tab1 = tab0 + 256*(l+1);
241         const uint32_t * const tab2 = tab1 + 256*(l+1);
242         const uint32_t * const tab3 = tab2 + 256*(l+1);
243         const uint32_t *pdata, *p0, *p1, *p2, *p3;
244
245         if (ecc) {
246                 /* load ecc parity bytes into internal 32-bit buffer */
247                 load_ecc8(bch, bch->ecc_buf, ecc);
248         } else {
249                 memset(bch->ecc_buf, 0, sizeof(r));
250         }
251
252         /* process first unaligned data bytes */
253         m = ((unsigned long)data) & 3;
254         if (m) {
255                 mlen = (len < (4-m)) ? len : 4-m;
256                 encode_bch_unaligned(bch, data, mlen, bch->ecc_buf);
257                 data += mlen;
258                 len  -= mlen;
259         }
260
261         /* process 32-bit aligned data words */
262         pdata = (uint32_t *)data;
263         mlen  = len/4;
264         data += 4*mlen;
265         len  -= 4*mlen;
266         memcpy(r, bch->ecc_buf, sizeof(r));
267
268         /*
269          * split each 32-bit word into 4 polynomials of weight 8 as follows:
270          *
271          * 31 ...24  23 ...16  15 ... 8  7 ... 0
272          * xxxxxxxx  yyyyyyyy  zzzzzzzz  tttttttt
273          *                               tttttttt  mod g = r0 (precomputed)
274          *                     zzzzzzzz  00000000  mod g = r1 (precomputed)
275          *           yyyyyyyy  00000000  00000000  mod g = r2 (precomputed)
276          * xxxxxxxx  00000000  00000000  00000000  mod g = r3 (precomputed)
277          * xxxxxxxx  yyyyyyyy  zzzzzzzz  tttttttt  mod g = r0^r1^r2^r3
278          */
279         while (mlen--) {
280                 /* input data is read in big-endian format */
281                 w = r[0]^cpu_to_be32(*pdata++);
282                 p0 = tab0 + (l+1)*((w >>  0) & 0xff);
283                 p1 = tab1 + (l+1)*((w >>  8) & 0xff);
284                 p2 = tab2 + (l+1)*((w >> 16) & 0xff);
285                 p3 = tab3 + (l+1)*((w >> 24) & 0xff);
286
287                 for (i = 0; i < l; i++)
288                         r[i] = r[i+1]^p0[i]^p1[i]^p2[i]^p3[i];
289
290                 r[l] = p0[l]^p1[l]^p2[l]^p3[l];
291         }
292         memcpy(bch->ecc_buf, r, sizeof(r));
293
294         /* process last unaligned bytes */
295         if (len)
296                 encode_bch_unaligned(bch, data, len, bch->ecc_buf);
297
298         /* store ecc parity bytes into original parity buffer */
299         if (ecc)
300                 store_ecc8(bch, ecc, bch->ecc_buf);
301 }
302
303 static inline int modulo(struct bch_control *bch, unsigned int v)
304 {
305         const unsigned int n = GF_N(bch);
306         while (v >= n) {
307                 v -= n;
308                 v = (v & n) + (v >> GF_M(bch));
309         }
310         return v;
311 }
312
313 /*
314  * shorter and faster modulo function, only works when v < 2N.
315  */
316 static inline int mod_s(struct bch_control *bch, unsigned int v)
317 {
318         const unsigned int n = GF_N(bch);
319         return (v < n) ? v : v-n;
320 }
321
322 static inline int deg(unsigned int poly)
323 {
324         /* polynomial degree is the most-significant bit index */
325         return fls(poly)-1;
326 }
327
328 static inline int parity(unsigned int x)
329 {
330         /*
331          * public domain code snippet, lifted from
332          * http://www-graphics.stanford.edu/~seander/bithacks.html
333          */
334         x ^= x >> 1;
335         x ^= x >> 2;
336         x = (x & 0x11111111U) * 0x11111111U;
337         return (x >> 28) & 1;
338 }
339
340 /* Galois field basic operations: multiply, divide, inverse, etc. */
341
342 static inline unsigned int gf_mul(struct bch_control *bch, unsigned int a,
343                                   unsigned int b)
344 {
345         return (a && b) ? bch->a_pow_tab[mod_s(bch, bch->a_log_tab[a]+
346                                                bch->a_log_tab[b])] : 0;
347 }
348
349 static inline unsigned int gf_sqr(struct bch_control *bch, unsigned int a)
350 {
351         return a ? bch->a_pow_tab[mod_s(bch, 2*bch->a_log_tab[a])] : 0;
352 }
353
354 static inline unsigned int gf_div(struct bch_control *bch, unsigned int a,
355                                   unsigned int b)
356 {
357         return a ? bch->a_pow_tab[mod_s(bch, bch->a_log_tab[a]+
358                                         GF_N(bch)-bch->a_log_tab[b])] : 0;
359 }
360
361 static inline unsigned int gf_inv(struct bch_control *bch, unsigned int a)
362 {
363         return bch->a_pow_tab[GF_N(bch)-bch->a_log_tab[a]];
364 }
365
366 static inline unsigned int a_pow(struct bch_control *bch, int i)
367 {
368         return bch->a_pow_tab[modulo(bch, i)];
369 }
370
371 static inline int a_log(struct bch_control *bch, unsigned int x)
372 {
373         return bch->a_log_tab[x];
374 }
375
376 static inline int a_ilog(struct bch_control *bch, unsigned int x)
377 {
378         return mod_s(bch, GF_N(bch)-bch->a_log_tab[x]);
379 }
380
381 /*
382  * compute 2t syndromes of ecc polynomial, i.e. ecc(a^j) for j=1..2t
383  */
384 static void compute_syndromes(struct bch_control *bch, uint32_t *ecc,
385                               unsigned int *syn)
386 {
387         int i, j, s;
388         unsigned int m;
389         uint32_t poly;
390         const int t = GF_T(bch);
391
392         s = bch->ecc_bits;
393
394         /* make sure extra bits in last ecc word are cleared */
395         m = ((unsigned int)s) & 31;
396         if (m)
397                 ecc[s/32] &= ~((1u << (32-m))-1);
398         memset(syn, 0, 2*t*sizeof(*syn));
399
400         /* compute v(a^j) for j=1 .. 2t-1 */
401         do {
402                 poly = *ecc++;
403                 s -= 32;
404                 while (poly) {
405                         i = deg(poly);
406                         for (j = 0; j < 2*t; j += 2)
407                                 syn[j] ^= a_pow(bch, (j+1)*(i+s));
408
409                         poly ^= (1 << i);
410                 }
411         } while (s > 0);
412
413         /* v(a^(2j)) = v(a^j)^2 */
414         for (j = 0; j < t; j++)
415                 syn[2*j+1] = gf_sqr(bch, syn[j]);
416 }
417
418 static void gf_poly_copy(struct gf_poly *dst, struct gf_poly *src)
419 {
420         memcpy(dst, src, GF_POLY_SZ(src->deg));
421 }
422
423 static int compute_error_locator_polynomial(struct bch_control *bch,
424                                             const unsigned int *syn)
425 {
426         const unsigned int t = GF_T(bch);
427         const unsigned int n = GF_N(bch);
428         unsigned int i, j, tmp, l, pd = 1, d = syn[0];
429         struct gf_poly *elp = bch->elp;
430         struct gf_poly *pelp = bch->poly_2t[0];
431         struct gf_poly *elp_copy = bch->poly_2t[1];
432         int k, pp = -1;
433
434         memset(pelp, 0, GF_POLY_SZ(2*t));
435         memset(elp, 0, GF_POLY_SZ(2*t));
436
437         pelp->deg = 0;
438         pelp->c[0] = 1;
439         elp->deg = 0;
440         elp->c[0] = 1;
441
442         /* use simplified binary Berlekamp-Massey algorithm */
443         for (i = 0; (i < t) && (elp->deg <= t); i++) {
444                 if (d) {
445                         k = 2*i-pp;
446                         gf_poly_copy(elp_copy, elp);
447                         /* e[i+1](X) = e[i](X)+di*dp^-1*X^2(i-p)*e[p](X) */
448                         tmp = a_log(bch, d)+n-a_log(bch, pd);
449                         for (j = 0; j <= pelp->deg; j++) {
450                                 if (pelp->c[j]) {
451                                         l = a_log(bch, pelp->c[j]);
452                                         elp->c[j+k] ^= a_pow(bch, tmp+l);
453                                 }
454                         }
455                         /* compute l[i+1] = max(l[i]->c[l[p]+2*(i-p]) */
456                         tmp = pelp->deg+k;
457                         if (tmp > elp->deg) {
458                                 elp->deg = tmp;
459                                 gf_poly_copy(pelp, elp_copy);
460                                 pd = d;
461                                 pp = 2*i;
462                         }
463                 }
464                 /* di+1 = S(2i+3)+elp[i+1].1*S(2i+2)+...+elp[i+1].lS(2i+3-l) */
465                 if (i < t-1) {
466                         d = syn[2*i+2];
467                         for (j = 1; j <= elp->deg; j++)
468                                 d ^= gf_mul(bch, elp->c[j], syn[2*i+2-j]);
469                 }
470         }
471         dbg("elp=%s\n", gf_poly_str(elp));
472         return (elp->deg > t) ? -1 : (int)elp->deg;
473 }
474
475 /*
476  * solve a m x m linear system in GF(2) with an expected number of solutions,
477  * and return the number of found solutions
478  */
479 static int solve_linear_system(struct bch_control *bch, unsigned int *rows,
480                                unsigned int *sol, int nsol)
481 {
482         const int m = GF_M(bch);
483         unsigned int tmp, mask;
484         int rem, c, r, p, k, param[m];
485
486         k = 0;
487         mask = 1 << m;
488
489         /* Gaussian elimination */
490         for (c = 0; c < m; c++) {
491                 rem = 0;
492                 p = c-k;
493                 /* find suitable row for elimination */
494                 for (r = p; r < m; r++) {
495                         if (rows[r] & mask) {
496                                 if (r != p) {
497                                         tmp = rows[r];
498                                         rows[r] = rows[p];
499                                         rows[p] = tmp;
500                                 }
501                                 rem = r+1;
502                                 break;
503                         }
504                 }
505                 if (rem) {
506                         /* perform elimination on remaining rows */
507                         tmp = rows[p];
508                         for (r = rem; r < m; r++) {
509                                 if (rows[r] & mask)
510                                         rows[r] ^= tmp;
511                         }
512                 } else {
513                         /* elimination not needed, store defective row index */
514                         param[k++] = c;
515                 }
516                 mask >>= 1;
517         }
518         /* rewrite system, inserting fake parameter rows */
519         if (k > 0) {
520                 p = k;
521                 for (r = m-1; r >= 0; r--) {
522                         if ((r > m-1-k) && rows[r])
523                                 /* system has no solution */
524                                 return 0;
525
526                         rows[r] = (p && (r == param[p-1])) ?
527                                 p--, 1u << (m-r) : rows[r-p];
528                 }
529         }
530
531         if (nsol != (1 << k))
532                 /* unexpected number of solutions */
533                 return 0;
534
535         for (p = 0; p < nsol; p++) {
536                 /* set parameters for p-th solution */
537                 for (c = 0; c < k; c++)
538                         rows[param[c]] = (rows[param[c]] & ~1)|((p >> c) & 1);
539
540                 /* compute unique solution */
541                 tmp = 0;
542                 for (r = m-1; r >= 0; r--) {
543                         mask = rows[r] & (tmp|1);
544                         tmp |= parity(mask) << (m-r);
545                 }
546                 sol[p] = tmp >> 1;
547         }
548         return nsol;
549 }
550
551 /*
552  * this function builds and solves a linear system for finding roots of a degree
553  * 4 affine monic polynomial X^4+aX^2+bX+c over GF(2^m).
554  */
555 static int find_affine4_roots(struct bch_control *bch, unsigned int a,
556                               unsigned int b, unsigned int c,
557                               unsigned int *roots)
558 {
559         int i, j, k;
560         const int m = GF_M(bch);
561         unsigned int mask = 0xff, t, rows[16] = {0,};
562
563         j = a_log(bch, b);
564         k = a_log(bch, a);
565         rows[0] = c;
566
567         /* buid linear system to solve X^4+aX^2+bX+c = 0 */
568         for (i = 0; i < m; i++) {
569                 rows[i+1] = bch->a_pow_tab[4*i]^
570                         (a ? bch->a_pow_tab[mod_s(bch, k)] : 0)^
571                         (b ? bch->a_pow_tab[mod_s(bch, j)] : 0);
572                 j++;
573                 k += 2;
574         }
575         /*
576          * transpose 16x16 matrix before passing it to linear solver
577          * warning: this code assumes m < 16
578          */
579         for (j = 8; j != 0; j >>= 1, mask ^= (mask << j)) {
580                 for (k = 0; k < 16; k = (k+j+1) & ~j) {
581                         t = ((rows[k] >> j)^rows[k+j]) & mask;
582                         rows[k] ^= (t << j);
583                         rows[k+j] ^= t;
584                 }
585         }
586         return solve_linear_system(bch, rows, roots, 4);
587 }
588
589 /*
590  * compute root r of a degree 1 polynomial over GF(2^m) (returned as log(1/r))
591  */
592 static int find_poly_deg1_roots(struct bch_control *bch, struct gf_poly *poly,
593                                 unsigned int *roots)
594 {
595         int n = 0;
596
597         if (poly->c[0])
598                 /* poly[X] = bX+c with c!=0, root=c/b */
599                 roots[n++] = mod_s(bch, GF_N(bch)-bch->a_log_tab[poly->c[0]]+
600                                    bch->a_log_tab[poly->c[1]]);
601         return n;
602 }
603
604 /*
605  * compute roots of a degree 2 polynomial over GF(2^m)
606  */
607 static int find_poly_deg2_roots(struct bch_control *bch, struct gf_poly *poly,
608                                 unsigned int *roots)
609 {
610         int n = 0, i, l0, l1, l2;
611         unsigned int u, v, r;
612
613         if (poly->c[0] && poly->c[1]) {
614
615                 l0 = bch->a_log_tab[poly->c[0]];
616                 l1 = bch->a_log_tab[poly->c[1]];
617                 l2 = bch->a_log_tab[poly->c[2]];
618
619                 /* using z=a/bX, transform aX^2+bX+c into z^2+z+u (u=ac/b^2) */
620                 u = a_pow(bch, l0+l2+2*(GF_N(bch)-l1));
621                 /*
622                  * let u = sum(li.a^i) i=0..m-1; then compute r = sum(li.xi):
623                  * r^2+r = sum(li.(xi^2+xi)) = sum(li.(a^i+Tr(a^i).a^k)) =
624                  * u + sum(li.Tr(a^i).a^k) = u+a^k.Tr(sum(li.a^i)) = u+a^k.Tr(u)
625                  * i.e. r and r+1 are roots iff Tr(u)=0
626                  */
627                 r = 0;
628                 v = u;
629                 while (v) {
630                         i = deg(v);
631                         r ^= bch->xi_tab[i];
632                         v ^= (1 << i);
633                 }
634                 /* verify root */
635                 if ((gf_sqr(bch, r)^r) == u) {
636                         /* reverse z=a/bX transformation and compute log(1/r) */
637                         roots[n++] = modulo(bch, 2*GF_N(bch)-l1-
638                                             bch->a_log_tab[r]+l2);
639                         roots[n++] = modulo(bch, 2*GF_N(bch)-l1-
640                                             bch->a_log_tab[r^1]+l2);
641                 }
642         }
643         return n;
644 }
645
646 /*
647  * compute roots of a degree 3 polynomial over GF(2^m)
648  */
649 static int find_poly_deg3_roots(struct bch_control *bch, struct gf_poly *poly,
650                                 unsigned int *roots)
651 {
652         int i, n = 0;
653         unsigned int a, b, c, a2, b2, c2, e3, tmp[4];
654
655         if (poly->c[0]) {
656                 /* transform polynomial into monic X^3 + a2X^2 + b2X + c2 */
657                 e3 = poly->c[3];
658                 c2 = gf_div(bch, poly->c[0], e3);
659                 b2 = gf_div(bch, poly->c[1], e3);
660                 a2 = gf_div(bch, poly->c[2], e3);
661
662                 /* (X+a2)(X^3+a2X^2+b2X+c2) = X^4+aX^2+bX+c (affine) */
663                 c = gf_mul(bch, a2, c2);           /* c = a2c2      */
664                 b = gf_mul(bch, a2, b2)^c2;        /* b = a2b2 + c2 */
665                 a = gf_sqr(bch, a2)^b2;            /* a = a2^2 + b2 */
666
667                 /* find the 4 roots of this affine polynomial */
668                 if (find_affine4_roots(bch, a, b, c, tmp) == 4) {
669                         /* remove a2 from final list of roots */
670                         for (i = 0; i < 4; i++) {
671                                 if (tmp[i] != a2)
672                                         roots[n++] = a_ilog(bch, tmp[i]);
673                         }
674                 }
675         }
676         return n;
677 }
678
679 /*
680  * compute roots of a degree 4 polynomial over GF(2^m)
681  */
682 static int find_poly_deg4_roots(struct bch_control *bch, struct gf_poly *poly,
683                                 unsigned int *roots)
684 {
685         int i, l, n = 0;
686         unsigned int a, b, c, d, e = 0, f, a2, b2, c2, e4;
687
688         if (poly->c[0] == 0)
689                 return 0;
690
691         /* transform polynomial into monic X^4 + aX^3 + bX^2 + cX + d */
692         e4 = poly->c[4];
693         d = gf_div(bch, poly->c[0], e4);
694         c = gf_div(bch, poly->c[1], e4);
695         b = gf_div(bch, poly->c[2], e4);
696         a = gf_div(bch, poly->c[3], e4);
697
698         /* use Y=1/X transformation to get an affine polynomial */
699         if (a) {
700                 /* first, eliminate cX by using z=X+e with ae^2+c=0 */
701                 if (c) {
702                         /* compute e such that e^2 = c/a */
703                         f = gf_div(bch, c, a);
704                         l = a_log(bch, f);
705                         l += (l & 1) ? GF_N(bch) : 0;
706                         e = a_pow(bch, l/2);
707                         /*
708                          * use transformation z=X+e:
709                          * z^4+e^4 + a(z^3+ez^2+e^2z+e^3) + b(z^2+e^2) +cz+ce+d
710                          * z^4 + az^3 + (ae+b)z^2 + (ae^2+c)z+e^4+be^2+ae^3+ce+d
711                          * z^4 + az^3 + (ae+b)z^2 + e^4+be^2+d
712                          * z^4 + az^3 +     b'z^2 + d'
713                          */
714                         d = a_pow(bch, 2*l)^gf_mul(bch, b, f)^d;
715                         b = gf_mul(bch, a, e)^b;
716                 }
717                 /* now, use Y=1/X to get Y^4 + b/dY^2 + a/dY + 1/d */
718                 if (d == 0)
719                         /* assume all roots have multiplicity 1 */
720                         return 0;
721
722                 c2 = gf_inv(bch, d);
723                 b2 = gf_div(bch, a, d);
724                 a2 = gf_div(bch, b, d);
725         } else {
726                 /* polynomial is already affine */
727                 c2 = d;
728                 b2 = c;
729                 a2 = b;
730         }
731         /* find the 4 roots of this affine polynomial */
732         if (find_affine4_roots(bch, a2, b2, c2, roots) == 4) {
733                 for (i = 0; i < 4; i++) {
734                         /* post-process roots (reverse transformations) */
735                         f = a ? gf_inv(bch, roots[i]) : roots[i];
736                         roots[i] = a_ilog(bch, f^e);
737                 }
738                 n = 4;
739         }
740         return n;
741 }
742
743 /*
744  * build monic, log-based representation of a polynomial
745  */
746 static void gf_poly_logrep(struct bch_control *bch,
747                            const struct gf_poly *a, int *rep)
748 {
749         int i, d = a->deg, l = GF_N(bch)-a_log(bch, a->c[a->deg]);
750
751         /* represent 0 values with -1; warning, rep[d] is not set to 1 */
752         for (i = 0; i < d; i++)
753                 rep[i] = a->c[i] ? mod_s(bch, a_log(bch, a->c[i])+l) : -1;
754 }
755
756 /*
757  * compute polynomial Euclidean division remainder in GF(2^m)[X]
758  */
759 static void gf_poly_mod(struct bch_control *bch, struct gf_poly *a,
760                         const struct gf_poly *b, int *rep)
761 {
762         int la, p, m;
763         unsigned int i, j, *c = a->c;
764         const unsigned int d = b->deg;
765
766         if (a->deg < d)
767                 return;
768
769         /* reuse or compute log representation of denominator */
770         if (!rep) {
771                 rep = bch->cache;
772                 gf_poly_logrep(bch, b, rep);
773         }
774
775         for (j = a->deg; j >= d; j--) {
776                 if (c[j]) {
777                         la = a_log(bch, c[j]);
778                         p = j-d;
779                         for (i = 0; i < d; i++, p++) {
780                                 m = rep[i];
781                                 if (m >= 0)
782                                         c[p] ^= bch->a_pow_tab[mod_s(bch,
783                                                                      m+la)];
784                         }
785                 }
786         }
787         a->deg = d-1;
788         while (!c[a->deg] && a->deg)
789                 a->deg--;
790 }
791
792 /*
793  * compute polynomial Euclidean division quotient in GF(2^m)[X]
794  */
795 static void gf_poly_div(struct bch_control *bch, struct gf_poly *a,
796                         const struct gf_poly *b, struct gf_poly *q)
797 {
798         if (a->deg >= b->deg) {
799                 q->deg = a->deg-b->deg;
800                 /* compute a mod b (modifies a) */
801                 gf_poly_mod(bch, a, b, NULL);
802                 /* quotient is stored in upper part of polynomial a */
803                 memcpy(q->c, &a->c[b->deg], (1+q->deg)*sizeof(unsigned int));
804         } else {
805                 q->deg = 0;
806                 q->c[0] = 0;
807         }
808 }
809
810 /*
811  * compute polynomial GCD (Greatest Common Divisor) in GF(2^m)[X]
812  */
813 static struct gf_poly *gf_poly_gcd(struct bch_control *bch, struct gf_poly *a,
814                                    struct gf_poly *b)
815 {
816         struct gf_poly *tmp;
817
818         dbg("gcd(%s,%s)=", gf_poly_str(a), gf_poly_str(b));
819
820         if (a->deg < b->deg) {
821                 tmp = b;
822                 b = a;
823                 a = tmp;
824         }
825
826         while (b->deg > 0) {
827                 gf_poly_mod(bch, a, b, NULL);
828                 tmp = b;
829                 b = a;
830                 a = tmp;
831         }
832
833         dbg("%s\n", gf_poly_str(a));
834
835         return a;
836 }
837
838 /*
839  * Given a polynomial f and an integer k, compute Tr(a^kX) mod f
840  * This is used in Berlekamp Trace algorithm for splitting polynomials
841  */
842 static void compute_trace_bk_mod(struct bch_control *bch, int k,
843                                  const struct gf_poly *f, struct gf_poly *z,
844                                  struct gf_poly *out)
845 {
846         const int m = GF_M(bch);
847         int i, j;
848
849         /* z contains z^2j mod f */
850         z->deg = 1;
851         z->c[0] = 0;
852         z->c[1] = bch->a_pow_tab[k];
853
854         out->deg = 0;
855         memset(out, 0, GF_POLY_SZ(f->deg));
856
857         /* compute f log representation only once */
858         gf_poly_logrep(bch, f, bch->cache);
859
860         for (i = 0; i < m; i++) {
861                 /* add a^(k*2^i)(z^(2^i) mod f) and compute (z^(2^i) mod f)^2 */
862                 for (j = z->deg; j >= 0; j--) {
863                         out->c[j] ^= z->c[j];
864                         z->c[2*j] = gf_sqr(bch, z->c[j]);
865                         z->c[2*j+1] = 0;
866                 }
867                 if (z->deg > out->deg)
868                         out->deg = z->deg;
869
870                 if (i < m-1) {
871                         z->deg *= 2;
872                         /* z^(2(i+1)) mod f = (z^(2^i) mod f)^2 mod f */
873                         gf_poly_mod(bch, z, f, bch->cache);
874                 }
875         }
876         while (!out->c[out->deg] && out->deg)
877                 out->deg--;
878
879         dbg("Tr(a^%d.X) mod f = %s\n", k, gf_poly_str(out));
880 }
881
882 /*
883  * factor a polynomial using Berlekamp Trace algorithm (BTA)
884  */
885 static void factor_polynomial(struct bch_control *bch, int k, struct gf_poly *f,
886                               struct gf_poly **g, struct gf_poly **h)
887 {
888         struct gf_poly *f2 = bch->poly_2t[0];
889         struct gf_poly *q  = bch->poly_2t[1];
890         struct gf_poly *tk = bch->poly_2t[2];
891         struct gf_poly *z  = bch->poly_2t[3];
892         struct gf_poly *gcd;
893
894         dbg("factoring %s...\n", gf_poly_str(f));
895
896         *g = f;
897         *h = NULL;
898
899         /* tk = Tr(a^k.X) mod f */
900         compute_trace_bk_mod(bch, k, f, z, tk);
901
902         if (tk->deg > 0) {
903                 /* compute g = gcd(f, tk) (destructive operation) */
904                 gf_poly_copy(f2, f);
905                 gcd = gf_poly_gcd(bch, f2, tk);
906                 if (gcd->deg < f->deg) {
907                         /* compute h=f/gcd(f,tk); this will modify f and q */
908                         gf_poly_div(bch, f, gcd, q);
909                         /* store g and h in-place (clobbering f) */
910                         *h = &((struct gf_poly_deg1 *)f)[gcd->deg].poly;
911                         gf_poly_copy(*g, gcd);
912                         gf_poly_copy(*h, q);
913                 }
914         }
915 }
916
917 /*
918  * find roots of a polynomial, using BTZ algorithm; see the beginning of this
919  * file for details
920  */
921 static int find_poly_roots(struct bch_control *bch, unsigned int k,
922                            struct gf_poly *poly, unsigned int *roots)
923 {
924         int cnt;
925         struct gf_poly *f1, *f2;
926
927         switch (poly->deg) {
928                 /* handle low degree polynomials with ad hoc techniques */
929         case 1:
930                 cnt = find_poly_deg1_roots(bch, poly, roots);
931                 break;
932         case 2:
933                 cnt = find_poly_deg2_roots(bch, poly, roots);
934                 break;
935         case 3:
936                 cnt = find_poly_deg3_roots(bch, poly, roots);
937                 break;
938         case 4:
939                 cnt = find_poly_deg4_roots(bch, poly, roots);
940                 break;
941         default:
942                 /* factor polynomial using Berlekamp Trace Algorithm (BTA) */
943                 cnt = 0;
944                 if (poly->deg && (k <= GF_M(bch))) {
945                         factor_polynomial(bch, k, poly, &f1, &f2);
946                         if (f1)
947                                 cnt += find_poly_roots(bch, k+1, f1, roots);
948                         if (f2)
949                                 cnt += find_poly_roots(bch, k+1, f2, roots+cnt);
950                 }
951                 break;
952         }
953         return cnt;
954 }
955
956 #if defined(USE_CHIEN_SEARCH)
957 /*
958  * exhaustive root search (Chien) implementation - not used, included only for
959  * reference/comparison tests
960  */
961 static int chien_search(struct bch_control *bch, unsigned int len,
962                         struct gf_poly *p, unsigned int *roots)
963 {
964         int m;
965         unsigned int i, j, syn, syn0, count = 0;
966         const unsigned int k = 8*len+bch->ecc_bits;
967
968         /* use a log-based representation of polynomial */
969         gf_poly_logrep(bch, p, bch->cache);
970         bch->cache[p->deg] = 0;
971         syn0 = gf_div(bch, p->c[0], p->c[p->deg]);
972
973         for (i = GF_N(bch)-k+1; i <= GF_N(bch); i++) {
974                 /* compute elp(a^i) */
975                 for (j = 1, syn = syn0; j <= p->deg; j++) {
976                         m = bch->cache[j];
977                         if (m >= 0)
978                                 syn ^= a_pow(bch, m+j*i);
979                 }
980                 if (syn == 0) {
981                         roots[count++] = GF_N(bch)-i;
982                         if (count == p->deg)
983                                 break;
984                 }
985         }
986         return (count == p->deg) ? count : 0;
987 }
988 #define find_poly_roots(_p, _k, _elp, _loc) chien_search(_p, len, _elp, _loc)
989 #endif /* USE_CHIEN_SEARCH */
990
991 /**
992  * decode_bch - decode received codeword and find bit error locations
993  * @bch:      BCH control structure
994  * @data:     received data, ignored if @calc_ecc is provided
995  * @len:      data length in bytes, must always be provided
996  * @recv_ecc: received ecc, if NULL then assume it was XORed in @calc_ecc
997  * @calc_ecc: calculated ecc, if NULL then calc_ecc is computed from @data
998  * @syn:      hw computed syndrome data (if NULL, syndrome is calculated)
999  * @errloc:   output array of error locations
1000  *
1001  * Returns:
1002  *  The number of errors found, or -EBADMSG if decoding failed, or -EINVAL if
1003  *  invalid parameters were provided
1004  *
1005  * Depending on the available hw BCH support and the need to compute @calc_ecc
1006  * separately (using encode_bch()), this function should be called with one of
1007  * the following parameter configurations -
1008  *
1009  * by providing @data and @recv_ecc only:
1010  *   decode_bch(@bch, @data, @len, @recv_ecc, NULL, NULL, @errloc)
1011  *
1012  * by providing @recv_ecc and @calc_ecc:
1013  *   decode_bch(@bch, NULL, @len, @recv_ecc, @calc_ecc, NULL, @errloc)
1014  *
1015  * by providing ecc = recv_ecc XOR calc_ecc:
1016  *   decode_bch(@bch, NULL, @len, NULL, ecc, NULL, @errloc)
1017  *
1018  * by providing syndrome results @syn:
1019  *   decode_bch(@bch, NULL, @len, NULL, NULL, @syn, @errloc)
1020  *
1021  * Once decode_bch() has successfully returned with a positive value, error
1022  * locations returned in array @errloc should be interpreted as follows -
1023  *
1024  * if (errloc[n] >= 8*len), then n-th error is located in ecc (no need for
1025  * data correction)
1026  *
1027  * if (errloc[n] < 8*len), then n-th error is located in data and can be
1028  * corrected with statement data[errloc[n]/8] ^= 1 << (errloc[n] % 8);
1029  *
1030  * Note that this function does not perform any data correction by itself, it
1031  * merely indicates error locations.
1032  */
1033 int decode_bch(struct bch_control *bch, const uint8_t *data, unsigned int len,
1034                const uint8_t *recv_ecc, const uint8_t *calc_ecc,
1035                const unsigned int *syn, unsigned int *errloc)
1036 {
1037         const unsigned int ecc_words = BCH_ECC_WORDS(bch);
1038         unsigned int nbits;
1039         int i, err, nroots;
1040         uint32_t sum;
1041
1042         /* sanity check: make sure data length can be handled */
1043         if (8*len > (bch->n-bch->ecc_bits))
1044                 return -EINVAL;
1045
1046         /* if caller does not provide syndromes, compute them */
1047         if (!syn) {
1048                 if (!calc_ecc) {
1049                         /* compute received data ecc into an internal buffer */
1050                         if (!data || !recv_ecc)
1051                                 return -EINVAL;
1052                         encode_bch(bch, data, len, NULL);
1053                 } else {
1054                         /* load provided calculated ecc */
1055                         load_ecc8(bch, bch->ecc_buf, calc_ecc);
1056                 }
1057                 /* load received ecc or assume it was XORed in calc_ecc */
1058                 if (recv_ecc) {
1059                         load_ecc8(bch, bch->ecc_buf2, recv_ecc);
1060                         /* XOR received and calculated ecc */
1061                         for (i = 0, sum = 0; i < (int)ecc_words; i++) {
1062                                 bch->ecc_buf[i] ^= bch->ecc_buf2[i];
1063                                 sum |= bch->ecc_buf[i];
1064                         }
1065                         if (!sum)
1066                                 /* no error found */
1067                                 return 0;
1068                 }
1069                 compute_syndromes(bch, bch->ecc_buf, bch->syn);
1070                 syn = bch->syn;
1071         }
1072
1073         err = compute_error_locator_polynomial(bch, syn);
1074         if (err > 0) {
1075                 nroots = find_poly_roots(bch, 1, bch->elp, errloc);
1076                 if (err != nroots)
1077                         err = -1;
1078         }
1079         if (err > 0) {
1080                 /* post-process raw error locations for easier correction */
1081                 nbits = (len*8)+bch->ecc_bits;
1082                 for (i = 0; i < err; i++) {
1083                         if (errloc[i] >= nbits) {
1084                                 err = -1;
1085                                 break;
1086                         }
1087                         errloc[i] = nbits-1-errloc[i];
1088                         errloc[i] = (errloc[i] & ~7)|(7-(errloc[i] & 7));
1089                 }
1090         }
1091         return (err >= 0) ? err : -EBADMSG;
1092 }
1093
1094 /*
1095  * generate Galois field lookup tables
1096  */
1097 static int build_gf_tables(struct bch_control *bch, unsigned int poly)
1098 {
1099         unsigned int i, x = 1;
1100         const unsigned int k = 1 << deg(poly);
1101
1102         /* primitive polynomial must be of degree m */
1103         if (k != (1u << GF_M(bch)))
1104                 return -1;
1105
1106         for (i = 0; i < GF_N(bch); i++) {
1107                 bch->a_pow_tab[i] = x;
1108                 bch->a_log_tab[x] = i;
1109                 if (i && (x == 1))
1110                         /* polynomial is not primitive (a^i=1 with 0<i<2^m-1) */
1111                         return -1;
1112                 x <<= 1;
1113                 if (x & k)
1114                         x ^= poly;
1115         }
1116         bch->a_pow_tab[GF_N(bch)] = 1;
1117         bch->a_log_tab[0] = 0;
1118
1119         return 0;
1120 }
1121
1122 /*
1123  * compute generator polynomial remainder tables for fast encoding
1124  */
1125 static void build_mod8_tables(struct bch_control *bch, const uint32_t *g)
1126 {
1127         int i, j, b, d;
1128         uint32_t data, hi, lo, *tab;
1129         const int l = BCH_ECC_WORDS(bch);
1130         const int plen = DIV_ROUND_UP(bch->ecc_bits+1, 32);
1131         const int ecclen = DIV_ROUND_UP(bch->ecc_bits, 32);
1132
1133         memset(bch->mod8_tab, 0, 4*256*l*sizeof(*bch->mod8_tab));
1134
1135         for (i = 0; i < 256; i++) {
1136                 /* p(X)=i is a small polynomial of weight <= 8 */
1137                 for (b = 0; b < 4; b++) {
1138                         /* we want to compute (p(X).X^(8*b+deg(g))) mod g(X) */
1139                         tab = bch->mod8_tab + (b*256+i)*l;
1140                         data = i << (8*b);
1141                         while (data) {
1142                                 d = deg(data);
1143                                 /* subtract X^d.g(X) from p(X).X^(8*b+deg(g)) */
1144                                 data ^= g[0] >> (31-d);
1145                                 for (j = 0; j < ecclen; j++) {
1146                                         hi = (d < 31) ? g[j] << (d+1) : 0;
1147                                         lo = (j+1 < plen) ?
1148                                                 g[j+1] >> (31-d) : 0;
1149                                         tab[j] ^= hi|lo;
1150                                 }
1151                         }
1152                 }
1153         }
1154 }
1155
1156 /*
1157  * build a base for factoring degree 2 polynomials
1158  */
1159 static int build_deg2_base(struct bch_control *bch)
1160 {
1161         const int m = GF_M(bch);
1162         int i, j, r;
1163         unsigned int sum, x, y, remaining, ak = 0, xi[m];
1164
1165         /* find k s.t. Tr(a^k) = 1 and 0 <= k < m */
1166         for (i = 0; i < m; i++) {
1167                 for (j = 0, sum = 0; j < m; j++)
1168                         sum ^= a_pow(bch, i*(1 << j));
1169
1170                 if (sum) {
1171                         ak = bch->a_pow_tab[i];
1172                         break;
1173                 }
1174         }
1175         /* find xi, i=0..m-1 such that xi^2+xi = a^i+Tr(a^i).a^k */
1176         remaining = m;
1177         memset(xi, 0, sizeof(xi));
1178
1179         for (x = 0; (x <= GF_N(bch)) && remaining; x++) {
1180                 y = gf_sqr(bch, x)^x;
1181                 for (i = 0; i < 2; i++) {
1182                         r = a_log(bch, y);
1183                         if (y && (r < m) && !xi[r]) {
1184                                 bch->xi_tab[r] = x;
1185                                 xi[r] = 1;
1186                                 remaining--;
1187                                 dbg("x%d = %x\n", r, x);
1188                                 break;
1189                         }
1190                         y ^= ak;
1191                 }
1192         }
1193         /* should not happen but check anyway */
1194         return remaining ? -1 : 0;
1195 }
1196
1197 static void *bch_alloc(size_t size, int *err)
1198 {
1199         void *ptr;
1200
1201         ptr = kmalloc(size, GFP_KERNEL);
1202         if (ptr == NULL)
1203                 *err = 1;
1204         return ptr;
1205 }
1206
1207 /*
1208  * compute generator polynomial for given (m,t) parameters.
1209  */
1210 static uint32_t *compute_generator_polynomial(struct bch_control *bch)
1211 {
1212         const unsigned int m = GF_M(bch);
1213         const unsigned int t = GF_T(bch);
1214         int n, err = 0;
1215         unsigned int i, j, nbits, r, word, *roots;
1216         struct gf_poly *g;
1217         uint32_t *genpoly;
1218
1219         g = bch_alloc(GF_POLY_SZ(m*t), &err);
1220         roots = bch_alloc((bch->n+1)*sizeof(*roots), &err);
1221         genpoly = bch_alloc(DIV_ROUND_UP(m*t+1, 32)*sizeof(*genpoly), &err);
1222
1223         if (err) {
1224                 kfree(genpoly);
1225                 genpoly = NULL;
1226                 goto finish;
1227         }
1228
1229         /* enumerate all roots of g(X) */
1230         memset(roots , 0, (bch->n+1)*sizeof(*roots));
1231         for (i = 0; i < t; i++) {
1232                 for (j = 0, r = 2*i+1; j < m; j++) {
1233                         roots[r] = 1;
1234                         r = mod_s(bch, 2*r);
1235                 }
1236         }
1237         /* build generator polynomial g(X) */
1238         g->deg = 0;
1239         g->c[0] = 1;
1240         for (i = 0; i < GF_N(bch); i++) {
1241                 if (roots[i]) {
1242                         /* multiply g(X) by (X+root) */
1243                         r = bch->a_pow_tab[i];
1244                         g->c[g->deg+1] = 1;
1245                         for (j = g->deg; j > 0; j--)
1246                                 g->c[j] = gf_mul(bch, g->c[j], r)^g->c[j-1];
1247
1248                         g->c[0] = gf_mul(bch, g->c[0], r);
1249                         g->deg++;
1250                 }
1251         }
1252         /* store left-justified binary representation of g(X) */
1253         n = g->deg+1;
1254         i = 0;
1255
1256         while (n > 0) {
1257                 nbits = (n > 32) ? 32 : n;
1258                 for (j = 0, word = 0; j < nbits; j++) {
1259                         if (g->c[n-1-j])
1260                                 word |= 1u << (31-j);
1261                 }
1262                 genpoly[i++] = word;
1263                 n -= nbits;
1264         }
1265         bch->ecc_bits = g->deg;
1266
1267 finish:
1268         kfree(g);
1269         kfree(roots);
1270
1271         return genpoly;
1272 }
1273
1274 /**
1275  * init_bch - initialize a BCH encoder/decoder
1276  * @m:          Galois field order, should be in the range 5-15
1277  * @t:          maximum error correction capability, in bits
1278  * @prim_poly:  user-provided primitive polynomial (or 0 to use default)
1279  *
1280  * Returns:
1281  *  a newly allocated BCH control structure if successful, NULL otherwise
1282  *
1283  * This initialization can take some time, as lookup tables are built for fast
1284  * encoding/decoding; make sure not to call this function from a time critical
1285  * path. Usually, init_bch() should be called on module/driver init and
1286  * free_bch() should be called to release memory on exit.
1287  *
1288  * You may provide your own primitive polynomial of degree @m in argument
1289  * @prim_poly, or let init_bch() use its default polynomial.
1290  *
1291  * Once init_bch() has successfully returned a pointer to a newly allocated
1292  * BCH control structure, ecc length in bytes is given by member @ecc_bytes of
1293  * the structure.
1294  */
1295 struct bch_control *init_bch(int m, int t, unsigned int prim_poly)
1296 {
1297         int err = 0;
1298         unsigned int i, words;
1299         uint32_t *genpoly;
1300         struct bch_control *bch = NULL;
1301
1302         const int min_m = 5;
1303         const int max_m = 15;
1304
1305         /* default primitive polynomials */
1306         static const unsigned int prim_poly_tab[] = {
1307                 0x25, 0x43, 0x83, 0x11d, 0x211, 0x409, 0x805, 0x1053, 0x201b,
1308                 0x402b, 0x8003,
1309         };
1310
1311 #if defined(CONFIG_BCH_CONST_PARAMS)
1312         if ((m != (CONFIG_BCH_CONST_M)) || (t != (CONFIG_BCH_CONST_T))) {
1313                 printk(KERN_ERR "bch encoder/decoder was configured to support "
1314                        "parameters m=%d, t=%d only!\n",
1315                        CONFIG_BCH_CONST_M, CONFIG_BCH_CONST_T);
1316                 goto fail;
1317         }
1318 #endif
1319         if ((m < min_m) || (m > max_m))
1320                 /*
1321                  * values of m greater than 15 are not currently supported;
1322                  * supporting m > 15 would require changing table base type
1323                  * (uint16_t) and a small patch in matrix transposition
1324                  */
1325                 goto fail;
1326
1327         /* sanity checks */
1328         if ((t < 1) || (m*t >= ((1 << m)-1)))
1329                 /* invalid t value */
1330                 goto fail;
1331
1332         /* select a primitive polynomial for generating GF(2^m) */
1333         if (prim_poly == 0)
1334                 prim_poly = prim_poly_tab[m-min_m];
1335
1336         bch = kzalloc(sizeof(*bch), GFP_KERNEL);
1337         if (bch == NULL)
1338                 goto fail;
1339
1340         bch->m = m;
1341         bch->t = t;
1342         bch->n = (1 << m)-1;
1343         words  = DIV_ROUND_UP(m*t, 32);
1344         bch->ecc_bytes = DIV_ROUND_UP(m*t, 8);
1345         bch->a_pow_tab = bch_alloc((1+bch->n)*sizeof(*bch->a_pow_tab), &err);
1346         bch->a_log_tab = bch_alloc((1+bch->n)*sizeof(*bch->a_log_tab), &err);
1347         bch->mod8_tab  = bch_alloc(words*1024*sizeof(*bch->mod8_tab), &err);
1348         bch->ecc_buf   = bch_alloc(words*sizeof(*bch->ecc_buf), &err);
1349         bch->ecc_buf2  = bch_alloc(words*sizeof(*bch->ecc_buf2), &err);
1350         bch->xi_tab    = bch_alloc(m*sizeof(*bch->xi_tab), &err);
1351         bch->syn       = bch_alloc(2*t*sizeof(*bch->syn), &err);
1352         bch->cache     = bch_alloc(2*t*sizeof(*bch->cache), &err);
1353         bch->elp       = bch_alloc((t+1)*sizeof(struct gf_poly_deg1), &err);
1354
1355         for (i = 0; i < ARRAY_SIZE(bch->poly_2t); i++)
1356                 bch->poly_2t[i] = bch_alloc(GF_POLY_SZ(2*t), &err);
1357
1358         if (err)
1359                 goto fail;
1360
1361         err = build_gf_tables(bch, prim_poly);
1362         if (err)
1363                 goto fail;
1364
1365         /* use generator polynomial for computing encoding tables */
1366         genpoly = compute_generator_polynomial(bch);
1367         if (genpoly == NULL)
1368                 goto fail;
1369
1370         build_mod8_tables(bch, genpoly);
1371         kfree(genpoly);
1372
1373         err = build_deg2_base(bch);
1374         if (err)
1375                 goto fail;
1376
1377         return bch;
1378
1379 fail:
1380         free_bch(bch);
1381         return NULL;
1382 }
1383
1384 /**
1385  *  free_bch - free the BCH control structure
1386  *  @bch:    BCH control structure to release
1387  */
1388 void free_bch(struct bch_control *bch)
1389 {
1390         unsigned int i;
1391
1392         if (bch) {
1393                 kfree(bch->a_pow_tab);
1394                 kfree(bch->a_log_tab);
1395                 kfree(bch->mod8_tab);
1396                 kfree(bch->ecc_buf);
1397                 kfree(bch->ecc_buf2);
1398                 kfree(bch->xi_tab);
1399                 kfree(bch->syn);
1400                 kfree(bch->cache);
1401                 kfree(bch->elp);
1402
1403                 for (i = 0; i < ARRAY_SIZE(bch->poly_2t); i++)
1404                         kfree(bch->poly_2t[i]);
1405
1406                 kfree(bch);
1407         }
1408 }