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