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