Merge branch 'hwmon-for-linus' of git://jdelvare.pck.nerim.net/jdelvare-2.6
[pandora-kernel.git] / drivers / mtd / devices / docecc.c
1 /*
2  * ECC algorithm for M-systems disk on chip. We use the excellent Reed
3  * Solmon code of Phil Karn (karn@ka9q.ampr.org) available under the
4  * GNU GPL License. The rest is simply to convert the disk on chip
5  * syndrom into a standard syndom.
6  *
7  * Author: Fabrice Bellard (fabrice.bellard@netgem.com)
8  * Copyright (C) 2000 Netgem S.A.
9  *
10  * $Id: docecc.c,v 1.7 2005/11/07 11:14:25 gleixner Exp $
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25  */
26 #include <linux/kernel.h>
27 #include <linux/module.h>
28 #include <asm/errno.h>
29 #include <asm/io.h>
30 #include <asm/uaccess.h>
31 #include <linux/miscdevice.h>
32 #include <linux/pci.h>
33 #include <linux/delay.h>
34 #include <linux/slab.h>
35 #include <linux/init.h>
36 #include <linux/types.h>
37
38 #include <linux/mtd/compatmac.h> /* for min() in older kernels */
39 #include <linux/mtd/mtd.h>
40 #include <linux/mtd/doc2000.h>
41
42 #define DEBUG_ECC 0
43 /* need to undef it (from asm/termbits.h) */
44 #undef B0
45
46 #define MM 10 /* Symbol size in bits */
47 #define KK (1023-4) /* Number of data symbols per block */
48 #define B0 510 /* First root of generator polynomial, alpha form */
49 #define PRIM 1 /* power of alpha used to generate roots of generator poly */
50 #define NN ((1 << MM) - 1)
51
52 typedef unsigned short dtype;
53
54 /* 1+x^3+x^10 */
55 static const int Pp[MM+1] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 };
56
57 /* This defines the type used to store an element of the Galois Field
58  * used by the code. Make sure this is something larger than a char if
59  * if anything larger than GF(256) is used.
60  *
61  * Note: unsigned char will work up to GF(256) but int seems to run
62  * faster on the Pentium.
63  */
64 typedef int gf;
65
66 /* No legal value in index form represents zero, so
67  * we need a special value for this purpose
68  */
69 #define A0      (NN)
70
71 /* Compute x % NN, where NN is 2**MM - 1,
72  * without a slow divide
73  */
74 static inline gf
75 modnn(int x)
76 {
77   while (x >= NN) {
78     x -= NN;
79     x = (x >> MM) + (x & NN);
80   }
81   return x;
82 }
83
84 #define CLEAR(a,n) {\
85 int ci;\
86 for(ci=(n)-1;ci >=0;ci--)\
87 (a)[ci] = 0;\
88 }
89
90 #define COPY(a,b,n) {\
91 int ci;\
92 for(ci=(n)-1;ci >=0;ci--)\
93 (a)[ci] = (b)[ci];\
94 }
95
96 #define COPYDOWN(a,b,n) {\
97 int ci;\
98 for(ci=(n)-1;ci >=0;ci--)\
99 (a)[ci] = (b)[ci];\
100 }
101
102 #define Ldec 1
103
104 /* generate GF(2**m) from the irreducible polynomial p(X) in Pp[0]..Pp[m]
105    lookup tables:  index->polynomial form   alpha_to[] contains j=alpha**i;
106                    polynomial form -> index form  index_of[j=alpha**i] = i
107    alpha=2 is the primitive element of GF(2**m)
108    HARI's COMMENT: (4/13/94) alpha_to[] can be used as follows:
109         Let @ represent the primitive element commonly called "alpha" that
110    is the root of the primitive polynomial p(x). Then in GF(2^m), for any
111    0 <= i <= 2^m-2,
112         @^i = a(0) + a(1) @ + a(2) @^2 + ... + a(m-1) @^(m-1)
113    where the binary vector (a(0),a(1),a(2),...,a(m-1)) is the representation
114    of the integer "alpha_to[i]" with a(0) being the LSB and a(m-1) the MSB. Thus for
115    example the polynomial representation of @^5 would be given by the binary
116    representation of the integer "alpha_to[5]".
117                    Similarily, index_of[] can be used as follows:
118         As above, let @ represent the primitive element of GF(2^m) that is
119    the root of the primitive polynomial p(x). In order to find the power
120    of @ (alpha) that has the polynomial representation
121         a(0) + a(1) @ + a(2) @^2 + ... + a(m-1) @^(m-1)
122    we consider the integer "i" whose binary representation with a(0) being LSB
123    and a(m-1) MSB is (a(0),a(1),...,a(m-1)) and locate the entry
124    "index_of[i]". Now, @^index_of[i] is that element whose polynomial
125     representation is (a(0),a(1),a(2),...,a(m-1)).
126    NOTE:
127         The element alpha_to[2^m-1] = 0 always signifying that the
128    representation of "@^infinity" = 0 is (0,0,0,...,0).
129         Similarily, the element index_of[0] = A0 always signifying
130    that the power of alpha which has the polynomial representation
131    (0,0,...,0) is "infinity".
132
133 */
134
135 static void
136 generate_gf(dtype Alpha_to[NN + 1], dtype Index_of[NN + 1])
137 {
138   register int i, mask;
139
140   mask = 1;
141   Alpha_to[MM] = 0;
142   for (i = 0; i < MM; i++) {
143     Alpha_to[i] = mask;
144     Index_of[Alpha_to[i]] = i;
145     /* If Pp[i] == 1 then, term @^i occurs in poly-repr of @^MM */
146     if (Pp[i] != 0)
147       Alpha_to[MM] ^= mask;     /* Bit-wise EXOR operation */
148     mask <<= 1; /* single left-shift */
149   }
150   Index_of[Alpha_to[MM]] = MM;
151   /*
152    * Have obtained poly-repr of @^MM. Poly-repr of @^(i+1) is given by
153    * poly-repr of @^i shifted left one-bit and accounting for any @^MM
154    * term that may occur when poly-repr of @^i is shifted.
155    */
156   mask >>= 1;
157   for (i = MM + 1; i < NN; i++) {
158     if (Alpha_to[i - 1] >= mask)
159       Alpha_to[i] = Alpha_to[MM] ^ ((Alpha_to[i - 1] ^ mask) << 1);
160     else
161       Alpha_to[i] = Alpha_to[i - 1] << 1;
162     Index_of[Alpha_to[i]] = i;
163   }
164   Index_of[0] = A0;
165   Alpha_to[NN] = 0;
166 }
167
168 /*
169  * Performs ERRORS+ERASURES decoding of RS codes. bb[] is the content
170  * of the feedback shift register after having processed the data and
171  * the ECC.
172  *
173  * Return number of symbols corrected, or -1 if codeword is illegal
174  * or uncorrectable. If eras_pos is non-null, the detected error locations
175  * are written back. NOTE! This array must be at least NN-KK elements long.
176  * The corrected data are written in eras_val[]. They must be xor with the data
177  * to retrieve the correct data : data[erase_pos[i]] ^= erase_val[i] .
178  *
179  * First "no_eras" erasures are declared by the calling program. Then, the
180  * maximum # of errors correctable is t_after_eras = floor((NN-KK-no_eras)/2).
181  * If the number of channel errors is not greater than "t_after_eras" the
182  * transmitted codeword will be recovered. Details of algorithm can be found
183  * in R. Blahut's "Theory ... of Error-Correcting Codes".
184
185  * Warning: the eras_pos[] array must not contain duplicate entries; decoder failure
186  * will result. The decoder *could* check for this condition, but it would involve
187  * extra time on every decoding operation.
188  * */
189 static int
190 eras_dec_rs(dtype Alpha_to[NN + 1], dtype Index_of[NN + 1],
191             gf bb[NN - KK + 1], gf eras_val[NN-KK], int eras_pos[NN-KK],
192             int no_eras)
193 {
194   int deg_lambda, el, deg_omega;
195   int i, j, r,k;
196   gf u,q,tmp,num1,num2,den,discr_r;
197   gf lambda[NN-KK + 1], s[NN-KK + 1];   /* Err+Eras Locator poly
198                                          * and syndrome poly */
199   gf b[NN-KK + 1], t[NN-KK + 1], omega[NN-KK + 1];
200   gf root[NN-KK], reg[NN-KK + 1], loc[NN-KK];
201   int syn_error, count;
202
203   syn_error = 0;
204   for(i=0;i<NN-KK;i++)
205       syn_error |= bb[i];
206
207   if (!syn_error) {
208     /* if remainder is zero, data[] is a codeword and there are no
209      * errors to correct. So return data[] unmodified
210      */
211     count = 0;
212     goto finish;
213   }
214
215   for(i=1;i<=NN-KK;i++){
216     s[i] = bb[0];
217   }
218   for(j=1;j<NN-KK;j++){
219     if(bb[j] == 0)
220       continue;
221     tmp = Index_of[bb[j]];
222
223     for(i=1;i<=NN-KK;i++)
224       s[i] ^= Alpha_to[modnn(tmp + (B0+i-1)*PRIM*j)];
225   }
226
227   /* undo the feedback register implicit multiplication and convert
228      syndromes to index form */
229
230   for(i=1;i<=NN-KK;i++) {
231       tmp = Index_of[s[i]];
232       if (tmp != A0)
233           tmp = modnn(tmp + 2 * KK * (B0+i-1)*PRIM);
234       s[i] = tmp;
235   }
236
237   CLEAR(&lambda[1],NN-KK);
238   lambda[0] = 1;
239
240   if (no_eras > 0) {
241     /* Init lambda to be the erasure locator polynomial */
242     lambda[1] = Alpha_to[modnn(PRIM * eras_pos[0])];
243     for (i = 1; i < no_eras; i++) {
244       u = modnn(PRIM*eras_pos[i]);
245       for (j = i+1; j > 0; j--) {
246         tmp = Index_of[lambda[j - 1]];
247         if(tmp != A0)
248           lambda[j] ^= Alpha_to[modnn(u + tmp)];
249       }
250     }
251 #if DEBUG_ECC >= 1
252     /* Test code that verifies the erasure locator polynomial just constructed
253        Needed only for decoder debugging. */
254
255     /* find roots of the erasure location polynomial */
256     for(i=1;i<=no_eras;i++)
257       reg[i] = Index_of[lambda[i]];
258     count = 0;
259     for (i = 1,k=NN-Ldec; i <= NN; i++,k = modnn(NN+k-Ldec)) {
260       q = 1;
261       for (j = 1; j <= no_eras; j++)
262         if (reg[j] != A0) {
263           reg[j] = modnn(reg[j] + j);
264           q ^= Alpha_to[reg[j]];
265         }
266       if (q != 0)
267         continue;
268       /* store root and error location number indices */
269       root[count] = i;
270       loc[count] = k;
271       count++;
272     }
273     if (count != no_eras) {
274       printf("\n lambda(x) is WRONG\n");
275       count = -1;
276       goto finish;
277     }
278 #if DEBUG_ECC >= 2
279     printf("\n Erasure positions as determined by roots of Eras Loc Poly:\n");
280     for (i = 0; i < count; i++)
281       printf("%d ", loc[i]);
282     printf("\n");
283 #endif
284 #endif
285   }
286   for(i=0;i<NN-KK+1;i++)
287     b[i] = Index_of[lambda[i]];
288
289   /*
290    * Begin Berlekamp-Massey algorithm to determine error+erasure
291    * locator polynomial
292    */
293   r = no_eras;
294   el = no_eras;
295   while (++r <= NN-KK) {        /* r is the step number */
296     /* Compute discrepancy at the r-th step in poly-form */
297     discr_r = 0;
298     for (i = 0; i < r; i++){
299       if ((lambda[i] != 0) && (s[r - i] != A0)) {
300         discr_r ^= Alpha_to[modnn(Index_of[lambda[i]] + s[r - i])];
301       }
302     }
303     discr_r = Index_of[discr_r];        /* Index form */
304     if (discr_r == A0) {
305       /* 2 lines below: B(x) <-- x*B(x) */
306       COPYDOWN(&b[1],b,NN-KK);
307       b[0] = A0;
308     } else {
309       /* 7 lines below: T(x) <-- lambda(x) - discr_r*x*b(x) */
310       t[0] = lambda[0];
311       for (i = 0 ; i < NN-KK; i++) {
312         if(b[i] != A0)
313           t[i+1] = lambda[i+1] ^ Alpha_to[modnn(discr_r + b[i])];
314         else
315           t[i+1] = lambda[i+1];
316       }
317       if (2 * el <= r + no_eras - 1) {
318         el = r + no_eras - el;
319         /*
320          * 2 lines below: B(x) <-- inv(discr_r) *
321          * lambda(x)
322          */
323         for (i = 0; i <= NN-KK; i++)
324           b[i] = (lambda[i] == 0) ? A0 : modnn(Index_of[lambda[i]] - discr_r + NN);
325       } else {
326         /* 2 lines below: B(x) <-- x*B(x) */
327         COPYDOWN(&b[1],b,NN-KK);
328         b[0] = A0;
329       }
330       COPY(lambda,t,NN-KK+1);
331     }
332   }
333
334   /* Convert lambda to index form and compute deg(lambda(x)) */
335   deg_lambda = 0;
336   for(i=0;i<NN-KK+1;i++){
337     lambda[i] = Index_of[lambda[i]];
338     if(lambda[i] != A0)
339       deg_lambda = i;
340   }
341   /*
342    * Find roots of the error+erasure locator polynomial by Chien
343    * Search
344    */
345   COPY(&reg[1],&lambda[1],NN-KK);
346   count = 0;            /* Number of roots of lambda(x) */
347   for (i = 1,k=NN-Ldec; i <= NN; i++,k = modnn(NN+k-Ldec)) {
348     q = 1;
349     for (j = deg_lambda; j > 0; j--){
350       if (reg[j] != A0) {
351         reg[j] = modnn(reg[j] + j);
352         q ^= Alpha_to[reg[j]];
353       }
354     }
355     if (q != 0)
356       continue;
357     /* store root (index-form) and error location number */
358     root[count] = i;
359     loc[count] = k;
360     /* If we've already found max possible roots,
361      * abort the search to save time
362      */
363     if(++count == deg_lambda)
364       break;
365   }
366   if (deg_lambda != count) {
367     /*
368      * deg(lambda) unequal to number of roots => uncorrectable
369      * error detected
370      */
371     count = -1;
372     goto finish;
373   }
374   /*
375    * Compute err+eras evaluator poly omega(x) = s(x)*lambda(x) (modulo
376    * x**(NN-KK)). in index form. Also find deg(omega).
377    */
378   deg_omega = 0;
379   for (i = 0; i < NN-KK;i++){
380     tmp = 0;
381     j = (deg_lambda < i) ? deg_lambda : i;
382     for(;j >= 0; j--){
383       if ((s[i + 1 - j] != A0) && (lambda[j] != A0))
384         tmp ^= Alpha_to[modnn(s[i + 1 - j] + lambda[j])];
385     }
386     if(tmp != 0)
387       deg_omega = i;
388     omega[i] = Index_of[tmp];
389   }
390   omega[NN-KK] = A0;
391
392   /*
393    * Compute error values in poly-form. num1 = omega(inv(X(l))), num2 =
394    * inv(X(l))**(B0-1) and den = lambda_pr(inv(X(l))) all in poly-form
395    */
396   for (j = count-1; j >=0; j--) {
397     num1 = 0;
398     for (i = deg_omega; i >= 0; i--) {
399       if (omega[i] != A0)
400         num1  ^= Alpha_to[modnn(omega[i] + i * root[j])];
401     }
402     num2 = Alpha_to[modnn(root[j] * (B0 - 1) + NN)];
403     den = 0;
404
405     /* lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i] */
406     for (i = min(deg_lambda,NN-KK-1) & ~1; i >= 0; i -=2) {
407       if(lambda[i+1] != A0)
408         den ^= Alpha_to[modnn(lambda[i+1] + i * root[j])];
409     }
410     if (den == 0) {
411 #if DEBUG_ECC >= 1
412       printf("\n ERROR: denominator = 0\n");
413 #endif
414       /* Convert to dual- basis */
415       count = -1;
416       goto finish;
417     }
418     /* Apply error to data */
419     if (num1 != 0) {
420         eras_val[j] = Alpha_to[modnn(Index_of[num1] + Index_of[num2] + NN - Index_of[den])];
421     } else {
422         eras_val[j] = 0;
423     }
424   }
425  finish:
426   for(i=0;i<count;i++)
427       eras_pos[i] = loc[i];
428   return count;
429 }
430
431 /***************************************************************************/
432 /* The DOC specific code begins here */
433
434 #define SECTOR_SIZE 512
435 /* The sector bytes are packed into NB_DATA MM bits words */
436 #define NB_DATA (((SECTOR_SIZE + 1) * 8 + 6) / MM)
437
438 /*
439  * Correct the errors in 'sector[]' by using 'ecc1[]' which is the
440  * content of the feedback shift register applyied to the sector and
441  * the ECC. Return the number of errors corrected (and correct them in
442  * sector), or -1 if error
443  */
444 int doc_decode_ecc(unsigned char sector[SECTOR_SIZE], unsigned char ecc1[6])
445 {
446     int parity, i, nb_errors;
447     gf bb[NN - KK + 1];
448     gf error_val[NN-KK];
449     int error_pos[NN-KK], pos, bitpos, index, val;
450     dtype *Alpha_to, *Index_of;
451
452     /* init log and exp tables here to save memory. However, it is slower */
453     Alpha_to = kmalloc((NN + 1) * sizeof(dtype), GFP_KERNEL);
454     if (!Alpha_to)
455         return -1;
456
457     Index_of = kmalloc((NN + 1) * sizeof(dtype), GFP_KERNEL);
458     if (!Index_of) {
459         kfree(Alpha_to);
460         return -1;
461     }
462
463     generate_gf(Alpha_to, Index_of);
464
465     parity = ecc1[1];
466
467     bb[0] =  (ecc1[4] & 0xff) | ((ecc1[5] & 0x03) << 8);
468     bb[1] = ((ecc1[5] & 0xfc) >> 2) | ((ecc1[2] & 0x0f) << 6);
469     bb[2] = ((ecc1[2] & 0xf0) >> 4) | ((ecc1[3] & 0x3f) << 4);
470     bb[3] = ((ecc1[3] & 0xc0) >> 6) | ((ecc1[0] & 0xff) << 2);
471
472     nb_errors = eras_dec_rs(Alpha_to, Index_of, bb,
473                             error_val, error_pos, 0);
474     if (nb_errors <= 0)
475         goto the_end;
476
477     /* correct the errors */
478     for(i=0;i<nb_errors;i++) {
479         pos = error_pos[i];
480         if (pos >= NB_DATA && pos < KK) {
481             nb_errors = -1;
482             goto the_end;
483         }
484         if (pos < NB_DATA) {
485             /* extract bit position (MSB first) */
486             pos = 10 * (NB_DATA - 1 - pos) - 6;
487             /* now correct the following 10 bits. At most two bytes
488                can be modified since pos is even */
489             index = (pos >> 3) ^ 1;
490             bitpos = pos & 7;
491             if ((index >= 0 && index < SECTOR_SIZE) ||
492                 index == (SECTOR_SIZE + 1)) {
493                 val = error_val[i] >> (2 + bitpos);
494                 parity ^= val;
495                 if (index < SECTOR_SIZE)
496                     sector[index] ^= val;
497             }
498             index = ((pos >> 3) + 1) ^ 1;
499             bitpos = (bitpos + 10) & 7;
500             if (bitpos == 0)
501                 bitpos = 8;
502             if ((index >= 0 && index < SECTOR_SIZE) ||
503                 index == (SECTOR_SIZE + 1)) {
504                 val = error_val[i] << (8 - bitpos);
505                 parity ^= val;
506                 if (index < SECTOR_SIZE)
507                     sector[index] ^= val;
508             }
509         }
510     }
511
512     /* use parity to test extra errors */
513     if ((parity & 0xff) != 0)
514         nb_errors = -1;
515
516  the_end:
517     kfree(Alpha_to);
518     kfree(Index_of);
519     return nb_errors;
520 }
521
522 EXPORT_SYMBOL_GPL(doc_decode_ecc);
523
524 MODULE_LICENSE("GPL");
525 MODULE_AUTHOR("Fabrice Bellard <fabrice.bellard@netgem.com>");
526 MODULE_DESCRIPTION("ECC code for correcting errors detected by DiskOnChip 2000 and Millennium ECC hardware");