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