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