GNU Linux-libre 4.9.318-gnu1
[releases.git] / drivers / mtd / chips / cfi_cmdset_0002.c
1 /*
2  * Common Flash Interface support:
3  *   AMD & Fujitsu Standard Vendor Command Set (ID 0x0002)
4  *
5  * Copyright (C) 2000 Crossnet Co. <info@crossnet.co.jp>
6  * Copyright (C) 2004 Arcom Control Systems Ltd <linux@arcom.com>
7  * Copyright (C) 2005 MontaVista Software Inc. <source@mvista.com>
8  *
9  * 2_by_8 routines added by Simon Munton
10  *
11  * 4_by_16 work by Carolyn J. Smith
12  *
13  * XIP support hooks by Vitaly Wool (based on code for Intel flash
14  * by Nicolas Pitre)
15  *
16  * 25/09/2008 Christopher Moore: TopBottom fixup for many Macronix with CFI V1.0
17  *
18  * Occasionally maintained by Thayne Harbaugh tharbaugh at lnxi dot com
19  *
20  * This code is GPL
21  */
22
23 #include <linux/module.h>
24 #include <linux/types.h>
25 #include <linux/kernel.h>
26 #include <linux/sched.h>
27 #include <asm/io.h>
28 #include <asm/byteorder.h>
29
30 #include <linux/errno.h>
31 #include <linux/slab.h>
32 #include <linux/delay.h>
33 #include <linux/interrupt.h>
34 #include <linux/reboot.h>
35 #include <linux/of.h>
36 #include <linux/of_platform.h>
37 #include <linux/mtd/map.h>
38 #include <linux/mtd/mtd.h>
39 #include <linux/mtd/cfi.h>
40 #include <linux/mtd/xip.h>
41
42 #define AMD_BOOTLOC_BUG
43 #define FORCE_WORD_WRITE 0
44
45 #define MAX_RETRIES 3
46
47 #define SST49LF004B             0x0060
48 #define SST49LF040B             0x0050
49 #define SST49LF008A             0x005a
50 #define AT49BV6416              0x00d6
51
52 enum cfi_quirks {
53         CFI_QUIRK_DQ_TRUE_DATA = BIT(0),
54 };
55
56 static int cfi_amdstd_read (struct mtd_info *, loff_t, size_t, size_t *, u_char *);
57 static int cfi_amdstd_write_words(struct mtd_info *, loff_t, size_t, size_t *, const u_char *);
58 static int cfi_amdstd_write_buffers(struct mtd_info *, loff_t, size_t, size_t *, const u_char *);
59 static int cfi_amdstd_erase_chip(struct mtd_info *, struct erase_info *);
60 static int cfi_amdstd_erase_varsize(struct mtd_info *, struct erase_info *);
61 static void cfi_amdstd_sync (struct mtd_info *);
62 static int cfi_amdstd_suspend (struct mtd_info *);
63 static void cfi_amdstd_resume (struct mtd_info *);
64 static int cfi_amdstd_reboot(struct notifier_block *, unsigned long, void *);
65 static int cfi_amdstd_get_fact_prot_info(struct mtd_info *, size_t,
66                                          size_t *, struct otp_info *);
67 static int cfi_amdstd_get_user_prot_info(struct mtd_info *, size_t,
68                                          size_t *, struct otp_info *);
69 static int cfi_amdstd_secsi_read (struct mtd_info *, loff_t, size_t, size_t *, u_char *);
70 static int cfi_amdstd_read_fact_prot_reg(struct mtd_info *, loff_t, size_t,
71                                          size_t *, u_char *);
72 static int cfi_amdstd_read_user_prot_reg(struct mtd_info *, loff_t, size_t,
73                                          size_t *, u_char *);
74 static int cfi_amdstd_write_user_prot_reg(struct mtd_info *, loff_t, size_t,
75                                           size_t *, u_char *);
76 static int cfi_amdstd_lock_user_prot_reg(struct mtd_info *, loff_t, size_t);
77
78 static int cfi_amdstd_panic_write(struct mtd_info *mtd, loff_t to, size_t len,
79                                   size_t *retlen, const u_char *buf);
80
81 static void cfi_amdstd_destroy(struct mtd_info *);
82
83 struct mtd_info *cfi_cmdset_0002(struct map_info *, int);
84 static struct mtd_info *cfi_amdstd_setup (struct mtd_info *);
85
86 static int get_chip(struct map_info *map, struct flchip *chip, unsigned long adr, int mode);
87 static void put_chip(struct map_info *map, struct flchip *chip, unsigned long adr);
88 #include "fwh_lock.h"
89
90 static int cfi_atmel_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len);
91 static int cfi_atmel_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len);
92
93 static int cfi_ppb_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len);
94 static int cfi_ppb_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len);
95 static int cfi_ppb_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len);
96
97 static struct mtd_chip_driver cfi_amdstd_chipdrv = {
98         .probe          = NULL, /* Not usable directly */
99         .destroy        = cfi_amdstd_destroy,
100         .name           = "cfi_cmdset_0002",
101         .module         = THIS_MODULE
102 };
103
104
105 /* #define DEBUG_CFI_FEATURES */
106
107
108 #ifdef DEBUG_CFI_FEATURES
109 static void cfi_tell_features(struct cfi_pri_amdstd *extp)
110 {
111         const char* erase_suspend[3] = {
112                 "Not supported", "Read only", "Read/write"
113         };
114         const char* top_bottom[6] = {
115                 "No WP", "8x8KiB sectors at top & bottom, no WP",
116                 "Bottom boot", "Top boot",
117                 "Uniform, Bottom WP", "Uniform, Top WP"
118         };
119
120         printk("  Silicon revision: %d\n", extp->SiliconRevision >> 1);
121         printk("  Address sensitive unlock: %s\n",
122                (extp->SiliconRevision & 1) ? "Not required" : "Required");
123
124         if (extp->EraseSuspend < ARRAY_SIZE(erase_suspend))
125                 printk("  Erase Suspend: %s\n", erase_suspend[extp->EraseSuspend]);
126         else
127                 printk("  Erase Suspend: Unknown value %d\n", extp->EraseSuspend);
128
129         if (extp->BlkProt == 0)
130                 printk("  Block protection: Not supported\n");
131         else
132                 printk("  Block protection: %d sectors per group\n", extp->BlkProt);
133
134
135         printk("  Temporary block unprotect: %s\n",
136                extp->TmpBlkUnprotect ? "Supported" : "Not supported");
137         printk("  Block protect/unprotect scheme: %d\n", extp->BlkProtUnprot);
138         printk("  Number of simultaneous operations: %d\n", extp->SimultaneousOps);
139         printk("  Burst mode: %s\n",
140                extp->BurstMode ? "Supported" : "Not supported");
141         if (extp->PageMode == 0)
142                 printk("  Page mode: Not supported\n");
143         else
144                 printk("  Page mode: %d word page\n", extp->PageMode << 2);
145
146         printk("  Vpp Supply Minimum Program/Erase Voltage: %d.%d V\n",
147                extp->VppMin >> 4, extp->VppMin & 0xf);
148         printk("  Vpp Supply Maximum Program/Erase Voltage: %d.%d V\n",
149                extp->VppMax >> 4, extp->VppMax & 0xf);
150
151         if (extp->TopBottom < ARRAY_SIZE(top_bottom))
152                 printk("  Top/Bottom Boot Block: %s\n", top_bottom[extp->TopBottom]);
153         else
154                 printk("  Top/Bottom Boot Block: Unknown value %d\n", extp->TopBottom);
155 }
156 #endif
157
158 #ifdef AMD_BOOTLOC_BUG
159 /* Wheee. Bring me the head of someone at AMD. */
160 static void fixup_amd_bootblock(struct mtd_info *mtd)
161 {
162         struct map_info *map = mtd->priv;
163         struct cfi_private *cfi = map->fldrv_priv;
164         struct cfi_pri_amdstd *extp = cfi->cmdset_priv;
165         __u8 major = extp->MajorVersion;
166         __u8 minor = extp->MinorVersion;
167
168         if (((major << 8) | minor) < 0x3131) {
169                 /* CFI version 1.0 => don't trust bootloc */
170
171                 pr_debug("%s: JEDEC Vendor ID is 0x%02X Device ID is 0x%02X\n",
172                         map->name, cfi->mfr, cfi->id);
173
174                 /* AFAICS all 29LV400 with a bottom boot block have a device ID
175                  * of 0x22BA in 16-bit mode and 0xBA in 8-bit mode.
176                  * These were badly detected as they have the 0x80 bit set
177                  * so treat them as a special case.
178                  */
179                 if (((cfi->id == 0xBA) || (cfi->id == 0x22BA)) &&
180
181                         /* Macronix added CFI to their 2nd generation
182                          * MX29LV400C B/T but AFAICS no other 29LV400 (AMD,
183                          * Fujitsu, Spansion, EON, ESI and older Macronix)
184                          * has CFI.
185                          *
186                          * Therefore also check the manufacturer.
187                          * This reduces the risk of false detection due to
188                          * the 8-bit device ID.
189                          */
190                         (cfi->mfr == CFI_MFR_MACRONIX)) {
191                         pr_debug("%s: Macronix MX29LV400C with bottom boot block"
192                                 " detected\n", map->name);
193                         extp->TopBottom = 2;    /* bottom boot */
194                 } else
195                 if (cfi->id & 0x80) {
196                         printk(KERN_WARNING "%s: JEDEC Device ID is 0x%02X. Assuming broken CFI table.\n", map->name, cfi->id);
197                         extp->TopBottom = 3;    /* top boot */
198                 } else {
199                         extp->TopBottom = 2;    /* bottom boot */
200                 }
201
202                 pr_debug("%s: AMD CFI PRI V%c.%c has no boot block field;"
203                         " deduced %s from Device ID\n", map->name, major, minor,
204                         extp->TopBottom == 2 ? "bottom" : "top");
205         }
206 }
207 #endif
208
209 static void fixup_use_write_buffers(struct mtd_info *mtd)
210 {
211         struct map_info *map = mtd->priv;
212         struct cfi_private *cfi = map->fldrv_priv;
213         if (cfi->cfiq->BufWriteTimeoutTyp) {
214                 pr_debug("Using buffer write method\n" );
215                 mtd->_write = cfi_amdstd_write_buffers;
216         }
217 }
218
219 /* Atmel chips don't use the same PRI format as AMD chips */
220 static void fixup_convert_atmel_pri(struct mtd_info *mtd)
221 {
222         struct map_info *map = mtd->priv;
223         struct cfi_private *cfi = map->fldrv_priv;
224         struct cfi_pri_amdstd *extp = cfi->cmdset_priv;
225         struct cfi_pri_atmel atmel_pri;
226
227         memcpy(&atmel_pri, extp, sizeof(atmel_pri));
228         memset((char *)extp + 5, 0, sizeof(*extp) - 5);
229
230         if (atmel_pri.Features & 0x02)
231                 extp->EraseSuspend = 2;
232
233         /* Some chips got it backwards... */
234         if (cfi->id == AT49BV6416) {
235                 if (atmel_pri.BottomBoot)
236                         extp->TopBottom = 3;
237                 else
238                         extp->TopBottom = 2;
239         } else {
240                 if (atmel_pri.BottomBoot)
241                         extp->TopBottom = 2;
242                 else
243                         extp->TopBottom = 3;
244         }
245
246         /* burst write mode not supported */
247         cfi->cfiq->BufWriteTimeoutTyp = 0;
248         cfi->cfiq->BufWriteTimeoutMax = 0;
249 }
250
251 static void fixup_use_secsi(struct mtd_info *mtd)
252 {
253         /* Setup for chips with a secsi area */
254         mtd->_read_user_prot_reg = cfi_amdstd_secsi_read;
255         mtd->_read_fact_prot_reg = cfi_amdstd_secsi_read;
256 }
257
258 static void fixup_use_erase_chip(struct mtd_info *mtd)
259 {
260         struct map_info *map = mtd->priv;
261         struct cfi_private *cfi = map->fldrv_priv;
262         if ((cfi->cfiq->NumEraseRegions == 1) &&
263                 ((cfi->cfiq->EraseRegionInfo[0] & 0xffff) == 0)) {
264                 mtd->_erase = cfi_amdstd_erase_chip;
265         }
266
267 }
268
269 /*
270  * Some Atmel chips (e.g. the AT49BV6416) power-up with all sectors
271  * locked by default.
272  */
273 static void fixup_use_atmel_lock(struct mtd_info *mtd)
274 {
275         mtd->_lock = cfi_atmel_lock;
276         mtd->_unlock = cfi_atmel_unlock;
277         mtd->flags |= MTD_POWERUP_LOCK;
278 }
279
280 static void fixup_old_sst_eraseregion(struct mtd_info *mtd)
281 {
282         struct map_info *map = mtd->priv;
283         struct cfi_private *cfi = map->fldrv_priv;
284
285         /*
286          * These flashes report two separate eraseblock regions based on the
287          * sector_erase-size and block_erase-size, although they both operate on the
288          * same memory. This is not allowed according to CFI, so we just pick the
289          * sector_erase-size.
290          */
291         cfi->cfiq->NumEraseRegions = 1;
292 }
293
294 static void fixup_sst39vf(struct mtd_info *mtd)
295 {
296         struct map_info *map = mtd->priv;
297         struct cfi_private *cfi = map->fldrv_priv;
298
299         fixup_old_sst_eraseregion(mtd);
300
301         cfi->addr_unlock1 = 0x5555;
302         cfi->addr_unlock2 = 0x2AAA;
303 }
304
305 static void fixup_sst39vf_rev_b(struct mtd_info *mtd)
306 {
307         struct map_info *map = mtd->priv;
308         struct cfi_private *cfi = map->fldrv_priv;
309
310         fixup_old_sst_eraseregion(mtd);
311
312         cfi->addr_unlock1 = 0x555;
313         cfi->addr_unlock2 = 0x2AA;
314
315         cfi->sector_erase_cmd = CMD(0x50);
316 }
317
318 static void fixup_sst38vf640x_sectorsize(struct mtd_info *mtd)
319 {
320         struct map_info *map = mtd->priv;
321         struct cfi_private *cfi = map->fldrv_priv;
322
323         fixup_sst39vf_rev_b(mtd);
324
325         /*
326          * CFI reports 1024 sectors (0x03ff+1) of 64KBytes (0x0100*256) where
327          * it should report a size of 8KBytes (0x0020*256).
328          */
329         cfi->cfiq->EraseRegionInfo[0] = 0x002003ff;
330         pr_warning("%s: Bad 38VF640x CFI data; adjusting sector size from 64 to 8KiB\n", mtd->name);
331 }
332
333 static void fixup_s29gl064n_sectors(struct mtd_info *mtd)
334 {
335         struct map_info *map = mtd->priv;
336         struct cfi_private *cfi = map->fldrv_priv;
337
338         if ((cfi->cfiq->EraseRegionInfo[0] & 0xffff) == 0x003f) {
339                 cfi->cfiq->EraseRegionInfo[0] |= 0x0040;
340                 pr_warning("%s: Bad S29GL064N CFI data; adjust from 64 to 128 sectors\n", mtd->name);
341         }
342 }
343
344 static void fixup_s29gl032n_sectors(struct mtd_info *mtd)
345 {
346         struct map_info *map = mtd->priv;
347         struct cfi_private *cfi = map->fldrv_priv;
348
349         if ((cfi->cfiq->EraseRegionInfo[1] & 0xffff) == 0x007e) {
350                 cfi->cfiq->EraseRegionInfo[1] &= ~0x0040;
351                 pr_warning("%s: Bad S29GL032N CFI data; adjust from 127 to 63 sectors\n", mtd->name);
352         }
353 }
354
355 static void fixup_s29ns512p_sectors(struct mtd_info *mtd)
356 {
357         struct map_info *map = mtd->priv;
358         struct cfi_private *cfi = map->fldrv_priv;
359
360         /*
361          *  S29NS512P flash uses more than 8bits to report number of sectors,
362          * which is not permitted by CFI.
363          */
364         cfi->cfiq->EraseRegionInfo[0] = 0x020001ff;
365         pr_warning("%s: Bad S29NS512P CFI data; adjust to 512 sectors\n", mtd->name);
366 }
367
368 static void fixup_quirks(struct mtd_info *mtd)
369 {
370         struct map_info *map = mtd->priv;
371         struct cfi_private *cfi = map->fldrv_priv;
372
373         if (cfi->mfr == CFI_MFR_AMD && cfi->id == 0x0c01)
374                 cfi->quirks |= CFI_QUIRK_DQ_TRUE_DATA;
375 }
376
377 /* Used to fix CFI-Tables of chips without Extended Query Tables */
378 static struct cfi_fixup cfi_nopri_fixup_table[] = {
379         { CFI_MFR_SST, 0x234a, fixup_sst39vf }, /* SST39VF1602 */
380         { CFI_MFR_SST, 0x234b, fixup_sst39vf }, /* SST39VF1601 */
381         { CFI_MFR_SST, 0x235a, fixup_sst39vf }, /* SST39VF3202 */
382         { CFI_MFR_SST, 0x235b, fixup_sst39vf }, /* SST39VF3201 */
383         { CFI_MFR_SST, 0x235c, fixup_sst39vf_rev_b }, /* SST39VF3202B */
384         { CFI_MFR_SST, 0x235d, fixup_sst39vf_rev_b }, /* SST39VF3201B */
385         { CFI_MFR_SST, 0x236c, fixup_sst39vf_rev_b }, /* SST39VF6402B */
386         { CFI_MFR_SST, 0x236d, fixup_sst39vf_rev_b }, /* SST39VF6401B */
387         { 0, 0, NULL }
388 };
389
390 static struct cfi_fixup cfi_fixup_table[] = {
391         { CFI_MFR_ATMEL, CFI_ID_ANY, fixup_convert_atmel_pri },
392 #ifdef AMD_BOOTLOC_BUG
393         { CFI_MFR_AMD, CFI_ID_ANY, fixup_amd_bootblock },
394         { CFI_MFR_AMIC, CFI_ID_ANY, fixup_amd_bootblock },
395         { CFI_MFR_MACRONIX, CFI_ID_ANY, fixup_amd_bootblock },
396 #endif
397         { CFI_MFR_AMD, 0x0050, fixup_use_secsi },
398         { CFI_MFR_AMD, 0x0053, fixup_use_secsi },
399         { CFI_MFR_AMD, 0x0055, fixup_use_secsi },
400         { CFI_MFR_AMD, 0x0056, fixup_use_secsi },
401         { CFI_MFR_AMD, 0x005C, fixup_use_secsi },
402         { CFI_MFR_AMD, 0x005F, fixup_use_secsi },
403         { CFI_MFR_AMD, 0x0c01, fixup_s29gl064n_sectors },
404         { CFI_MFR_AMD, 0x1301, fixup_s29gl064n_sectors },
405         { CFI_MFR_AMD, 0x1a00, fixup_s29gl032n_sectors },
406         { CFI_MFR_AMD, 0x1a01, fixup_s29gl032n_sectors },
407         { CFI_MFR_AMD, 0x3f00, fixup_s29ns512p_sectors },
408         { CFI_MFR_SST, 0x536a, fixup_sst38vf640x_sectorsize }, /* SST38VF6402 */
409         { CFI_MFR_SST, 0x536b, fixup_sst38vf640x_sectorsize }, /* SST38VF6401 */
410         { CFI_MFR_SST, 0x536c, fixup_sst38vf640x_sectorsize }, /* SST38VF6404 */
411         { CFI_MFR_SST, 0x536d, fixup_sst38vf640x_sectorsize }, /* SST38VF6403 */
412 #if !FORCE_WORD_WRITE
413         { CFI_MFR_ANY, CFI_ID_ANY, fixup_use_write_buffers },
414 #endif
415         { CFI_MFR_ANY, CFI_ID_ANY, fixup_quirks },
416         { 0, 0, NULL }
417 };
418 static struct cfi_fixup jedec_fixup_table[] = {
419         { CFI_MFR_SST, SST49LF004B, fixup_use_fwh_lock },
420         { CFI_MFR_SST, SST49LF040B, fixup_use_fwh_lock },
421         { CFI_MFR_SST, SST49LF008A, fixup_use_fwh_lock },
422         { 0, 0, NULL }
423 };
424
425 static struct cfi_fixup fixup_table[] = {
426         /* The CFI vendor ids and the JEDEC vendor IDs appear
427          * to be common.  It is like the devices id's are as
428          * well.  This table is to pick all cases where
429          * we know that is the case.
430          */
431         { CFI_MFR_ANY, CFI_ID_ANY, fixup_use_erase_chip },
432         { CFI_MFR_ATMEL, AT49BV6416, fixup_use_atmel_lock },
433         { 0, 0, NULL }
434 };
435
436
437 static void cfi_fixup_major_minor(struct cfi_private *cfi,
438                                   struct cfi_pri_amdstd *extp)
439 {
440         if (cfi->mfr == CFI_MFR_SAMSUNG) {
441                 if ((extp->MajorVersion == '0' && extp->MinorVersion == '0') ||
442                     (extp->MajorVersion == '3' && extp->MinorVersion == '3')) {
443                         /*
444                          * Samsung K8P2815UQB and K8D6x16UxM chips
445                          * report major=0 / minor=0.
446                          * K8D3x16UxC chips report major=3 / minor=3.
447                          */
448                         printk(KERN_NOTICE "  Fixing Samsung's Amd/Fujitsu"
449                                " Extended Query version to 1.%c\n",
450                                extp->MinorVersion);
451                         extp->MajorVersion = '1';
452                 }
453         }
454
455         /*
456          * SST 38VF640x chips report major=0xFF / minor=0xFF.
457          */
458         if (cfi->mfr == CFI_MFR_SST && (cfi->id >> 4) == 0x0536) {
459                 extp->MajorVersion = '1';
460                 extp->MinorVersion = '0';
461         }
462 }
463
464 static int is_m29ew(struct cfi_private *cfi)
465 {
466         if (cfi->mfr == CFI_MFR_INTEL &&
467             ((cfi->device_type == CFI_DEVICETYPE_X8 && (cfi->id & 0xff) == 0x7e) ||
468              (cfi->device_type == CFI_DEVICETYPE_X16 && cfi->id == 0x227e)))
469                 return 1;
470         return 0;
471 }
472
473 /*
474  * From TN-13-07: Patching the Linux Kernel and U-Boot for M29 Flash, page 20:
475  * Some revisions of the M29EW suffer from erase suspend hang ups. In
476  * particular, it can occur when the sequence
477  * Erase Confirm -> Suspend -> Program -> Resume
478  * causes a lockup due to internal timing issues. The consequence is that the
479  * erase cannot be resumed without inserting a dummy command after programming
480  * and prior to resuming. [...] The work-around is to issue a dummy write cycle
481  * that writes an F0 command code before the RESUME command.
482  */
483 static void cfi_fixup_m29ew_erase_suspend(struct map_info *map,
484                                           unsigned long adr)
485 {
486         struct cfi_private *cfi = map->fldrv_priv;
487         /* before resume, insert a dummy 0xF0 cycle for Micron M29EW devices */
488         if (is_m29ew(cfi))
489                 map_write(map, CMD(0xF0), adr);
490 }
491
492 /*
493  * From TN-13-07: Patching the Linux Kernel and U-Boot for M29 Flash, page 22:
494  *
495  * Some revisions of the M29EW (for example, A1 and A2 step revisions)
496  * are affected by a problem that could cause a hang up when an ERASE SUSPEND
497  * command is issued after an ERASE RESUME operation without waiting for a
498  * minimum delay.  The result is that once the ERASE seems to be completed
499  * (no bits are toggling), the contents of the Flash memory block on which
500  * the erase was ongoing could be inconsistent with the expected values
501  * (typically, the array value is stuck to the 0xC0, 0xC4, 0x80, or 0x84
502  * values), causing a consequent failure of the ERASE operation.
503  * The occurrence of this issue could be high, especially when file system
504  * operations on the Flash are intensive.  As a result, it is recommended
505  * that a patch be applied.  Intensive file system operations can cause many
506  * calls to the garbage routine to free Flash space (also by erasing physical
507  * Flash blocks) and as a result, many consecutive SUSPEND and RESUME
508  * commands can occur.  The problem disappears when a delay is inserted after
509  * the RESUME command by using the udelay() function available in Linux.
510  * The DELAY value must be tuned based on the customer's platform.
511  * The maximum value that fixes the problem in all cases is 500us.
512  * But, in our experience, a delay of 30 Âµs to 50 Âµs is sufficient
513  * in most cases.
514  * We have chosen 500µs because this latency is acceptable.
515  */
516 static void cfi_fixup_m29ew_delay_after_resume(struct cfi_private *cfi)
517 {
518         /*
519          * Resolving the Delay After Resume Issue see Micron TN-13-07
520          * Worst case delay must be 500µs but 30-50µs should be ok as well
521          */
522         if (is_m29ew(cfi))
523                 cfi_udelay(500);
524 }
525
526 struct mtd_info *cfi_cmdset_0002(struct map_info *map, int primary)
527 {
528         struct cfi_private *cfi = map->fldrv_priv;
529         struct device_node __maybe_unused *np = map->device_node;
530         struct mtd_info *mtd;
531         int i;
532
533         mtd = kzalloc(sizeof(*mtd), GFP_KERNEL);
534         if (!mtd)
535                 return NULL;
536         mtd->priv = map;
537         mtd->type = MTD_NORFLASH;
538
539         /* Fill in the default mtd operations */
540         mtd->_erase   = cfi_amdstd_erase_varsize;
541         mtd->_write   = cfi_amdstd_write_words;
542         mtd->_read    = cfi_amdstd_read;
543         mtd->_sync    = cfi_amdstd_sync;
544         mtd->_suspend = cfi_amdstd_suspend;
545         mtd->_resume  = cfi_amdstd_resume;
546         mtd->_read_user_prot_reg = cfi_amdstd_read_user_prot_reg;
547         mtd->_read_fact_prot_reg = cfi_amdstd_read_fact_prot_reg;
548         mtd->_get_fact_prot_info = cfi_amdstd_get_fact_prot_info;
549         mtd->_get_user_prot_info = cfi_amdstd_get_user_prot_info;
550         mtd->_write_user_prot_reg = cfi_amdstd_write_user_prot_reg;
551         mtd->_lock_user_prot_reg = cfi_amdstd_lock_user_prot_reg;
552         mtd->flags   = MTD_CAP_NORFLASH;
553         mtd->name    = map->name;
554         mtd->writesize = 1;
555         mtd->writebufsize = cfi_interleave(cfi) << cfi->cfiq->MaxBufWriteSize;
556
557         pr_debug("MTD %s(): write buffer size %d\n", __func__,
558                         mtd->writebufsize);
559
560         mtd->_panic_write = cfi_amdstd_panic_write;
561         mtd->reboot_notifier.notifier_call = cfi_amdstd_reboot;
562
563         if (cfi->cfi_mode==CFI_MODE_CFI){
564                 unsigned char bootloc;
565                 __u16 adr = primary?cfi->cfiq->P_ADR:cfi->cfiq->A_ADR;
566                 struct cfi_pri_amdstd *extp;
567
568                 extp = (struct cfi_pri_amdstd*)cfi_read_pri(map, adr, sizeof(*extp), "Amd/Fujitsu");
569                 if (extp) {
570                         /*
571                          * It's a real CFI chip, not one for which the probe
572                          * routine faked a CFI structure.
573                          */
574                         cfi_fixup_major_minor(cfi, extp);
575
576                         /*
577                          * Valid primary extension versions are: 1.0, 1.1, 1.2, 1.3, 1.4, 1.5
578                          * see: http://cs.ozerki.net/zap/pub/axim-x5/docs/cfi_r20.pdf, page 19 
579                          *      http://www.spansion.com/Support/AppNotes/cfi_100_20011201.pdf
580                          *      http://www.spansion.com/Support/Datasheets/s29ws-p_00_a12_e.pdf
581                          *      http://www.spansion.com/Support/Datasheets/S29GL_128S_01GS_00_02_e.pdf
582                          */
583                         if (extp->MajorVersion != '1' ||
584                             (extp->MajorVersion == '1' && (extp->MinorVersion < '0' || extp->MinorVersion > '5'))) {
585                                 printk(KERN_ERR "  Unknown Amd/Fujitsu Extended Query "
586                                        "version %c.%c (%#02x/%#02x).\n",
587                                        extp->MajorVersion, extp->MinorVersion,
588                                        extp->MajorVersion, extp->MinorVersion);
589                                 kfree(extp);
590                                 kfree(mtd);
591                                 return NULL;
592                         }
593
594                         printk(KERN_INFO "  Amd/Fujitsu Extended Query version %c.%c.\n",
595                                extp->MajorVersion, extp->MinorVersion);
596
597                         /* Install our own private info structure */
598                         cfi->cmdset_priv = extp;
599
600                         /* Apply cfi device specific fixups */
601                         cfi_fixup(mtd, cfi_fixup_table);
602
603 #ifdef DEBUG_CFI_FEATURES
604                         /* Tell the user about it in lots of lovely detail */
605                         cfi_tell_features(extp);
606 #endif
607
608 #ifdef CONFIG_OF
609                         if (np && of_property_read_bool(
610                                     np, "use-advanced-sector-protection")
611                             && extp->BlkProtUnprot == 8) {
612                                 printk(KERN_INFO "  Advanced Sector Protection (PPB Locking) supported\n");
613                                 mtd->_lock = cfi_ppb_lock;
614                                 mtd->_unlock = cfi_ppb_unlock;
615                                 mtd->_is_locked = cfi_ppb_is_locked;
616                         }
617 #endif
618
619                         bootloc = extp->TopBottom;
620                         if ((bootloc < 2) || (bootloc > 5)) {
621                                 printk(KERN_WARNING "%s: CFI contains unrecognised boot "
622                                        "bank location (%d). Assuming bottom.\n",
623                                        map->name, bootloc);
624                                 bootloc = 2;
625                         }
626
627                         if (bootloc == 3 && cfi->cfiq->NumEraseRegions > 1) {
628                                 printk(KERN_WARNING "%s: Swapping erase regions for top-boot CFI table.\n", map->name);
629
630                                 for (i=0; i<cfi->cfiq->NumEraseRegions / 2; i++) {
631                                         int j = (cfi->cfiq->NumEraseRegions-1)-i;
632
633                                         swap(cfi->cfiq->EraseRegionInfo[i],
634                                              cfi->cfiq->EraseRegionInfo[j]);
635                                 }
636                         }
637                         /* Set the default CFI lock/unlock addresses */
638                         cfi->addr_unlock1 = 0x555;
639                         cfi->addr_unlock2 = 0x2aa;
640                 }
641                 cfi_fixup(mtd, cfi_nopri_fixup_table);
642
643                 if (!cfi->addr_unlock1 || !cfi->addr_unlock2) {
644                         kfree(mtd);
645                         return NULL;
646                 }
647
648         } /* CFI mode */
649         else if (cfi->cfi_mode == CFI_MODE_JEDEC) {
650                 /* Apply jedec specific fixups */
651                 cfi_fixup(mtd, jedec_fixup_table);
652         }
653         /* Apply generic fixups */
654         cfi_fixup(mtd, fixup_table);
655
656         for (i=0; i< cfi->numchips; i++) {
657                 cfi->chips[i].word_write_time = 1<<cfi->cfiq->WordWriteTimeoutTyp;
658                 cfi->chips[i].buffer_write_time = 1<<cfi->cfiq->BufWriteTimeoutTyp;
659                 cfi->chips[i].erase_time = 1<<cfi->cfiq->BlockEraseTimeoutTyp;
660                 /*
661                  * First calculate the timeout max according to timeout field
662                  * of struct cfi_ident that probed from chip's CFI aera, if
663                  * available. Specify a minimum of 2000us, in case the CFI data
664                  * is wrong.
665                  */
666                 if (cfi->cfiq->BufWriteTimeoutTyp &&
667                     cfi->cfiq->BufWriteTimeoutMax)
668                         cfi->chips[i].buffer_write_time_max =
669                                 1 << (cfi->cfiq->BufWriteTimeoutTyp +
670                                       cfi->cfiq->BufWriteTimeoutMax);
671                 else
672                         cfi->chips[i].buffer_write_time_max = 0;
673
674                 cfi->chips[i].buffer_write_time_max =
675                         max(cfi->chips[i].buffer_write_time_max, 2000);
676
677                 cfi->chips[i].ref_point_counter = 0;
678                 init_waitqueue_head(&(cfi->chips[i].wq));
679         }
680
681         map->fldrv = &cfi_amdstd_chipdrv;
682
683         return cfi_amdstd_setup(mtd);
684 }
685 struct mtd_info *cfi_cmdset_0006(struct map_info *map, int primary) __attribute__((alias("cfi_cmdset_0002")));
686 struct mtd_info *cfi_cmdset_0701(struct map_info *map, int primary) __attribute__((alias("cfi_cmdset_0002")));
687 EXPORT_SYMBOL_GPL(cfi_cmdset_0002);
688 EXPORT_SYMBOL_GPL(cfi_cmdset_0006);
689 EXPORT_SYMBOL_GPL(cfi_cmdset_0701);
690
691 static struct mtd_info *cfi_amdstd_setup(struct mtd_info *mtd)
692 {
693         struct map_info *map = mtd->priv;
694         struct cfi_private *cfi = map->fldrv_priv;
695         unsigned long devsize = (1<<cfi->cfiq->DevSize) * cfi->interleave;
696         unsigned long offset = 0;
697         int i,j;
698
699         printk(KERN_NOTICE "number of %s chips: %d\n",
700                (cfi->cfi_mode == CFI_MODE_CFI)?"CFI":"JEDEC",cfi->numchips);
701         /* Select the correct geometry setup */
702         mtd->size = devsize * cfi->numchips;
703
704         mtd->numeraseregions = cfi->cfiq->NumEraseRegions * cfi->numchips;
705         mtd->eraseregions = kmalloc(sizeof(struct mtd_erase_region_info)
706                                     * mtd->numeraseregions, GFP_KERNEL);
707         if (!mtd->eraseregions)
708                 goto setup_err;
709
710         for (i=0; i<cfi->cfiq->NumEraseRegions; i++) {
711                 unsigned long ernum, ersize;
712                 ersize = ((cfi->cfiq->EraseRegionInfo[i] >> 8) & ~0xff) * cfi->interleave;
713                 ernum = (cfi->cfiq->EraseRegionInfo[i] & 0xffff) + 1;
714
715                 if (mtd->erasesize < ersize) {
716                         mtd->erasesize = ersize;
717                 }
718                 for (j=0; j<cfi->numchips; j++) {
719                         mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].offset = (j*devsize)+offset;
720                         mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].erasesize = ersize;
721                         mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].numblocks = ernum;
722                 }
723                 offset += (ersize * ernum);
724         }
725         if (offset != devsize) {
726                 /* Argh */
727                 printk(KERN_WARNING "Sum of regions (%lx) != total size of set of interleaved chips (%lx)\n", offset, devsize);
728                 goto setup_err;
729         }
730
731         __module_get(THIS_MODULE);
732         register_reboot_notifier(&mtd->reboot_notifier);
733         return mtd;
734
735  setup_err:
736         kfree(mtd->eraseregions);
737         kfree(mtd);
738         kfree(cfi->cmdset_priv);
739         return NULL;
740 }
741
742 /*
743  * Return true if the chip is ready and has the correct value.
744  *
745  * Ready is one of: read mode, query mode, erase-suspend-read mode (in any
746  * non-suspended sector) and is indicated by no toggle bits toggling.
747  *
748  * Error are indicated by toggling bits or bits held with the wrong value,
749  * or with bits toggling.
750  *
751  * Note that anything more complicated than checking if no bits are toggling
752  * (including checking DQ5 for an error status) is tricky to get working
753  * correctly and is therefore not done  (particularly with interleaved chips
754  * as each chip must be checked independently of the others).
755  */
756 static int __xipram chip_ready(struct map_info *map, unsigned long addr,
757                                map_word *expected)
758 {
759         map_word d, t;
760         int ret;
761
762         d = map_read(map, addr);
763         t = map_read(map, addr);
764
765         ret = map_word_equal(map, d, t);
766
767         if (!ret || !expected)
768                 return ret;
769
770         return map_word_equal(map, t, *expected);
771 }
772
773 static int __xipram chip_good(struct map_info *map, unsigned long addr,
774                               map_word *expected)
775 {
776         struct cfi_private *cfi = map->fldrv_priv;
777         map_word *datum = expected;
778
779         if (cfi->quirks & CFI_QUIRK_DQ_TRUE_DATA)
780                 datum = NULL;
781
782         return chip_ready(map, addr, datum);
783 }
784
785 static int get_chip(struct map_info *map, struct flchip *chip, unsigned long adr, int mode)
786 {
787         DECLARE_WAITQUEUE(wait, current);
788         struct cfi_private *cfi = map->fldrv_priv;
789         unsigned long timeo;
790         struct cfi_pri_amdstd *cfip = (struct cfi_pri_amdstd *)cfi->cmdset_priv;
791
792  resettime:
793         timeo = jiffies + HZ;
794  retry:
795         switch (chip->state) {
796
797         case FL_STATUS:
798                 for (;;) {
799                         if (chip_ready(map, adr, NULL))
800                                 break;
801
802                         if (time_after(jiffies, timeo)) {
803                                 printk(KERN_ERR "Waiting for chip to be ready timed out.\n");
804                                 return -EIO;
805                         }
806                         mutex_unlock(&chip->mutex);
807                         cfi_udelay(1);
808                         mutex_lock(&chip->mutex);
809                         /* Someone else might have been playing with it. */
810                         goto retry;
811                 }
812
813         case FL_READY:
814         case FL_CFI_QUERY:
815         case FL_JEDEC_QUERY:
816                 return 0;
817
818         case FL_ERASING:
819                 if (!cfip || !(cfip->EraseSuspend & (0x1|0x2)) ||
820                     !(mode == FL_READY || mode == FL_POINT ||
821                     (mode == FL_WRITING && (cfip->EraseSuspend & 0x2))))
822                         goto sleep;
823
824                 /* Do not allow suspend iff read/write to EB address */
825                 if ((adr & chip->in_progress_block_mask) ==
826                     chip->in_progress_block_addr)
827                         goto sleep;
828
829                 /* Erase suspend */
830                 /* It's harmless to issue the Erase-Suspend and Erase-Resume
831                  * commands when the erase algorithm isn't in progress. */
832                 map_write(map, CMD(0xB0), chip->in_progress_block_addr);
833                 chip->oldstate = FL_ERASING;
834                 chip->state = FL_ERASE_SUSPENDING;
835                 chip->erase_suspended = 1;
836                 for (;;) {
837                         if (chip_ready(map, adr, NULL))
838                                 break;
839
840                         if (time_after(jiffies, timeo)) {
841                                 /* Should have suspended the erase by now.
842                                  * Send an Erase-Resume command as either
843                                  * there was an error (so leave the erase
844                                  * routine to recover from it) or we trying to
845                                  * use the erase-in-progress sector. */
846                                 put_chip(map, chip, adr);
847                                 printk(KERN_ERR "MTD %s(): chip not ready after erase suspend\n", __func__);
848                                 return -EIO;
849                         }
850
851                         mutex_unlock(&chip->mutex);
852                         cfi_udelay(1);
853                         mutex_lock(&chip->mutex);
854                         /* Nobody will touch it while it's in state FL_ERASE_SUSPENDING.
855                            So we can just loop here. */
856                 }
857                 chip->state = FL_READY;
858                 return 0;
859
860         case FL_XIP_WHILE_ERASING:
861                 if (mode != FL_READY && mode != FL_POINT &&
862                     (!cfip || !(cfip->EraseSuspend&2)))
863                         goto sleep;
864                 chip->oldstate = chip->state;
865                 chip->state = FL_READY;
866                 return 0;
867
868         case FL_SHUTDOWN:
869                 /* The machine is rebooting */
870                 return -EIO;
871
872         case FL_POINT:
873                 /* Only if there's no operation suspended... */
874                 if (mode == FL_READY && chip->oldstate == FL_READY)
875                         return 0;
876
877         default:
878         sleep:
879                 set_current_state(TASK_UNINTERRUPTIBLE);
880                 add_wait_queue(&chip->wq, &wait);
881                 mutex_unlock(&chip->mutex);
882                 schedule();
883                 remove_wait_queue(&chip->wq, &wait);
884                 mutex_lock(&chip->mutex);
885                 goto resettime;
886         }
887 }
888
889
890 static void put_chip(struct map_info *map, struct flchip *chip, unsigned long adr)
891 {
892         struct cfi_private *cfi = map->fldrv_priv;
893
894         switch(chip->oldstate) {
895         case FL_ERASING:
896                 cfi_fixup_m29ew_erase_suspend(map,
897                         chip->in_progress_block_addr);
898                 map_write(map, cfi->sector_erase_cmd, chip->in_progress_block_addr);
899                 cfi_fixup_m29ew_delay_after_resume(cfi);
900                 chip->oldstate = FL_READY;
901                 chip->state = FL_ERASING;
902                 break;
903
904         case FL_XIP_WHILE_ERASING:
905                 chip->state = chip->oldstate;
906                 chip->oldstate = FL_READY;
907                 break;
908
909         case FL_READY:
910         case FL_STATUS:
911                 break;
912         default:
913                 printk(KERN_ERR "MTD: put_chip() called with oldstate %d!!\n", chip->oldstate);
914         }
915         wake_up(&chip->wq);
916 }
917
918 #ifdef CONFIG_MTD_XIP
919
920 /*
921  * No interrupt what so ever can be serviced while the flash isn't in array
922  * mode.  This is ensured by the xip_disable() and xip_enable() functions
923  * enclosing any code path where the flash is known not to be in array mode.
924  * And within a XIP disabled code path, only functions marked with __xipram
925  * may be called and nothing else (it's a good thing to inspect generated
926  * assembly to make sure inline functions were actually inlined and that gcc
927  * didn't emit calls to its own support functions). Also configuring MTD CFI
928  * support to a single buswidth and a single interleave is also recommended.
929  */
930
931 static void xip_disable(struct map_info *map, struct flchip *chip,
932                         unsigned long adr)
933 {
934         /* TODO: chips with no XIP use should ignore and return */
935         (void) map_read(map, adr); /* ensure mmu mapping is up to date */
936         local_irq_disable();
937 }
938
939 static void __xipram xip_enable(struct map_info *map, struct flchip *chip,
940                                 unsigned long adr)
941 {
942         struct cfi_private *cfi = map->fldrv_priv;
943
944         if (chip->state != FL_POINT && chip->state != FL_READY) {
945                 map_write(map, CMD(0xf0), adr);
946                 chip->state = FL_READY;
947         }
948         (void) map_read(map, adr);
949         xip_iprefetch();
950         local_irq_enable();
951 }
952
953 /*
954  * When a delay is required for the flash operation to complete, the
955  * xip_udelay() function is polling for both the given timeout and pending
956  * (but still masked) hardware interrupts.  Whenever there is an interrupt
957  * pending then the flash erase operation is suspended, array mode restored
958  * and interrupts unmasked.  Task scheduling might also happen at that
959  * point.  The CPU eventually returns from the interrupt or the call to
960  * schedule() and the suspended flash operation is resumed for the remaining
961  * of the delay period.
962  *
963  * Warning: this function _will_ fool interrupt latency tracing tools.
964  */
965
966 static void __xipram xip_udelay(struct map_info *map, struct flchip *chip,
967                                 unsigned long adr, int usec)
968 {
969         struct cfi_private *cfi = map->fldrv_priv;
970         struct cfi_pri_amdstd *extp = cfi->cmdset_priv;
971         map_word status, OK = CMD(0x80);
972         unsigned long suspended, start = xip_currtime();
973         flstate_t oldstate;
974
975         do {
976                 cpu_relax();
977                 if (xip_irqpending() && extp &&
978                     ((chip->state == FL_ERASING && (extp->EraseSuspend & 2))) &&
979                     (cfi_interleave_is_1(cfi) || chip->oldstate == FL_READY)) {
980                         /*
981                          * Let's suspend the erase operation when supported.
982                          * Note that we currently don't try to suspend
983                          * interleaved chips if there is already another
984                          * operation suspended (imagine what happens
985                          * when one chip was already done with the current
986                          * operation while another chip suspended it, then
987                          * we resume the whole thing at once).  Yes, it
988                          * can happen!
989                          */
990                         map_write(map, CMD(0xb0), adr);
991                         usec -= xip_elapsed_since(start);
992                         suspended = xip_currtime();
993                         do {
994                                 if (xip_elapsed_since(suspended) > 100000) {
995                                         /*
996                                          * The chip doesn't want to suspend
997                                          * after waiting for 100 msecs.
998                                          * This is a critical error but there
999                                          * is not much we can do here.
1000                                          */
1001                                         return;
1002                                 }
1003                                 status = map_read(map, adr);
1004                         } while (!map_word_andequal(map, status, OK, OK));
1005
1006                         /* Suspend succeeded */
1007                         oldstate = chip->state;
1008                         if (!map_word_bitsset(map, status, CMD(0x40)))
1009                                 break;
1010                         chip->state = FL_XIP_WHILE_ERASING;
1011                         chip->erase_suspended = 1;
1012                         map_write(map, CMD(0xf0), adr);
1013                         (void) map_read(map, adr);
1014                         xip_iprefetch();
1015                         local_irq_enable();
1016                         mutex_unlock(&chip->mutex);
1017                         xip_iprefetch();
1018                         cond_resched();
1019
1020                         /*
1021                          * We're back.  However someone else might have
1022                          * decided to go write to the chip if we are in
1023                          * a suspended erase state.  If so let's wait
1024                          * until it's done.
1025                          */
1026                         mutex_lock(&chip->mutex);
1027                         while (chip->state != FL_XIP_WHILE_ERASING) {
1028                                 DECLARE_WAITQUEUE(wait, current);
1029                                 set_current_state(TASK_UNINTERRUPTIBLE);
1030                                 add_wait_queue(&chip->wq, &wait);
1031                                 mutex_unlock(&chip->mutex);
1032                                 schedule();
1033                                 remove_wait_queue(&chip->wq, &wait);
1034                                 mutex_lock(&chip->mutex);
1035                         }
1036                         /* Disallow XIP again */
1037                         local_irq_disable();
1038
1039                         /* Correct Erase Suspend Hangups for M29EW */
1040                         cfi_fixup_m29ew_erase_suspend(map, adr);
1041                         /* Resume the write or erase operation */
1042                         map_write(map, cfi->sector_erase_cmd, adr);
1043                         chip->state = oldstate;
1044                         start = xip_currtime();
1045                 } else if (usec >= 1000000/HZ) {
1046                         /*
1047                          * Try to save on CPU power when waiting delay
1048                          * is at least a system timer tick period.
1049                          * No need to be extremely accurate here.
1050                          */
1051                         xip_cpu_idle();
1052                 }
1053                 status = map_read(map, adr);
1054         } while (!map_word_andequal(map, status, OK, OK)
1055                  && xip_elapsed_since(start) < usec);
1056 }
1057
1058 #define UDELAY(map, chip, adr, usec)  xip_udelay(map, chip, adr, usec)
1059
1060 /*
1061  * The INVALIDATE_CACHED_RANGE() macro is normally used in parallel while
1062  * the flash is actively programming or erasing since we have to poll for
1063  * the operation to complete anyway.  We can't do that in a generic way with
1064  * a XIP setup so do it before the actual flash operation in this case
1065  * and stub it out from INVALIDATE_CACHE_UDELAY.
1066  */
1067 #define XIP_INVAL_CACHED_RANGE(map, from, size)  \
1068         INVALIDATE_CACHED_RANGE(map, from, size)
1069
1070 #define INVALIDATE_CACHE_UDELAY(map, chip, adr, len, usec)  \
1071         UDELAY(map, chip, adr, usec)
1072
1073 /*
1074  * Extra notes:
1075  *
1076  * Activating this XIP support changes the way the code works a bit.  For
1077  * example the code to suspend the current process when concurrent access
1078  * happens is never executed because xip_udelay() will always return with the
1079  * same chip state as it was entered with.  This is why there is no care for
1080  * the presence of add_wait_queue() or schedule() calls from within a couple
1081  * xip_disable()'d  areas of code, like in do_erase_oneblock for example.
1082  * The queueing and scheduling are always happening within xip_udelay().
1083  *
1084  * Similarly, get_chip() and put_chip() just happen to always be executed
1085  * with chip->state set to FL_READY (or FL_XIP_WHILE_*) where flash state
1086  * is in array mode, therefore never executing many cases therein and not
1087  * causing any problem with XIP.
1088  */
1089
1090 #else
1091
1092 #define xip_disable(map, chip, adr)
1093 #define xip_enable(map, chip, adr)
1094 #define XIP_INVAL_CACHED_RANGE(x...)
1095
1096 #define UDELAY(map, chip, adr, usec)  \
1097 do {  \
1098         mutex_unlock(&chip->mutex);  \
1099         cfi_udelay(usec);  \
1100         mutex_lock(&chip->mutex);  \
1101 } while (0)
1102
1103 #define INVALIDATE_CACHE_UDELAY(map, chip, adr, len, usec)  \
1104 do {  \
1105         mutex_unlock(&chip->mutex);  \
1106         INVALIDATE_CACHED_RANGE(map, adr, len);  \
1107         cfi_udelay(usec);  \
1108         mutex_lock(&chip->mutex);  \
1109 } while (0)
1110
1111 #endif
1112
1113 static inline int do_read_onechip(struct map_info *map, struct flchip *chip, loff_t adr, size_t len, u_char *buf)
1114 {
1115         unsigned long cmd_addr;
1116         struct cfi_private *cfi = map->fldrv_priv;
1117         int ret;
1118
1119         adr += chip->start;
1120
1121         /* Ensure cmd read/writes are aligned. */
1122         cmd_addr = adr & ~(map_bankwidth(map)-1);
1123
1124         mutex_lock(&chip->mutex);
1125         ret = get_chip(map, chip, cmd_addr, FL_READY);
1126         if (ret) {
1127                 mutex_unlock(&chip->mutex);
1128                 return ret;
1129         }
1130
1131         if (chip->state != FL_POINT && chip->state != FL_READY) {
1132                 map_write(map, CMD(0xf0), cmd_addr);
1133                 chip->state = FL_READY;
1134         }
1135
1136         map_copy_from(map, buf, adr, len);
1137
1138         put_chip(map, chip, cmd_addr);
1139
1140         mutex_unlock(&chip->mutex);
1141         return 0;
1142 }
1143
1144
1145 static int cfi_amdstd_read (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf)
1146 {
1147         struct map_info *map = mtd->priv;
1148         struct cfi_private *cfi = map->fldrv_priv;
1149         unsigned long ofs;
1150         int chipnum;
1151         int ret = 0;
1152
1153         /* ofs: offset within the first chip that the first read should start */
1154         chipnum = (from >> cfi->chipshift);
1155         ofs = from - (chipnum <<  cfi->chipshift);
1156
1157         while (len) {
1158                 unsigned long thislen;
1159
1160                 if (chipnum >= cfi->numchips)
1161                         break;
1162
1163                 if ((len + ofs -1) >> cfi->chipshift)
1164                         thislen = (1<<cfi->chipshift) - ofs;
1165                 else
1166                         thislen = len;
1167
1168                 ret = do_read_onechip(map, &cfi->chips[chipnum], ofs, thislen, buf);
1169                 if (ret)
1170                         break;
1171
1172                 *retlen += thislen;
1173                 len -= thislen;
1174                 buf += thislen;
1175
1176                 ofs = 0;
1177                 chipnum++;
1178         }
1179         return ret;
1180 }
1181
1182 typedef int (*otp_op_t)(struct map_info *map, struct flchip *chip,
1183                         loff_t adr, size_t len, u_char *buf, size_t grouplen);
1184
1185 static inline void otp_enter(struct map_info *map, struct flchip *chip,
1186                              loff_t adr, size_t len)
1187 {
1188         struct cfi_private *cfi = map->fldrv_priv;
1189
1190         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi,
1191                          cfi->device_type, NULL);
1192         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi,
1193                          cfi->device_type, NULL);
1194         cfi_send_gen_cmd(0x88, cfi->addr_unlock1, chip->start, map, cfi,
1195                          cfi->device_type, NULL);
1196
1197         INVALIDATE_CACHED_RANGE(map, chip->start + adr, len);
1198 }
1199
1200 static inline void otp_exit(struct map_info *map, struct flchip *chip,
1201                             loff_t adr, size_t len)
1202 {
1203         struct cfi_private *cfi = map->fldrv_priv;
1204
1205         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi,
1206                          cfi->device_type, NULL);
1207         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi,
1208                          cfi->device_type, NULL);
1209         cfi_send_gen_cmd(0x90, cfi->addr_unlock1, chip->start, map, cfi,
1210                          cfi->device_type, NULL);
1211         cfi_send_gen_cmd(0x00, cfi->addr_unlock1, chip->start, map, cfi,
1212                          cfi->device_type, NULL);
1213
1214         INVALIDATE_CACHED_RANGE(map, chip->start + adr, len);
1215 }
1216
1217 static inline int do_read_secsi_onechip(struct map_info *map,
1218                                         struct flchip *chip, loff_t adr,
1219                                         size_t len, u_char *buf,
1220                                         size_t grouplen)
1221 {
1222         DECLARE_WAITQUEUE(wait, current);
1223         unsigned long timeo = jiffies + HZ;
1224
1225  retry:
1226         mutex_lock(&chip->mutex);
1227
1228         if (chip->state != FL_READY){
1229                 set_current_state(TASK_UNINTERRUPTIBLE);
1230                 add_wait_queue(&chip->wq, &wait);
1231
1232                 mutex_unlock(&chip->mutex);
1233
1234                 schedule();
1235                 remove_wait_queue(&chip->wq, &wait);
1236                 timeo = jiffies + HZ;
1237
1238                 goto retry;
1239         }
1240
1241         adr += chip->start;
1242
1243         chip->state = FL_READY;
1244
1245         otp_enter(map, chip, adr, len);
1246         map_copy_from(map, buf, adr, len);
1247         otp_exit(map, chip, adr, len);
1248
1249         wake_up(&chip->wq);
1250         mutex_unlock(&chip->mutex);
1251
1252         return 0;
1253 }
1254
1255 static int cfi_amdstd_secsi_read (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf)
1256 {
1257         struct map_info *map = mtd->priv;
1258         struct cfi_private *cfi = map->fldrv_priv;
1259         unsigned long ofs;
1260         int chipnum;
1261         int ret = 0;
1262
1263         /* ofs: offset within the first chip that the first read should start */
1264         /* 8 secsi bytes per chip */
1265         chipnum=from>>3;
1266         ofs=from & 7;
1267
1268         while (len) {
1269                 unsigned long thislen;
1270
1271                 if (chipnum >= cfi->numchips)
1272                         break;
1273
1274                 if ((len + ofs -1) >> 3)
1275                         thislen = (1<<3) - ofs;
1276                 else
1277                         thislen = len;
1278
1279                 ret = do_read_secsi_onechip(map, &cfi->chips[chipnum], ofs,
1280                                             thislen, buf, 0);
1281                 if (ret)
1282                         break;
1283
1284                 *retlen += thislen;
1285                 len -= thislen;
1286                 buf += thislen;
1287
1288                 ofs = 0;
1289                 chipnum++;
1290         }
1291         return ret;
1292 }
1293
1294 static int __xipram do_write_oneword(struct map_info *map, struct flchip *chip,
1295                                      unsigned long adr, map_word datum,
1296                                      int mode);
1297
1298 static int do_otp_write(struct map_info *map, struct flchip *chip, loff_t adr,
1299                         size_t len, u_char *buf, size_t grouplen)
1300 {
1301         int ret;
1302         while (len) {
1303                 unsigned long bus_ofs = adr & ~(map_bankwidth(map)-1);
1304                 int gap = adr - bus_ofs;
1305                 int n = min_t(int, len, map_bankwidth(map) - gap);
1306                 map_word datum = map_word_ff(map);
1307
1308                 if (n != map_bankwidth(map)) {
1309                         /* partial write of a word, load old contents */
1310                         otp_enter(map, chip, bus_ofs, map_bankwidth(map));
1311                         datum = map_read(map, bus_ofs);
1312                         otp_exit(map, chip, bus_ofs, map_bankwidth(map));
1313                 }
1314
1315                 datum = map_word_load_partial(map, datum, buf, gap, n);
1316                 ret = do_write_oneword(map, chip, bus_ofs, datum, FL_OTP_WRITE);
1317                 if (ret)
1318                         return ret;
1319
1320                 adr += n;
1321                 buf += n;
1322                 len -= n;
1323         }
1324
1325         return 0;
1326 }
1327
1328 static int do_otp_lock(struct map_info *map, struct flchip *chip, loff_t adr,
1329                        size_t len, u_char *buf, size_t grouplen)
1330 {
1331         struct cfi_private *cfi = map->fldrv_priv;
1332         uint8_t lockreg;
1333         unsigned long timeo;
1334         int ret;
1335
1336         /* make sure area matches group boundaries */
1337         if ((adr != 0) || (len != grouplen))
1338                 return -EINVAL;
1339
1340         mutex_lock(&chip->mutex);
1341         ret = get_chip(map, chip, chip->start, FL_LOCKING);
1342         if (ret) {
1343                 mutex_unlock(&chip->mutex);
1344                 return ret;
1345         }
1346         chip->state = FL_LOCKING;
1347
1348         /* Enter lock register command */
1349         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi,
1350                          cfi->device_type, NULL);
1351         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi,
1352                          cfi->device_type, NULL);
1353         cfi_send_gen_cmd(0x40, cfi->addr_unlock1, chip->start, map, cfi,
1354                          cfi->device_type, NULL);
1355
1356         /* read lock register */
1357         lockreg = cfi_read_query(map, 0);
1358
1359         /* set bit 0 to protect extended memory block */
1360         lockreg &= ~0x01;
1361
1362         /* set bit 0 to protect extended memory block */
1363         /* write lock register */
1364         map_write(map, CMD(0xA0), chip->start);
1365         map_write(map, CMD(lockreg), chip->start);
1366
1367         /* wait for chip to become ready */
1368         timeo = jiffies + msecs_to_jiffies(2);
1369         for (;;) {
1370                 if (chip_ready(map, adr, NULL))
1371                         break;
1372
1373                 if (time_after(jiffies, timeo)) {
1374                         pr_err("Waiting for chip to be ready timed out.\n");
1375                         ret = -EIO;
1376                         break;
1377                 }
1378                 UDELAY(map, chip, 0, 1);
1379         }
1380
1381         /* exit protection commands */
1382         map_write(map, CMD(0x90), chip->start);
1383         map_write(map, CMD(0x00), chip->start);
1384
1385         chip->state = FL_READY;
1386         put_chip(map, chip, chip->start);
1387         mutex_unlock(&chip->mutex);
1388
1389         return ret;
1390 }
1391
1392 static int cfi_amdstd_otp_walk(struct mtd_info *mtd, loff_t from, size_t len,
1393                                size_t *retlen, u_char *buf,
1394                                otp_op_t action, int user_regs)
1395 {
1396         struct map_info *map = mtd->priv;
1397         struct cfi_private *cfi = map->fldrv_priv;
1398         int ofs_factor = cfi->interleave * cfi->device_type;
1399         unsigned long base;
1400         int chipnum;
1401         struct flchip *chip;
1402         uint8_t otp, lockreg;
1403         int ret;
1404
1405         size_t user_size, factory_size, otpsize;
1406         loff_t user_offset, factory_offset, otpoffset;
1407         int user_locked = 0, otplocked;
1408
1409         *retlen = 0;
1410
1411         for (chipnum = 0; chipnum < cfi->numchips; chipnum++) {
1412                 chip = &cfi->chips[chipnum];
1413                 factory_size = 0;
1414                 user_size = 0;
1415
1416                 /* Micron M29EW family */
1417                 if (is_m29ew(cfi)) {
1418                         base = chip->start;
1419
1420                         /* check whether secsi area is factory locked
1421                            or user lockable */
1422                         mutex_lock(&chip->mutex);
1423                         ret = get_chip(map, chip, base, FL_CFI_QUERY);
1424                         if (ret) {
1425                                 mutex_unlock(&chip->mutex);
1426                                 return ret;
1427                         }
1428                         cfi_qry_mode_on(base, map, cfi);
1429                         otp = cfi_read_query(map, base + 0x3 * ofs_factor);
1430                         cfi_qry_mode_off(base, map, cfi);
1431                         put_chip(map, chip, base);
1432                         mutex_unlock(&chip->mutex);
1433
1434                         if (otp & 0x80) {
1435                                 /* factory locked */
1436                                 factory_offset = 0;
1437                                 factory_size = 0x100;
1438                         } else {
1439                                 /* customer lockable */
1440                                 user_offset = 0;
1441                                 user_size = 0x100;
1442
1443                                 mutex_lock(&chip->mutex);
1444                                 ret = get_chip(map, chip, base, FL_LOCKING);
1445                                 if (ret) {
1446                                         mutex_unlock(&chip->mutex);
1447                                         return ret;
1448                                 }
1449
1450                                 /* Enter lock register command */
1451                                 cfi_send_gen_cmd(0xAA, cfi->addr_unlock1,
1452                                                  chip->start, map, cfi,
1453                                                  cfi->device_type, NULL);
1454                                 cfi_send_gen_cmd(0x55, cfi->addr_unlock2,
1455                                                  chip->start, map, cfi,
1456                                                  cfi->device_type, NULL);
1457                                 cfi_send_gen_cmd(0x40, cfi->addr_unlock1,
1458                                                  chip->start, map, cfi,
1459                                                  cfi->device_type, NULL);
1460                                 /* read lock register */
1461                                 lockreg = cfi_read_query(map, 0);
1462                                 /* exit protection commands */
1463                                 map_write(map, CMD(0x90), chip->start);
1464                                 map_write(map, CMD(0x00), chip->start);
1465                                 put_chip(map, chip, chip->start);
1466                                 mutex_unlock(&chip->mutex);
1467
1468                                 user_locked = ((lockreg & 0x01) == 0x00);
1469                         }
1470                 }
1471
1472                 otpsize = user_regs ? user_size : factory_size;
1473                 if (!otpsize)
1474                         continue;
1475                 otpoffset = user_regs ? user_offset : factory_offset;
1476                 otplocked = user_regs ? user_locked : 1;
1477
1478                 if (!action) {
1479                         /* return otpinfo */
1480                         struct otp_info *otpinfo;
1481                         len -= sizeof(*otpinfo);
1482                         if (len <= 0)
1483                                 return -ENOSPC;
1484                         otpinfo = (struct otp_info *)buf;
1485                         otpinfo->start = from;
1486                         otpinfo->length = otpsize;
1487                         otpinfo->locked = otplocked;
1488                         buf += sizeof(*otpinfo);
1489                         *retlen += sizeof(*otpinfo);
1490                         from += otpsize;
1491                 } else if ((from < otpsize) && (len > 0)) {
1492                         size_t size;
1493                         size = (len < otpsize - from) ? len : otpsize - from;
1494                         ret = action(map, chip, otpoffset + from, size, buf,
1495                                      otpsize);
1496                         if (ret < 0)
1497                                 return ret;
1498
1499                         buf += size;
1500                         len -= size;
1501                         *retlen += size;
1502                         from = 0;
1503                 } else {
1504                         from -= otpsize;
1505                 }
1506         }
1507         return 0;
1508 }
1509
1510 static int cfi_amdstd_get_fact_prot_info(struct mtd_info *mtd, size_t len,
1511                                          size_t *retlen, struct otp_info *buf)
1512 {
1513         return cfi_amdstd_otp_walk(mtd, 0, len, retlen, (u_char *)buf,
1514                                    NULL, 0);
1515 }
1516
1517 static int cfi_amdstd_get_user_prot_info(struct mtd_info *mtd, size_t len,
1518                                          size_t *retlen, struct otp_info *buf)
1519 {
1520         return cfi_amdstd_otp_walk(mtd, 0, len, retlen, (u_char *)buf,
1521                                    NULL, 1);
1522 }
1523
1524 static int cfi_amdstd_read_fact_prot_reg(struct mtd_info *mtd, loff_t from,
1525                                          size_t len, size_t *retlen,
1526                                          u_char *buf)
1527 {
1528         return cfi_amdstd_otp_walk(mtd, from, len, retlen,
1529                                    buf, do_read_secsi_onechip, 0);
1530 }
1531
1532 static int cfi_amdstd_read_user_prot_reg(struct mtd_info *mtd, loff_t from,
1533                                          size_t len, size_t *retlen,
1534                                          u_char *buf)
1535 {
1536         return cfi_amdstd_otp_walk(mtd, from, len, retlen,
1537                                    buf, do_read_secsi_onechip, 1);
1538 }
1539
1540 static int cfi_amdstd_write_user_prot_reg(struct mtd_info *mtd, loff_t from,
1541                                           size_t len, size_t *retlen,
1542                                           u_char *buf)
1543 {
1544         return cfi_amdstd_otp_walk(mtd, from, len, retlen, buf,
1545                                    do_otp_write, 1);
1546 }
1547
1548 static int cfi_amdstd_lock_user_prot_reg(struct mtd_info *mtd, loff_t from,
1549                                          size_t len)
1550 {
1551         size_t retlen;
1552         return cfi_amdstd_otp_walk(mtd, from, len, &retlen, NULL,
1553                                    do_otp_lock, 1);
1554 }
1555
1556 static int __xipram do_write_oneword(struct map_info *map, struct flchip *chip,
1557                                      unsigned long adr, map_word datum,
1558                                      int mode)
1559 {
1560         struct cfi_private *cfi = map->fldrv_priv;
1561         unsigned long timeo = jiffies + HZ;
1562         /*
1563          * We use a 1ms + 1 jiffies generic timeout for writes (most devices
1564          * have a max write time of a few hundreds usec). However, we should
1565          * use the maximum timeout value given by the chip at probe time
1566          * instead.  Unfortunately, struct flchip does have a field for
1567          * maximum timeout, only for typical which can be far too short
1568          * depending of the conditions.  The ' + 1' is to avoid having a
1569          * timeout of 0 jiffies if HZ is smaller than 1000.
1570          */
1571         unsigned long uWriteTimeout = ( HZ / 1000 ) + 1;
1572         int ret = 0;
1573         map_word oldd;
1574         int retry_cnt = 0;
1575
1576         adr += chip->start;
1577
1578         mutex_lock(&chip->mutex);
1579         ret = get_chip(map, chip, adr, mode);
1580         if (ret) {
1581                 mutex_unlock(&chip->mutex);
1582                 return ret;
1583         }
1584
1585         pr_debug("MTD %s(): WRITE 0x%.8lx(0x%.8lx)\n",
1586                __func__, adr, datum.x[0] );
1587
1588         if (mode == FL_OTP_WRITE)
1589                 otp_enter(map, chip, adr, map_bankwidth(map));
1590
1591         /*
1592          * Check for a NOP for the case when the datum to write is already
1593          * present - it saves time and works around buggy chips that corrupt
1594          * data at other locations when 0xff is written to a location that
1595          * already contains 0xff.
1596          */
1597         oldd = map_read(map, adr);
1598         if (map_word_equal(map, oldd, datum)) {
1599                 pr_debug("MTD %s(): NOP\n",
1600                        __func__);
1601                 goto op_done;
1602         }
1603
1604         XIP_INVAL_CACHED_RANGE(map, adr, map_bankwidth(map));
1605         ENABLE_VPP(map);
1606         xip_disable(map, chip, adr);
1607
1608  retry:
1609         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
1610         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi, cfi->device_type, NULL);
1611         cfi_send_gen_cmd(0xA0, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
1612         map_write(map, datum, adr);
1613         chip->state = mode;
1614
1615         INVALIDATE_CACHE_UDELAY(map, chip,
1616                                 adr, map_bankwidth(map),
1617                                 chip->word_write_time);
1618
1619         /* See comment above for timeout value. */
1620         timeo = jiffies + uWriteTimeout;
1621         for (;;) {
1622                 if (chip->state != mode) {
1623                         /* Someone's suspended the write. Sleep */
1624                         DECLARE_WAITQUEUE(wait, current);
1625
1626                         set_current_state(TASK_UNINTERRUPTIBLE);
1627                         add_wait_queue(&chip->wq, &wait);
1628                         mutex_unlock(&chip->mutex);
1629                         schedule();
1630                         remove_wait_queue(&chip->wq, &wait);
1631                         timeo = jiffies + (HZ / 2); /* FIXME */
1632                         mutex_lock(&chip->mutex);
1633                         continue;
1634                 }
1635
1636                 /*
1637                  * We check "time_after" and "!chip_good" before checking
1638                  * "chip_good" to avoid the failure due to scheduling.
1639                  */
1640                 if (time_after(jiffies, timeo) &&
1641                     !chip_good(map, adr, &datum)) {
1642                         xip_enable(map, chip, adr);
1643                         printk(KERN_WARNING "MTD %s(): software timeout\n", __func__);
1644                         xip_disable(map, chip, adr);
1645                         ret = -EIO;
1646                         break;
1647                 }
1648
1649                 if (chip_good(map, adr, &datum))
1650                         break;
1651
1652                 /* Latency issues. Drop the lock, wait a while and retry */
1653                 UDELAY(map, chip, adr, 1);
1654         }
1655
1656         /* Did we succeed? */
1657         if (ret) {
1658                 /* reset on all failures. */
1659                 map_write( map, CMD(0xF0), chip->start );
1660                 /* FIXME - should have reset delay before continuing */
1661
1662                 if (++retry_cnt <= MAX_RETRIES) {
1663                         ret = 0;
1664                         goto retry;
1665                 }
1666         }
1667         xip_enable(map, chip, adr);
1668  op_done:
1669         if (mode == FL_OTP_WRITE)
1670                 otp_exit(map, chip, adr, map_bankwidth(map));
1671         chip->state = FL_READY;
1672         DISABLE_VPP(map);
1673         put_chip(map, chip, adr);
1674         mutex_unlock(&chip->mutex);
1675
1676         return ret;
1677 }
1678
1679
1680 static int cfi_amdstd_write_words(struct mtd_info *mtd, loff_t to, size_t len,
1681                                   size_t *retlen, const u_char *buf)
1682 {
1683         struct map_info *map = mtd->priv;
1684         struct cfi_private *cfi = map->fldrv_priv;
1685         int ret = 0;
1686         int chipnum;
1687         unsigned long ofs, chipstart;
1688         DECLARE_WAITQUEUE(wait, current);
1689
1690         chipnum = to >> cfi->chipshift;
1691         ofs = to  - (chipnum << cfi->chipshift);
1692         chipstart = cfi->chips[chipnum].start;
1693
1694         /* If it's not bus-aligned, do the first byte write */
1695         if (ofs & (map_bankwidth(map)-1)) {
1696                 unsigned long bus_ofs = ofs & ~(map_bankwidth(map)-1);
1697                 int i = ofs - bus_ofs;
1698                 int n = 0;
1699                 map_word tmp_buf;
1700
1701  retry:
1702                 mutex_lock(&cfi->chips[chipnum].mutex);
1703
1704                 if (cfi->chips[chipnum].state != FL_READY) {
1705                         set_current_state(TASK_UNINTERRUPTIBLE);
1706                         add_wait_queue(&cfi->chips[chipnum].wq, &wait);
1707
1708                         mutex_unlock(&cfi->chips[chipnum].mutex);
1709
1710                         schedule();
1711                         remove_wait_queue(&cfi->chips[chipnum].wq, &wait);
1712                         goto retry;
1713                 }
1714
1715                 /* Load 'tmp_buf' with old contents of flash */
1716                 tmp_buf = map_read(map, bus_ofs+chipstart);
1717
1718                 mutex_unlock(&cfi->chips[chipnum].mutex);
1719
1720                 /* Number of bytes to copy from buffer */
1721                 n = min_t(int, len, map_bankwidth(map)-i);
1722
1723                 tmp_buf = map_word_load_partial(map, tmp_buf, buf, i, n);
1724
1725                 ret = do_write_oneword(map, &cfi->chips[chipnum],
1726                                        bus_ofs, tmp_buf, FL_WRITING);
1727                 if (ret)
1728                         return ret;
1729
1730                 ofs += n;
1731                 buf += n;
1732                 (*retlen) += n;
1733                 len -= n;
1734
1735                 if (ofs >> cfi->chipshift) {
1736                         chipnum ++;
1737                         ofs = 0;
1738                         if (chipnum == cfi->numchips)
1739                                 return 0;
1740                 }
1741         }
1742
1743         /* We are now aligned, write as much as possible */
1744         while(len >= map_bankwidth(map)) {
1745                 map_word datum;
1746
1747                 datum = map_word_load(map, buf);
1748
1749                 ret = do_write_oneword(map, &cfi->chips[chipnum],
1750                                        ofs, datum, FL_WRITING);
1751                 if (ret)
1752                         return ret;
1753
1754                 ofs += map_bankwidth(map);
1755                 buf += map_bankwidth(map);
1756                 (*retlen) += map_bankwidth(map);
1757                 len -= map_bankwidth(map);
1758
1759                 if (ofs >> cfi->chipshift) {
1760                         chipnum ++;
1761                         ofs = 0;
1762                         if (chipnum == cfi->numchips)
1763                                 return 0;
1764                         chipstart = cfi->chips[chipnum].start;
1765                 }
1766         }
1767
1768         /* Write the trailing bytes if any */
1769         if (len & (map_bankwidth(map)-1)) {
1770                 map_word tmp_buf;
1771
1772  retry1:
1773                 mutex_lock(&cfi->chips[chipnum].mutex);
1774
1775                 if (cfi->chips[chipnum].state != FL_READY) {
1776                         set_current_state(TASK_UNINTERRUPTIBLE);
1777                         add_wait_queue(&cfi->chips[chipnum].wq, &wait);
1778
1779                         mutex_unlock(&cfi->chips[chipnum].mutex);
1780
1781                         schedule();
1782                         remove_wait_queue(&cfi->chips[chipnum].wq, &wait);
1783                         goto retry1;
1784                 }
1785
1786                 tmp_buf = map_read(map, ofs + chipstart);
1787
1788                 mutex_unlock(&cfi->chips[chipnum].mutex);
1789
1790                 tmp_buf = map_word_load_partial(map, tmp_buf, buf, 0, len);
1791
1792                 ret = do_write_oneword(map, &cfi->chips[chipnum],
1793                                        ofs, tmp_buf, FL_WRITING);
1794                 if (ret)
1795                         return ret;
1796
1797                 (*retlen) += len;
1798         }
1799
1800         return 0;
1801 }
1802
1803
1804 /*
1805  * FIXME: interleaved mode not tested, and probably not supported!
1806  */
1807 static int __xipram do_write_buffer(struct map_info *map, struct flchip *chip,
1808                                     unsigned long adr, const u_char *buf,
1809                                     int len)
1810 {
1811         struct cfi_private *cfi = map->fldrv_priv;
1812         unsigned long timeo = jiffies + HZ;
1813         /*
1814          * Timeout is calculated according to CFI data, if available.
1815          * See more comments in cfi_cmdset_0002().
1816          */
1817         unsigned long uWriteTimeout =
1818                                 usecs_to_jiffies(chip->buffer_write_time_max);
1819         int ret = -EIO;
1820         unsigned long cmd_adr;
1821         int z, words;
1822         map_word datum;
1823
1824         adr += chip->start;
1825         cmd_adr = adr;
1826
1827         mutex_lock(&chip->mutex);
1828         ret = get_chip(map, chip, adr, FL_WRITING);
1829         if (ret) {
1830                 mutex_unlock(&chip->mutex);
1831                 return ret;
1832         }
1833
1834         datum = map_word_load(map, buf);
1835
1836         pr_debug("MTD %s(): WRITE 0x%.8lx(0x%.8lx)\n",
1837                __func__, adr, datum.x[0] );
1838
1839         XIP_INVAL_CACHED_RANGE(map, adr, len);
1840         ENABLE_VPP(map);
1841         xip_disable(map, chip, cmd_adr);
1842
1843         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
1844         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi, cfi->device_type, NULL);
1845
1846         /* Write Buffer Load */
1847         map_write(map, CMD(0x25), cmd_adr);
1848
1849         chip->state = FL_WRITING_TO_BUFFER;
1850
1851         /* Write length of data to come */
1852         words = len / map_bankwidth(map);
1853         map_write(map, CMD(words - 1), cmd_adr);
1854         /* Write data */
1855         z = 0;
1856         while(z < words * map_bankwidth(map)) {
1857                 datum = map_word_load(map, buf);
1858                 map_write(map, datum, adr + z);
1859
1860                 z += map_bankwidth(map);
1861                 buf += map_bankwidth(map);
1862         }
1863         z -= map_bankwidth(map);
1864
1865         adr += z;
1866
1867         /* Write Buffer Program Confirm: GO GO GO */
1868         map_write(map, CMD(0x29), cmd_adr);
1869         chip->state = FL_WRITING;
1870
1871         INVALIDATE_CACHE_UDELAY(map, chip,
1872                                 adr, map_bankwidth(map),
1873                                 chip->word_write_time);
1874
1875         timeo = jiffies + uWriteTimeout;
1876
1877         for (;;) {
1878                 if (chip->state != FL_WRITING) {
1879                         /* Someone's suspended the write. Sleep */
1880                         DECLARE_WAITQUEUE(wait, current);
1881
1882                         set_current_state(TASK_UNINTERRUPTIBLE);
1883                         add_wait_queue(&chip->wq, &wait);
1884                         mutex_unlock(&chip->mutex);
1885                         schedule();
1886                         remove_wait_queue(&chip->wq, &wait);
1887                         timeo = jiffies + (HZ / 2); /* FIXME */
1888                         mutex_lock(&chip->mutex);
1889                         continue;
1890                 }
1891
1892                 /*
1893                  * We check "time_after" and "!chip_good" before checking
1894                  * "chip_good" to avoid the failure due to scheduling.
1895                  */
1896                 if (time_after(jiffies, timeo) && !chip_good(map, adr, &datum))
1897                         break;
1898
1899                 if (chip_good(map, adr, &datum)) {
1900                         xip_enable(map, chip, adr);
1901                         goto op_done;
1902                 }
1903
1904                 /* Latency issues. Drop the lock, wait a while and retry */
1905                 UDELAY(map, chip, adr, 1);
1906         }
1907
1908         /*
1909          * Recovery from write-buffer programming failures requires
1910          * the write-to-buffer-reset sequence.  Since the last part
1911          * of the sequence also works as a normal reset, we can run
1912          * the same commands regardless of why we are here.
1913          * See e.g.
1914          * http://www.spansion.com/Support/Application%20Notes/MirrorBit_Write_Buffer_Prog_Page_Buffer_Read_AN.pdf
1915          */
1916         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi,
1917                          cfi->device_type, NULL);
1918         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi,
1919                          cfi->device_type, NULL);
1920         cfi_send_gen_cmd(0xF0, cfi->addr_unlock1, chip->start, map, cfi,
1921                          cfi->device_type, NULL);
1922         xip_enable(map, chip, adr);
1923         /* FIXME - should have reset delay before continuing */
1924
1925         printk(KERN_WARNING "MTD %s(): software timeout, address:0x%.8lx.\n",
1926                __func__, adr);
1927
1928         ret = -EIO;
1929  op_done:
1930         chip->state = FL_READY;
1931         DISABLE_VPP(map);
1932         put_chip(map, chip, adr);
1933         mutex_unlock(&chip->mutex);
1934
1935         return ret;
1936 }
1937
1938
1939 static int cfi_amdstd_write_buffers(struct mtd_info *mtd, loff_t to, size_t len,
1940                                     size_t *retlen, const u_char *buf)
1941 {
1942         struct map_info *map = mtd->priv;
1943         struct cfi_private *cfi = map->fldrv_priv;
1944         int wbufsize = cfi_interleave(cfi) << cfi->cfiq->MaxBufWriteSize;
1945         int ret = 0;
1946         int chipnum;
1947         unsigned long ofs;
1948
1949         chipnum = to >> cfi->chipshift;
1950         ofs = to  - (chipnum << cfi->chipshift);
1951
1952         /* If it's not bus-aligned, do the first word write */
1953         if (ofs & (map_bankwidth(map)-1)) {
1954                 size_t local_len = (-ofs)&(map_bankwidth(map)-1);
1955                 if (local_len > len)
1956                         local_len = len;
1957                 ret = cfi_amdstd_write_words(mtd, ofs + (chipnum<<cfi->chipshift),
1958                                              local_len, retlen, buf);
1959                 if (ret)
1960                         return ret;
1961                 ofs += local_len;
1962                 buf += local_len;
1963                 len -= local_len;
1964
1965                 if (ofs >> cfi->chipshift) {
1966                         chipnum ++;
1967                         ofs = 0;
1968                         if (chipnum == cfi->numchips)
1969                                 return 0;
1970                 }
1971         }
1972
1973         /* Write buffer is worth it only if more than one word to write... */
1974         while (len >= map_bankwidth(map) * 2) {
1975                 /* We must not cross write block boundaries */
1976                 int size = wbufsize - (ofs & (wbufsize-1));
1977
1978                 if (size > len)
1979                         size = len;
1980                 if (size % map_bankwidth(map))
1981                         size -= size % map_bankwidth(map);
1982
1983                 ret = do_write_buffer(map, &cfi->chips[chipnum],
1984                                       ofs, buf, size);
1985                 if (ret)
1986                         return ret;
1987
1988                 ofs += size;
1989                 buf += size;
1990                 (*retlen) += size;
1991                 len -= size;
1992
1993                 if (ofs >> cfi->chipshift) {
1994                         chipnum ++;
1995                         ofs = 0;
1996                         if (chipnum == cfi->numchips)
1997                                 return 0;
1998                 }
1999         }
2000
2001         if (len) {
2002                 size_t retlen_dregs = 0;
2003
2004                 ret = cfi_amdstd_write_words(mtd, ofs + (chipnum<<cfi->chipshift),
2005                                              len, &retlen_dregs, buf);
2006
2007                 *retlen += retlen_dregs;
2008                 return ret;
2009         }
2010
2011         return 0;
2012 }
2013
2014 /*
2015  * Wait for the flash chip to become ready to write data
2016  *
2017  * This is only called during the panic_write() path. When panic_write()
2018  * is called, the kernel is in the process of a panic, and will soon be
2019  * dead. Therefore we don't take any locks, and attempt to get access
2020  * to the chip as soon as possible.
2021  */
2022 static int cfi_amdstd_panic_wait(struct map_info *map, struct flchip *chip,
2023                                  unsigned long adr)
2024 {
2025         struct cfi_private *cfi = map->fldrv_priv;
2026         int retries = 10;
2027         int i;
2028
2029         /*
2030          * If the driver thinks the chip is idle, and no toggle bits
2031          * are changing, then the chip is actually idle for sure.
2032          */
2033         if (chip->state == FL_READY && chip_ready(map, adr, NULL))
2034                 return 0;
2035
2036         /*
2037          * Try several times to reset the chip and then wait for it
2038          * to become idle. The upper limit of a few milliseconds of
2039          * delay isn't a big problem: the kernel is dying anyway. It
2040          * is more important to save the messages.
2041          */
2042         while (retries > 0) {
2043                 const unsigned long timeo = (HZ / 1000) + 1;
2044
2045                 /* send the reset command */
2046                 map_write(map, CMD(0xF0), chip->start);
2047
2048                 /* wait for the chip to become ready */
2049                 for (i = 0; i < jiffies_to_usecs(timeo); i++) {
2050                         if (chip_ready(map, adr, NULL))
2051                                 return 0;
2052
2053                         udelay(1);
2054                 }
2055
2056                 retries--;
2057         }
2058
2059         /* the chip never became ready */
2060         return -EBUSY;
2061 }
2062
2063 /*
2064  * Write out one word of data to a single flash chip during a kernel panic
2065  *
2066  * This is only called during the panic_write() path. When panic_write()
2067  * is called, the kernel is in the process of a panic, and will soon be
2068  * dead. Therefore we don't take any locks, and attempt to get access
2069  * to the chip as soon as possible.
2070  *
2071  * The implementation of this routine is intentionally similar to
2072  * do_write_oneword(), in order to ease code maintenance.
2073  */
2074 static int do_panic_write_oneword(struct map_info *map, struct flchip *chip,
2075                                   unsigned long adr, map_word datum)
2076 {
2077         const unsigned long uWriteTimeout = (HZ / 1000) + 1;
2078         struct cfi_private *cfi = map->fldrv_priv;
2079         int retry_cnt = 0;
2080         map_word oldd;
2081         int ret = 0;
2082         int i;
2083
2084         adr += chip->start;
2085
2086         ret = cfi_amdstd_panic_wait(map, chip, adr);
2087         if (ret)
2088                 return ret;
2089
2090         pr_debug("MTD %s(): PANIC WRITE 0x%.8lx(0x%.8lx)\n",
2091                         __func__, adr, datum.x[0]);
2092
2093         /*
2094          * Check for a NOP for the case when the datum to write is already
2095          * present - it saves time and works around buggy chips that corrupt
2096          * data at other locations when 0xff is written to a location that
2097          * already contains 0xff.
2098          */
2099         oldd = map_read(map, adr);
2100         if (map_word_equal(map, oldd, datum)) {
2101                 pr_debug("MTD %s(): NOP\n", __func__);
2102                 goto op_done;
2103         }
2104
2105         ENABLE_VPP(map);
2106
2107 retry:
2108         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2109         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi, cfi->device_type, NULL);
2110         cfi_send_gen_cmd(0xA0, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2111         map_write(map, datum, adr);
2112
2113         for (i = 0; i < jiffies_to_usecs(uWriteTimeout); i++) {
2114                 if (chip_ready(map, adr, NULL))
2115                         break;
2116
2117                 udelay(1);
2118         }
2119
2120         if (!chip_ready(map, adr, &datum)) {
2121                 /* reset on all failures. */
2122                 map_write(map, CMD(0xF0), chip->start);
2123                 /* FIXME - should have reset delay before continuing */
2124
2125                 if (++retry_cnt <= MAX_RETRIES)
2126                         goto retry;
2127
2128                 ret = -EIO;
2129         }
2130
2131 op_done:
2132         DISABLE_VPP(map);
2133         return ret;
2134 }
2135
2136 /*
2137  * Write out some data during a kernel panic
2138  *
2139  * This is used by the mtdoops driver to save the dying messages from a
2140  * kernel which has panic'd.
2141  *
2142  * This routine ignores all of the locking used throughout the rest of the
2143  * driver, in order to ensure that the data gets written out no matter what
2144  * state this driver (and the flash chip itself) was in when the kernel crashed.
2145  *
2146  * The implementation of this routine is intentionally similar to
2147  * cfi_amdstd_write_words(), in order to ease code maintenance.
2148  */
2149 static int cfi_amdstd_panic_write(struct mtd_info *mtd, loff_t to, size_t len,
2150                                   size_t *retlen, const u_char *buf)
2151 {
2152         struct map_info *map = mtd->priv;
2153         struct cfi_private *cfi = map->fldrv_priv;
2154         unsigned long ofs, chipstart;
2155         int ret = 0;
2156         int chipnum;
2157
2158         chipnum = to >> cfi->chipshift;
2159         ofs = to - (chipnum << cfi->chipshift);
2160         chipstart = cfi->chips[chipnum].start;
2161
2162         /* If it's not bus aligned, do the first byte write */
2163         if (ofs & (map_bankwidth(map) - 1)) {
2164                 unsigned long bus_ofs = ofs & ~(map_bankwidth(map) - 1);
2165                 int i = ofs - bus_ofs;
2166                 int n = 0;
2167                 map_word tmp_buf;
2168
2169                 ret = cfi_amdstd_panic_wait(map, &cfi->chips[chipnum], bus_ofs);
2170                 if (ret)
2171                         return ret;
2172
2173                 /* Load 'tmp_buf' with old contents of flash */
2174                 tmp_buf = map_read(map, bus_ofs + chipstart);
2175
2176                 /* Number of bytes to copy from buffer */
2177                 n = min_t(int, len, map_bankwidth(map) - i);
2178
2179                 tmp_buf = map_word_load_partial(map, tmp_buf, buf, i, n);
2180
2181                 ret = do_panic_write_oneword(map, &cfi->chips[chipnum],
2182                                              bus_ofs, tmp_buf);
2183                 if (ret)
2184                         return ret;
2185
2186                 ofs += n;
2187                 buf += n;
2188                 (*retlen) += n;
2189                 len -= n;
2190
2191                 if (ofs >> cfi->chipshift) {
2192                         chipnum++;
2193                         ofs = 0;
2194                         if (chipnum == cfi->numchips)
2195                                 return 0;
2196                 }
2197         }
2198
2199         /* We are now aligned, write as much as possible */
2200         while (len >= map_bankwidth(map)) {
2201                 map_word datum;
2202
2203                 datum = map_word_load(map, buf);
2204
2205                 ret = do_panic_write_oneword(map, &cfi->chips[chipnum],
2206                                              ofs, datum);
2207                 if (ret)
2208                         return ret;
2209
2210                 ofs += map_bankwidth(map);
2211                 buf += map_bankwidth(map);
2212                 (*retlen) += map_bankwidth(map);
2213                 len -= map_bankwidth(map);
2214
2215                 if (ofs >> cfi->chipshift) {
2216                         chipnum++;
2217                         ofs = 0;
2218                         if (chipnum == cfi->numchips)
2219                                 return 0;
2220
2221                         chipstart = cfi->chips[chipnum].start;
2222                 }
2223         }
2224
2225         /* Write the trailing bytes if any */
2226         if (len & (map_bankwidth(map) - 1)) {
2227                 map_word tmp_buf;
2228
2229                 ret = cfi_amdstd_panic_wait(map, &cfi->chips[chipnum], ofs);
2230                 if (ret)
2231                         return ret;
2232
2233                 tmp_buf = map_read(map, ofs + chipstart);
2234
2235                 tmp_buf = map_word_load_partial(map, tmp_buf, buf, 0, len);
2236
2237                 ret = do_panic_write_oneword(map, &cfi->chips[chipnum],
2238                                              ofs, tmp_buf);
2239                 if (ret)
2240                         return ret;
2241
2242                 (*retlen) += len;
2243         }
2244
2245         return 0;
2246 }
2247
2248
2249 /*
2250  * Handle devices with one erase region, that only implement
2251  * the chip erase command.
2252  */
2253 static int __xipram do_erase_chip(struct map_info *map, struct flchip *chip)
2254 {
2255         struct cfi_private *cfi = map->fldrv_priv;
2256         unsigned long timeo = jiffies + HZ;
2257         unsigned long int adr;
2258         DECLARE_WAITQUEUE(wait, current);
2259         int ret = 0;
2260         int retry_cnt = 0;
2261         map_word datum = map_word_ff(map);
2262
2263         adr = cfi->addr_unlock1;
2264
2265         mutex_lock(&chip->mutex);
2266         ret = get_chip(map, chip, adr, FL_WRITING);
2267         if (ret) {
2268                 mutex_unlock(&chip->mutex);
2269                 return ret;
2270         }
2271
2272         pr_debug("MTD %s(): ERASE 0x%.8lx\n",
2273                __func__, chip->start );
2274
2275         XIP_INVAL_CACHED_RANGE(map, adr, map->size);
2276         ENABLE_VPP(map);
2277         xip_disable(map, chip, adr);
2278
2279  retry:
2280         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2281         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi, cfi->device_type, NULL);
2282         cfi_send_gen_cmd(0x80, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2283         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2284         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi, cfi->device_type, NULL);
2285         cfi_send_gen_cmd(0x10, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2286
2287         chip->state = FL_ERASING;
2288         chip->erase_suspended = 0;
2289         chip->in_progress_block_addr = adr;
2290         chip->in_progress_block_mask = ~(map->size - 1);
2291
2292         INVALIDATE_CACHE_UDELAY(map, chip,
2293                                 adr, map->size,
2294                                 chip->erase_time*500);
2295
2296         timeo = jiffies + (HZ*20);
2297
2298         for (;;) {
2299                 if (chip->state != FL_ERASING) {
2300                         /* Someone's suspended the erase. Sleep */
2301                         set_current_state(TASK_UNINTERRUPTIBLE);
2302                         add_wait_queue(&chip->wq, &wait);
2303                         mutex_unlock(&chip->mutex);
2304                         schedule();
2305                         remove_wait_queue(&chip->wq, &wait);
2306                         mutex_lock(&chip->mutex);
2307                         continue;
2308                 }
2309                 if (chip->erase_suspended) {
2310                         /* This erase was suspended and resumed.
2311                            Adjust the timeout */
2312                         timeo = jiffies + (HZ*20); /* FIXME */
2313                         chip->erase_suspended = 0;
2314                 }
2315
2316                 if (chip_ready(map, adr, &datum))
2317                         break;
2318
2319                 if (time_after(jiffies, timeo)) {
2320                         printk(KERN_WARNING "MTD %s(): software timeout\n",
2321                                 __func__ );
2322                         ret = -EIO;
2323                         break;
2324                 }
2325
2326                 /* Latency issues. Drop the lock, wait a while and retry */
2327                 UDELAY(map, chip, adr, 1000000/HZ);
2328         }
2329         /* Did we succeed? */
2330         if (ret) {
2331                 /* reset on all failures. */
2332                 map_write( map, CMD(0xF0), chip->start );
2333                 /* FIXME - should have reset delay before continuing */
2334
2335                 if (++retry_cnt <= MAX_RETRIES) {
2336                         ret = 0;
2337                         goto retry;
2338                 }
2339         }
2340
2341         chip->state = FL_READY;
2342         xip_enable(map, chip, adr);
2343         DISABLE_VPP(map);
2344         put_chip(map, chip, adr);
2345         mutex_unlock(&chip->mutex);
2346
2347         return ret;
2348 }
2349
2350
2351 static int __xipram do_erase_oneblock(struct map_info *map, struct flchip *chip, unsigned long adr, int len, void *thunk)
2352 {
2353         struct cfi_private *cfi = map->fldrv_priv;
2354         unsigned long timeo = jiffies + HZ;
2355         DECLARE_WAITQUEUE(wait, current);
2356         int ret = 0;
2357         int retry_cnt = 0;
2358         map_word datum = map_word_ff(map);
2359
2360         adr += chip->start;
2361
2362         mutex_lock(&chip->mutex);
2363         ret = get_chip(map, chip, adr, FL_ERASING);
2364         if (ret) {
2365                 mutex_unlock(&chip->mutex);
2366                 return ret;
2367         }
2368
2369         pr_debug("MTD %s(): ERASE 0x%.8lx\n",
2370                __func__, adr );
2371
2372         XIP_INVAL_CACHED_RANGE(map, adr, len);
2373         ENABLE_VPP(map);
2374         xip_disable(map, chip, adr);
2375
2376  retry:
2377         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2378         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi, cfi->device_type, NULL);
2379         cfi_send_gen_cmd(0x80, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2380         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi, cfi->device_type, NULL);
2381         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi, cfi->device_type, NULL);
2382         map_write(map, cfi->sector_erase_cmd, adr);
2383
2384         chip->state = FL_ERASING;
2385         chip->erase_suspended = 0;
2386         chip->in_progress_block_addr = adr;
2387         chip->in_progress_block_mask = ~(len - 1);
2388
2389         INVALIDATE_CACHE_UDELAY(map, chip,
2390                                 adr, len,
2391                                 chip->erase_time*500);
2392
2393         timeo = jiffies + (HZ*20);
2394
2395         for (;;) {
2396                 if (chip->state != FL_ERASING) {
2397                         /* Someone's suspended the erase. Sleep */
2398                         set_current_state(TASK_UNINTERRUPTIBLE);
2399                         add_wait_queue(&chip->wq, &wait);
2400                         mutex_unlock(&chip->mutex);
2401                         schedule();
2402                         remove_wait_queue(&chip->wq, &wait);
2403                         mutex_lock(&chip->mutex);
2404                         continue;
2405                 }
2406                 if (chip->erase_suspended) {
2407                         /* This erase was suspended and resumed.
2408                            Adjust the timeout */
2409                         timeo = jiffies + (HZ*20); /* FIXME */
2410                         chip->erase_suspended = 0;
2411                 }
2412
2413                 if (chip_ready(map, adr, &datum)) {
2414                         xip_enable(map, chip, adr);
2415                         break;
2416                 }
2417
2418                 if (time_after(jiffies, timeo)) {
2419                         xip_enable(map, chip, adr);
2420                         printk(KERN_WARNING "MTD %s(): software timeout\n",
2421                                 __func__ );
2422                         ret = -EIO;
2423                         break;
2424                 }
2425
2426                 /* Latency issues. Drop the lock, wait a while and retry */
2427                 UDELAY(map, chip, adr, 1000000/HZ);
2428         }
2429         /* Did we succeed? */
2430         if (ret) {
2431                 /* reset on all failures. */
2432                 map_write( map, CMD(0xF0), chip->start );
2433                 /* FIXME - should have reset delay before continuing */
2434
2435                 if (++retry_cnt <= MAX_RETRIES) {
2436                         ret = 0;
2437                         goto retry;
2438                 }
2439         }
2440
2441         chip->state = FL_READY;
2442         DISABLE_VPP(map);
2443         put_chip(map, chip, adr);
2444         mutex_unlock(&chip->mutex);
2445         return ret;
2446 }
2447
2448
2449 static int cfi_amdstd_erase_varsize(struct mtd_info *mtd, struct erase_info *instr)
2450 {
2451         unsigned long ofs, len;
2452         int ret;
2453
2454         ofs = instr->addr;
2455         len = instr->len;
2456
2457         ret = cfi_varsize_frob(mtd, do_erase_oneblock, ofs, len, NULL);
2458         if (ret)
2459                 return ret;
2460
2461         instr->state = MTD_ERASE_DONE;
2462         mtd_erase_callback(instr);
2463
2464         return 0;
2465 }
2466
2467
2468 static int cfi_amdstd_erase_chip(struct mtd_info *mtd, struct erase_info *instr)
2469 {
2470         struct map_info *map = mtd->priv;
2471         struct cfi_private *cfi = map->fldrv_priv;
2472         int ret = 0;
2473
2474         if (instr->addr != 0)
2475                 return -EINVAL;
2476
2477         if (instr->len != mtd->size)
2478                 return -EINVAL;
2479
2480         ret = do_erase_chip(map, &cfi->chips[0]);
2481         if (ret)
2482                 return ret;
2483
2484         instr->state = MTD_ERASE_DONE;
2485         mtd_erase_callback(instr);
2486
2487         return 0;
2488 }
2489
2490 static int do_atmel_lock(struct map_info *map, struct flchip *chip,
2491                          unsigned long adr, int len, void *thunk)
2492 {
2493         struct cfi_private *cfi = map->fldrv_priv;
2494         int ret;
2495
2496         mutex_lock(&chip->mutex);
2497         ret = get_chip(map, chip, adr + chip->start, FL_LOCKING);
2498         if (ret)
2499                 goto out_unlock;
2500         chip->state = FL_LOCKING;
2501
2502         pr_debug("MTD %s(): LOCK 0x%08lx len %d\n", __func__, adr, len);
2503
2504         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi,
2505                          cfi->device_type, NULL);
2506         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi,
2507                          cfi->device_type, NULL);
2508         cfi_send_gen_cmd(0x80, cfi->addr_unlock1, chip->start, map, cfi,
2509                          cfi->device_type, NULL);
2510         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi,
2511                          cfi->device_type, NULL);
2512         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi,
2513                          cfi->device_type, NULL);
2514         map_write(map, CMD(0x40), chip->start + adr);
2515
2516         chip->state = FL_READY;
2517         put_chip(map, chip, adr + chip->start);
2518         ret = 0;
2519
2520 out_unlock:
2521         mutex_unlock(&chip->mutex);
2522         return ret;
2523 }
2524
2525 static int do_atmel_unlock(struct map_info *map, struct flchip *chip,
2526                            unsigned long adr, int len, void *thunk)
2527 {
2528         struct cfi_private *cfi = map->fldrv_priv;
2529         int ret;
2530
2531         mutex_lock(&chip->mutex);
2532         ret = get_chip(map, chip, adr + chip->start, FL_UNLOCKING);
2533         if (ret)
2534                 goto out_unlock;
2535         chip->state = FL_UNLOCKING;
2536
2537         pr_debug("MTD %s(): LOCK 0x%08lx len %d\n", __func__, adr, len);
2538
2539         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi,
2540                          cfi->device_type, NULL);
2541         map_write(map, CMD(0x70), adr);
2542
2543         chip->state = FL_READY;
2544         put_chip(map, chip, adr + chip->start);
2545         ret = 0;
2546
2547 out_unlock:
2548         mutex_unlock(&chip->mutex);
2549         return ret;
2550 }
2551
2552 static int cfi_atmel_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2553 {
2554         return cfi_varsize_frob(mtd, do_atmel_lock, ofs, len, NULL);
2555 }
2556
2557 static int cfi_atmel_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2558 {
2559         return cfi_varsize_frob(mtd, do_atmel_unlock, ofs, len, NULL);
2560 }
2561
2562 /*
2563  * Advanced Sector Protection - PPB (Persistent Protection Bit) locking
2564  */
2565
2566 struct ppb_lock {
2567         struct flchip *chip;
2568         unsigned long adr;
2569         int locked;
2570 };
2571
2572 #define MAX_SECTORS                     512
2573
2574 #define DO_XXLOCK_ONEBLOCK_LOCK         ((void *)1)
2575 #define DO_XXLOCK_ONEBLOCK_UNLOCK       ((void *)2)
2576 #define DO_XXLOCK_ONEBLOCK_GETLOCK      ((void *)3)
2577
2578 static int __maybe_unused do_ppb_xxlock(struct map_info *map,
2579                                         struct flchip *chip,
2580                                         unsigned long adr, int len, void *thunk)
2581 {
2582         struct cfi_private *cfi = map->fldrv_priv;
2583         unsigned long timeo;
2584         int ret;
2585
2586         adr += chip->start;
2587         mutex_lock(&chip->mutex);
2588         ret = get_chip(map, chip, adr, FL_LOCKING);
2589         if (ret) {
2590                 mutex_unlock(&chip->mutex);
2591                 return ret;
2592         }
2593
2594         pr_debug("MTD %s(): XXLOCK 0x%08lx len %d\n", __func__, adr, len);
2595
2596         cfi_send_gen_cmd(0xAA, cfi->addr_unlock1, chip->start, map, cfi,
2597                          cfi->device_type, NULL);
2598         cfi_send_gen_cmd(0x55, cfi->addr_unlock2, chip->start, map, cfi,
2599                          cfi->device_type, NULL);
2600         /* PPB entry command */
2601         cfi_send_gen_cmd(0xC0, cfi->addr_unlock1, chip->start, map, cfi,
2602                          cfi->device_type, NULL);
2603
2604         if (thunk == DO_XXLOCK_ONEBLOCK_LOCK) {
2605                 chip->state = FL_LOCKING;
2606                 map_write(map, CMD(0xA0), adr);
2607                 map_write(map, CMD(0x00), adr);
2608         } else if (thunk == DO_XXLOCK_ONEBLOCK_UNLOCK) {
2609                 /*
2610                  * Unlocking of one specific sector is not supported, so we
2611                  * have to unlock all sectors of this device instead
2612                  */
2613                 chip->state = FL_UNLOCKING;
2614                 map_write(map, CMD(0x80), chip->start);
2615                 map_write(map, CMD(0x30), chip->start);
2616         } else if (thunk == DO_XXLOCK_ONEBLOCK_GETLOCK) {
2617                 chip->state = FL_JEDEC_QUERY;
2618                 /* Return locked status: 0->locked, 1->unlocked */
2619                 ret = !cfi_read_query(map, adr);
2620         } else
2621                 BUG();
2622
2623         /*
2624          * Wait for some time as unlocking of all sectors takes quite long
2625          */
2626         timeo = jiffies + msecs_to_jiffies(2000);       /* 2s max (un)locking */
2627         for (;;) {
2628                 if (chip_ready(map, adr, NULL))
2629                         break;
2630
2631                 if (time_after(jiffies, timeo)) {
2632                         printk(KERN_ERR "Waiting for chip to be ready timed out.\n");
2633                         ret = -EIO;
2634                         break;
2635                 }
2636
2637                 UDELAY(map, chip, adr, 1);
2638         }
2639
2640         /* Exit BC commands */
2641         map_write(map, CMD(0x90), chip->start);
2642         map_write(map, CMD(0x00), chip->start);
2643
2644         chip->state = FL_READY;
2645         put_chip(map, chip, adr);
2646         mutex_unlock(&chip->mutex);
2647
2648         return ret;
2649 }
2650
2651 static int __maybe_unused cfi_ppb_lock(struct mtd_info *mtd, loff_t ofs,
2652                                        uint64_t len)
2653 {
2654         return cfi_varsize_frob(mtd, do_ppb_xxlock, ofs, len,
2655                                 DO_XXLOCK_ONEBLOCK_LOCK);
2656 }
2657
2658 static int __maybe_unused cfi_ppb_unlock(struct mtd_info *mtd, loff_t ofs,
2659                                          uint64_t len)
2660 {
2661         struct mtd_erase_region_info *regions = mtd->eraseregions;
2662         struct map_info *map = mtd->priv;
2663         struct cfi_private *cfi = map->fldrv_priv;
2664         struct ppb_lock *sect;
2665         unsigned long adr;
2666         loff_t offset;
2667         uint64_t length;
2668         int chipnum;
2669         int i;
2670         int sectors;
2671         int ret;
2672
2673         /*
2674          * PPB unlocking always unlocks all sectors of the flash chip.
2675          * We need to re-lock all previously locked sectors. So lets
2676          * first check the locking status of all sectors and save
2677          * it for future use.
2678          */
2679         sect = kzalloc(MAX_SECTORS * sizeof(struct ppb_lock), GFP_KERNEL);
2680         if (!sect)
2681                 return -ENOMEM;
2682
2683         /*
2684          * This code to walk all sectors is a slightly modified version
2685          * of the cfi_varsize_frob() code.
2686          */
2687         i = 0;
2688         chipnum = 0;
2689         adr = 0;
2690         sectors = 0;
2691         offset = 0;
2692         length = mtd->size;
2693
2694         while (length) {
2695                 int size = regions[i].erasesize;
2696
2697                 /*
2698                  * Only test sectors that shall not be unlocked. The other
2699                  * sectors shall be unlocked, so lets keep their locking
2700                  * status at "unlocked" (locked=0) for the final re-locking.
2701                  */
2702                 if ((offset < ofs) || (offset >= (ofs + len))) {
2703                         sect[sectors].chip = &cfi->chips[chipnum];
2704                         sect[sectors].adr = adr;
2705                         sect[sectors].locked = do_ppb_xxlock(
2706                                 map, &cfi->chips[chipnum], adr, 0,
2707                                 DO_XXLOCK_ONEBLOCK_GETLOCK);
2708                 }
2709
2710                 adr += size;
2711                 offset += size;
2712                 length -= size;
2713
2714                 if (offset == regions[i].offset + size * regions[i].numblocks)
2715                         i++;
2716
2717                 if (adr >> cfi->chipshift) {
2718                         if (offset >= (ofs + len))
2719                                 break;
2720                         adr = 0;
2721                         chipnum++;
2722
2723                         if (chipnum >= cfi->numchips)
2724                                 break;
2725                 }
2726
2727                 sectors++;
2728                 if (sectors >= MAX_SECTORS) {
2729                         printk(KERN_ERR "Only %d sectors for PPB locking supported!\n",
2730                                MAX_SECTORS);
2731                         kfree(sect);
2732                         return -EINVAL;
2733                 }
2734         }
2735
2736         /* Now unlock the whole chip */
2737         ret = cfi_varsize_frob(mtd, do_ppb_xxlock, ofs, len,
2738                                DO_XXLOCK_ONEBLOCK_UNLOCK);
2739         if (ret) {
2740                 kfree(sect);
2741                 return ret;
2742         }
2743
2744         /*
2745          * PPB unlocking always unlocks all sectors of the flash chip.
2746          * We need to re-lock all previously locked sectors.
2747          */
2748         for (i = 0; i < sectors; i++) {
2749                 if (sect[i].locked)
2750                         do_ppb_xxlock(map, sect[i].chip, sect[i].adr, 0,
2751                                       DO_XXLOCK_ONEBLOCK_LOCK);
2752         }
2753
2754         kfree(sect);
2755         return ret;
2756 }
2757
2758 static int __maybe_unused cfi_ppb_is_locked(struct mtd_info *mtd, loff_t ofs,
2759                                             uint64_t len)
2760 {
2761         return cfi_varsize_frob(mtd, do_ppb_xxlock, ofs, len,
2762                                 DO_XXLOCK_ONEBLOCK_GETLOCK) ? 1 : 0;
2763 }
2764
2765 static void cfi_amdstd_sync (struct mtd_info *mtd)
2766 {
2767         struct map_info *map = mtd->priv;
2768         struct cfi_private *cfi = map->fldrv_priv;
2769         int i;
2770         struct flchip *chip;
2771         int ret = 0;
2772         DECLARE_WAITQUEUE(wait, current);
2773
2774         for (i=0; !ret && i<cfi->numchips; i++) {
2775                 chip = &cfi->chips[i];
2776
2777         retry:
2778                 mutex_lock(&chip->mutex);
2779
2780                 switch(chip->state) {
2781                 case FL_READY:
2782                 case FL_STATUS:
2783                 case FL_CFI_QUERY:
2784                 case FL_JEDEC_QUERY:
2785                         chip->oldstate = chip->state;
2786                         chip->state = FL_SYNCING;
2787                         /* No need to wake_up() on this state change -
2788                          * as the whole point is that nobody can do anything
2789                          * with the chip now anyway.
2790                          */
2791                 case FL_SYNCING:
2792                         mutex_unlock(&chip->mutex);
2793                         break;
2794
2795                 default:
2796                         /* Not an idle state */
2797                         set_current_state(TASK_UNINTERRUPTIBLE);
2798                         add_wait_queue(&chip->wq, &wait);
2799
2800                         mutex_unlock(&chip->mutex);
2801
2802                         schedule();
2803
2804                         remove_wait_queue(&chip->wq, &wait);
2805
2806                         goto retry;
2807                 }
2808         }
2809
2810         /* Unlock the chips again */
2811
2812         for (i--; i >=0; i--) {
2813                 chip = &cfi->chips[i];
2814
2815                 mutex_lock(&chip->mutex);
2816
2817                 if (chip->state == FL_SYNCING) {
2818                         chip->state = chip->oldstate;
2819                         wake_up(&chip->wq);
2820                 }
2821                 mutex_unlock(&chip->mutex);
2822         }
2823 }
2824
2825
2826 static int cfi_amdstd_suspend(struct mtd_info *mtd)
2827 {
2828         struct map_info *map = mtd->priv;
2829         struct cfi_private *cfi = map->fldrv_priv;
2830         int i;
2831         struct flchip *chip;
2832         int ret = 0;
2833
2834         for (i=0; !ret && i<cfi->numchips; i++) {
2835                 chip = &cfi->chips[i];
2836
2837                 mutex_lock(&chip->mutex);
2838
2839                 switch(chip->state) {
2840                 case FL_READY:
2841                 case FL_STATUS:
2842                 case FL_CFI_QUERY:
2843                 case FL_JEDEC_QUERY:
2844                         chip->oldstate = chip->state;
2845                         chip->state = FL_PM_SUSPENDED;
2846                         /* No need to wake_up() on this state change -
2847                          * as the whole point is that nobody can do anything
2848                          * with the chip now anyway.
2849                          */
2850                 case FL_PM_SUSPENDED:
2851                         break;
2852
2853                 default:
2854                         ret = -EAGAIN;
2855                         break;
2856                 }
2857                 mutex_unlock(&chip->mutex);
2858         }
2859
2860         /* Unlock the chips again */
2861
2862         if (ret) {
2863                 for (i--; i >=0; i--) {
2864                         chip = &cfi->chips[i];
2865
2866                         mutex_lock(&chip->mutex);
2867
2868                         if (chip->state == FL_PM_SUSPENDED) {
2869                                 chip->state = chip->oldstate;
2870                                 wake_up(&chip->wq);
2871                         }
2872                         mutex_unlock(&chip->mutex);
2873                 }
2874         }
2875
2876         return ret;
2877 }
2878
2879
2880 static void cfi_amdstd_resume(struct mtd_info *mtd)
2881 {
2882         struct map_info *map = mtd->priv;
2883         struct cfi_private *cfi = map->fldrv_priv;
2884         int i;
2885         struct flchip *chip;
2886
2887         for (i=0; i<cfi->numchips; i++) {
2888
2889                 chip = &cfi->chips[i];
2890
2891                 mutex_lock(&chip->mutex);
2892
2893                 if (chip->state == FL_PM_SUSPENDED) {
2894                         chip->state = FL_READY;
2895                         map_write(map, CMD(0xF0), chip->start);
2896                         wake_up(&chip->wq);
2897                 }
2898                 else
2899                         printk(KERN_ERR "Argh. Chip not in PM_SUSPENDED state upon resume()\n");
2900
2901                 mutex_unlock(&chip->mutex);
2902         }
2903 }
2904
2905
2906 /*
2907  * Ensure that the flash device is put back into read array mode before
2908  * unloading the driver or rebooting.  On some systems, rebooting while
2909  * the flash is in query/program/erase mode will prevent the CPU from
2910  * fetching the bootloader code, requiring a hard reset or power cycle.
2911  */
2912 static int cfi_amdstd_reset(struct mtd_info *mtd)
2913 {
2914         struct map_info *map = mtd->priv;
2915         struct cfi_private *cfi = map->fldrv_priv;
2916         int i, ret;
2917         struct flchip *chip;
2918
2919         for (i = 0; i < cfi->numchips; i++) {
2920
2921                 chip = &cfi->chips[i];
2922
2923                 mutex_lock(&chip->mutex);
2924
2925                 ret = get_chip(map, chip, chip->start, FL_SHUTDOWN);
2926                 if (!ret) {
2927                         map_write(map, CMD(0xF0), chip->start);
2928                         chip->state = FL_SHUTDOWN;
2929                         put_chip(map, chip, chip->start);
2930                 }
2931
2932                 mutex_unlock(&chip->mutex);
2933         }
2934
2935         return 0;
2936 }
2937
2938
2939 static int cfi_amdstd_reboot(struct notifier_block *nb, unsigned long val,
2940                                void *v)
2941 {
2942         struct mtd_info *mtd;
2943
2944         mtd = container_of(nb, struct mtd_info, reboot_notifier);
2945         cfi_amdstd_reset(mtd);
2946         return NOTIFY_DONE;
2947 }
2948
2949
2950 static void cfi_amdstd_destroy(struct mtd_info *mtd)
2951 {
2952         struct map_info *map = mtd->priv;
2953         struct cfi_private *cfi = map->fldrv_priv;
2954
2955         cfi_amdstd_reset(mtd);
2956         unregister_reboot_notifier(&mtd->reboot_notifier);
2957         kfree(cfi->cmdset_priv);
2958         kfree(cfi->cfiq);
2959         kfree(cfi);
2960         kfree(mtd->eraseregions);
2961 }
2962
2963 MODULE_LICENSE("GPL");
2964 MODULE_AUTHOR("Crossnet Co. <info@crossnet.co.jp> et al.");
2965 MODULE_DESCRIPTION("MTD chip driver for AMD/Fujitsu flash chips");
2966 MODULE_ALIAS("cfi_cmdset_0006");
2967 MODULE_ALIAS("cfi_cmdset_0701");