xref: /rk3399_rockchip-uboot/drivers/mtd/cfi_flash.c (revision 799ca3be036d2334b074961bdf83bb6001fe4078)
1 /*
2  * (C) Copyright 2002-2004
3  * Brad Kemp, Seranoa Networks, Brad.Kemp@seranoa.com
4  *
5  * Copyright (C) 2003 Arabella Software Ltd.
6  * Yuli Barcohen <yuli@arabellasw.com>
7  *
8  * Copyright (C) 2004
9  * Ed Okerson
10  *
11  * Copyright (C) 2006
12  * Tolunay Orkun <listmember@orkun.us>
13  *
14  * SPDX-License-Identifier:	GPL-2.0+
15  */
16 
17 /* The DEBUG define must be before common to enable debugging */
18 /* #define DEBUG	*/
19 
20 #include <common.h>
21 #include <console.h>
22 #include <dm.h>
23 #include <errno.h>
24 #include <fdt_support.h>
25 #include <asm/processor.h>
26 #include <asm/io.h>
27 #include <asm/byteorder.h>
28 #include <asm/unaligned.h>
29 #include <environment.h>
30 #include <mtd/cfi_flash.h>
31 #include <watchdog.h>
32 
33 /*
34  * This file implements a Common Flash Interface (CFI) driver for
35  * U-Boot.
36  *
37  * The width of the port and the width of the chips are determined at
38  * initialization.  These widths are used to calculate the address for
39  * access CFI data structures.
40  *
41  * References
42  * JEDEC Standard JESD68 - Common Flash Interface (CFI)
43  * JEDEC Standard JEP137-A Common Flash Interface (CFI) ID Codes
44  * Intel Application Note 646 Common Flash Interface (CFI) and Command Sets
45  * Intel 290667-008 3 Volt Intel StrataFlash Memory datasheet
46  * AMD CFI Specification, Release 2.0 December 1, 2001
47  * AMD/Spansion Application Note: Migration from Single-byte to Three-byte
48  *   Device IDs, Publication Number 25538 Revision A, November 8, 2001
49  *
50  * Define CONFIG_SYS_WRITE_SWAPPED_DATA, if you have to swap the Bytes between
51  * reading and writing ... (yes there is such a Hardware).
52  */
53 
54 DECLARE_GLOBAL_DATA_PTR;
55 
56 static uint flash_offset_cfi[2] = { FLASH_OFFSET_CFI, FLASH_OFFSET_CFI_ALT };
57 #ifdef CONFIG_FLASH_CFI_MTD
58 static uint flash_verbose = 1;
59 #else
60 #define flash_verbose 1
61 #endif
62 
63 flash_info_t flash_info[CFI_MAX_FLASH_BANKS];	/* FLASH chips info */
64 
65 /*
66  * Check if chip width is defined. If not, start detecting with 8bit.
67  */
68 #ifndef CONFIG_SYS_FLASH_CFI_WIDTH
69 #define CONFIG_SYS_FLASH_CFI_WIDTH	FLASH_CFI_8BIT
70 #endif
71 
72 #ifdef CONFIG_CFI_FLASH_USE_WEAK_ACCESSORS
73 #define __maybe_weak __weak
74 #else
75 #define __maybe_weak static
76 #endif
77 
78 /*
79  * 0xffff is an undefined value for the configuration register. When
80  * this value is returned, the configuration register shall not be
81  * written at all (default mode).
82  */
83 static u16 cfi_flash_config_reg(int i)
84 {
85 #ifdef CONFIG_SYS_CFI_FLASH_CONFIG_REGS
86 	return ((u16 [])CONFIG_SYS_CFI_FLASH_CONFIG_REGS)[i];
87 #else
88 	return 0xffff;
89 #endif
90 }
91 
92 #if defined(CONFIG_SYS_MAX_FLASH_BANKS_DETECT)
93 int cfi_flash_num_flash_banks = CONFIG_SYS_MAX_FLASH_BANKS_DETECT;
94 #endif
95 
96 #ifdef CONFIG_CFI_FLASH /* for driver model */
97 static void cfi_flash_init_dm(void)
98 {
99 	struct udevice *dev;
100 
101 	cfi_flash_num_flash_banks = 0;
102 	/*
103 	 * The uclass_first_device() will probe the first device and
104 	 * uclass_next_device() will probe the rest if they exist. So
105 	 * that cfi_flash_probe() will get called assigning the base
106 	 * addresses that are available.
107 	 */
108 	for (uclass_first_device(UCLASS_MTD, &dev);
109 	     dev;
110 	     uclass_next_device(&dev)) {
111 	}
112 }
113 
114 phys_addr_t cfi_flash_bank_addr(int i)
115 {
116 	return flash_info[i].base;
117 }
118 #else
119 __weak phys_addr_t cfi_flash_bank_addr(int i)
120 {
121 	return ((phys_addr_t [])CONFIG_SYS_FLASH_BANKS_LIST)[i];
122 }
123 #endif
124 
125 __weak unsigned long cfi_flash_bank_size(int i)
126 {
127 #ifdef CONFIG_SYS_FLASH_BANKS_SIZES
128 	return ((unsigned long [])CONFIG_SYS_FLASH_BANKS_SIZES)[i];
129 #else
130 	return 0;
131 #endif
132 }
133 
134 __maybe_weak void flash_write8(u8 value, void *addr)
135 {
136 	__raw_writeb(value, addr);
137 }
138 
139 __maybe_weak void flash_write16(u16 value, void *addr)
140 {
141 	__raw_writew(value, addr);
142 }
143 
144 __maybe_weak void flash_write32(u32 value, void *addr)
145 {
146 	__raw_writel(value, addr);
147 }
148 
149 __maybe_weak void flash_write64(u64 value, void *addr)
150 {
151 	/* No architectures currently implement __raw_writeq() */
152 	*(volatile u64 *)addr = value;
153 }
154 
155 __maybe_weak u8 flash_read8(void *addr)
156 {
157 	return __raw_readb(addr);
158 }
159 
160 __maybe_weak u16 flash_read16(void *addr)
161 {
162 	return __raw_readw(addr);
163 }
164 
165 __maybe_weak u32 flash_read32(void *addr)
166 {
167 	return __raw_readl(addr);
168 }
169 
170 __maybe_weak u64 flash_read64(void *addr)
171 {
172 	/* No architectures currently implement __raw_readq() */
173 	return *(volatile u64 *)addr;
174 }
175 
176 /*-----------------------------------------------------------------------
177  */
178 #if defined(CONFIG_ENV_IS_IN_FLASH) || defined(CONFIG_ENV_ADDR_REDUND) || (CONFIG_SYS_MONITOR_BASE >= CONFIG_SYS_FLASH_BASE)
179 static flash_info_t *flash_get_info(ulong base)
180 {
181 	int i;
182 	flash_info_t *info;
183 
184 	for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
185 		info = &flash_info[i];
186 		if (info->size && info->start[0] <= base &&
187 		    base <= info->start[0] + info->size - 1)
188 			return info;
189 	}
190 
191 	return NULL;
192 }
193 #endif
194 
195 unsigned long flash_sector_size(flash_info_t *info, flash_sect_t sect)
196 {
197 	if (sect != (info->sector_count - 1))
198 		return info->start[sect + 1] - info->start[sect];
199 	else
200 		return info->start[0] + info->size - info->start[sect];
201 }
202 
203 /*-----------------------------------------------------------------------
204  * create an address based on the offset and the port width
205  */
206 static inline void *
207 flash_map(flash_info_t *info, flash_sect_t sect, uint offset)
208 {
209 	unsigned int byte_offset = offset * info->portwidth;
210 
211 	return (void *)(info->start[sect] + byte_offset);
212 }
213 
214 static inline void flash_unmap(flash_info_t *info, flash_sect_t sect,
215 		unsigned int offset, void *addr)
216 {
217 }
218 
219 /*-----------------------------------------------------------------------
220  * make a proper sized command based on the port and chip widths
221  */
222 static void flash_make_cmd(flash_info_t *info, u32 cmd, void *cmdbuf)
223 {
224 	int i;
225 	int cword_offset;
226 	int cp_offset;
227 #if defined(__LITTLE_ENDIAN) || defined(CONFIG_SYS_WRITE_SWAPPED_DATA)
228 	u32 cmd_le = cpu_to_le32(cmd);
229 #endif
230 	uchar val;
231 	uchar *cp = (uchar *) cmdbuf;
232 
233 	for (i = info->portwidth; i > 0; i--) {
234 		cword_offset = (info->portwidth - i) % info->chipwidth;
235 #if defined(__LITTLE_ENDIAN) || defined(CONFIG_SYS_WRITE_SWAPPED_DATA)
236 		cp_offset = info->portwidth - i;
237 		val = *((uchar *)&cmd_le + cword_offset);
238 #else
239 		cp_offset = i - 1;
240 		val = *((uchar *)&cmd + sizeof(u32) - cword_offset - 1);
241 #endif
242 		cp[cp_offset] = (cword_offset >= sizeof(u32)) ? 0x00 : val;
243 	}
244 }
245 
246 #ifdef DEBUG
247 /*-----------------------------------------------------------------------
248  * Debug support
249  */
250 static void print_longlong(char *str, unsigned long long data)
251 {
252 	int i;
253 	char *cp;
254 
255 	cp = (char *)&data;
256 	for (i = 0; i < 8; i++)
257 		sprintf(&str[i * 2], "%2.2x", *cp++);
258 }
259 
260 static void flash_printqry(struct cfi_qry *qry)
261 {
262 	u8 *p = (u8 *)qry;
263 	int x, y;
264 
265 	for (x = 0; x < sizeof(struct cfi_qry); x += 16) {
266 		debug("%02x : ", x);
267 		for (y = 0; y < 16; y++)
268 			debug("%2.2x ", p[x + y]);
269 		debug(" ");
270 		for (y = 0; y < 16; y++) {
271 			unsigned char c = p[x + y];
272 
273 			if (c >= 0x20 && c <= 0x7e)
274 				debug("%c", c);
275 			else
276 				debug(".");
277 		}
278 		debug("\n");
279 	}
280 }
281 #endif
282 
283 /*-----------------------------------------------------------------------
284  * read a character at a port width address
285  */
286 static inline uchar flash_read_uchar(flash_info_t *info, uint offset)
287 {
288 	uchar *cp;
289 	uchar retval;
290 
291 	cp = flash_map(info, 0, offset);
292 #if defined(__LITTLE_ENDIAN) || defined(CONFIG_SYS_WRITE_SWAPPED_DATA)
293 	retval = flash_read8(cp);
294 #else
295 	retval = flash_read8(cp + info->portwidth - 1);
296 #endif
297 	flash_unmap(info, 0, offset, cp);
298 	return retval;
299 }
300 
301 /*-----------------------------------------------------------------------
302  * read a word at a port width address, assume 16bit bus
303  */
304 static inline ushort flash_read_word(flash_info_t *info, uint offset)
305 {
306 	ushort *addr, retval;
307 
308 	addr = flash_map(info, 0, offset);
309 	retval = flash_read16(addr);
310 	flash_unmap(info, 0, offset, addr);
311 	return retval;
312 }
313 
314 /*-----------------------------------------------------------------------
315  * read a long word by picking the least significant byte of each maximum
316  * port size word. Swap for ppc format.
317  */
318 static ulong flash_read_long (flash_info_t *info, flash_sect_t sect,
319 			      uint offset)
320 {
321 	uchar *addr;
322 	ulong retval;
323 
324 #ifdef DEBUG
325 	int x;
326 #endif
327 	addr = flash_map(info, sect, offset);
328 
329 #ifdef DEBUG
330 	debug("long addr is at %p info->portwidth = %d\n", addr,
331 	       info->portwidth);
332 	for (x = 0; x < 4 * info->portwidth; x++)
333 		debug("addr[%x] = 0x%x\n", x, flash_read8(addr + x));
334 #endif
335 #if defined(__LITTLE_ENDIAN) || defined(CONFIG_SYS_WRITE_SWAPPED_DATA)
336 	retval = ((flash_read8(addr) << 16) |
337 		  (flash_read8(addr + info->portwidth) << 24) |
338 		  (flash_read8(addr + 2 * info->portwidth)) |
339 		  (flash_read8(addr + 3 * info->portwidth) << 8));
340 #else
341 	retval = ((flash_read8(addr + 2 * info->portwidth - 1) << 24) |
342 		  (flash_read8(addr + info->portwidth - 1) << 16) |
343 		  (flash_read8(addr + 4 * info->portwidth - 1) << 8) |
344 		  (flash_read8(addr + 3 * info->portwidth - 1)));
345 #endif
346 	flash_unmap(info, sect, offset, addr);
347 
348 	return retval;
349 }
350 
351 /*
352  * Write a proper sized command to the correct address
353  */
354 static void flash_write_cmd(flash_info_t *info, flash_sect_t sect,
355 			    uint offset, u32 cmd)
356 {
357 	void *addr;
358 	cfiword_t cword;
359 
360 	addr = flash_map(info, sect, offset);
361 	flash_make_cmd(info, cmd, &cword);
362 	switch (info->portwidth) {
363 	case FLASH_CFI_8BIT:
364 		debug("fwc addr %p cmd %x %x 8bit x %d bit\n", addr, cmd,
365 		       cword.w8, info->chipwidth << CFI_FLASH_SHIFT_WIDTH);
366 		flash_write8(cword.w8, addr);
367 		break;
368 	case FLASH_CFI_16BIT:
369 		debug("fwc addr %p cmd %x %4.4x 16bit x %d bit\n", addr,
370 		       cmd, cword.w16,
371 		       info->chipwidth << CFI_FLASH_SHIFT_WIDTH);
372 		flash_write16(cword.w16, addr);
373 		break;
374 	case FLASH_CFI_32BIT:
375 		debug("fwc addr %p cmd %x %8.8x 32bit x %d bit\n", addr,
376 		       cmd, cword.w32,
377 		       info->chipwidth << CFI_FLASH_SHIFT_WIDTH);
378 		flash_write32(cword.w32, addr);
379 		break;
380 	case FLASH_CFI_64BIT:
381 #ifdef DEBUG
382 		{
383 			char str[20];
384 
385 			print_longlong(str, cword.w64);
386 
387 			debug("fwrite addr %p cmd %x %s 64 bit x %d bit\n",
388 			       addr, cmd, str,
389 			       info->chipwidth << CFI_FLASH_SHIFT_WIDTH);
390 		}
391 #endif
392 		flash_write64(cword.w64, addr);
393 		break;
394 	}
395 
396 	/* Ensure all the instructions are fully finished */
397 	sync();
398 
399 	flash_unmap(info, sect, offset, addr);
400 }
401 
402 static void flash_unlock_seq(flash_info_t *info, flash_sect_t sect)
403 {
404 	flash_write_cmd(info, sect, info->addr_unlock1, AMD_CMD_UNLOCK_START);
405 	flash_write_cmd(info, sect, info->addr_unlock2, AMD_CMD_UNLOCK_ACK);
406 }
407 
408 /*-----------------------------------------------------------------------
409  */
410 static int flash_isequal(flash_info_t *info, flash_sect_t sect,
411 			  uint offset, uchar cmd)
412 {
413 	void *addr;
414 	cfiword_t cword;
415 	int retval;
416 
417 	addr = flash_map(info, sect, offset);
418 	flash_make_cmd(info, cmd, &cword);
419 
420 	debug("is= cmd %x(%c) addr %p ", cmd, cmd, addr);
421 	switch (info->portwidth) {
422 	case FLASH_CFI_8BIT:
423 		debug("is= %x %x\n", flash_read8(addr), cword.w8);
424 		retval = (flash_read8(addr) == cword.w8);
425 		break;
426 	case FLASH_CFI_16BIT:
427 		debug("is= %4.4x %4.4x\n", flash_read16(addr), cword.w16);
428 		retval = (flash_read16(addr) == cword.w16);
429 		break;
430 	case FLASH_CFI_32BIT:
431 		debug("is= %8.8x %8.8x\n", flash_read32(addr), cword.w32);
432 		retval = (flash_read32(addr) == cword.w32);
433 		break;
434 	case FLASH_CFI_64BIT:
435 #ifdef DEBUG
436 		{
437 			char str1[20];
438 			char str2[20];
439 
440 			print_longlong(str1, flash_read64(addr));
441 			print_longlong(str2, cword.w64);
442 			debug("is= %s %s\n", str1, str2);
443 		}
444 #endif
445 		retval = (flash_read64(addr) == cword.w64);
446 		break;
447 	default:
448 		retval = 0;
449 		break;
450 	}
451 	flash_unmap(info, sect, offset, addr);
452 
453 	return retval;
454 }
455 
456 /*-----------------------------------------------------------------------
457  */
458 static int flash_isset(flash_info_t *info, flash_sect_t sect,
459 			uint offset, uchar cmd)
460 {
461 	void *addr;
462 	cfiword_t cword;
463 	int retval;
464 
465 	addr = flash_map(info, sect, offset);
466 	flash_make_cmd(info, cmd, &cword);
467 	switch (info->portwidth) {
468 	case FLASH_CFI_8BIT:
469 		retval = ((flash_read8(addr) & cword.w8) == cword.w8);
470 		break;
471 	case FLASH_CFI_16BIT:
472 		retval = ((flash_read16(addr) & cword.w16) == cword.w16);
473 		break;
474 	case FLASH_CFI_32BIT:
475 		retval = ((flash_read32(addr) & cword.w32) == cword.w32);
476 		break;
477 	case FLASH_CFI_64BIT:
478 		retval = ((flash_read64(addr) & cword.w64) == cword.w64);
479 		break;
480 	default:
481 		retval = 0;
482 		break;
483 	}
484 	flash_unmap(info, sect, offset, addr);
485 
486 	return retval;
487 }
488 
489 /*-----------------------------------------------------------------------
490  */
491 static int flash_toggle(flash_info_t *info, flash_sect_t sect,
492 			 uint offset, uchar cmd)
493 {
494 	void *addr;
495 	cfiword_t cword;
496 	int retval;
497 
498 	addr = flash_map(info, sect, offset);
499 	flash_make_cmd(info, cmd, &cword);
500 	switch (info->portwidth) {
501 	case FLASH_CFI_8BIT:
502 		retval = flash_read8(addr) != flash_read8(addr);
503 		break;
504 	case FLASH_CFI_16BIT:
505 		retval = flash_read16(addr) != flash_read16(addr);
506 		break;
507 	case FLASH_CFI_32BIT:
508 		retval = flash_read32(addr) != flash_read32(addr);
509 		break;
510 	case FLASH_CFI_64BIT:
511 		retval = ((flash_read32(addr) != flash_read32(addr)) ||
512 			   (flash_read32(addr + 4) != flash_read32(addr + 4)));
513 		break;
514 	default:
515 		retval = 0;
516 		break;
517 	}
518 	flash_unmap(info, sect, offset, addr);
519 
520 	return retval;
521 }
522 
523 /*
524  * flash_is_busy - check to see if the flash is busy
525  *
526  * This routine checks the status of the chip and returns true if the
527  * chip is busy.
528  */
529 static int flash_is_busy(flash_info_t *info, flash_sect_t sect)
530 {
531 	int retval;
532 
533 	switch (info->vendor) {
534 	case CFI_CMDSET_INTEL_PROG_REGIONS:
535 	case CFI_CMDSET_INTEL_STANDARD:
536 	case CFI_CMDSET_INTEL_EXTENDED:
537 		retval = !flash_isset(info, sect, 0, FLASH_STATUS_DONE);
538 		break;
539 	case CFI_CMDSET_AMD_STANDARD:
540 	case CFI_CMDSET_AMD_EXTENDED:
541 #ifdef CONFIG_FLASH_CFI_LEGACY
542 	case CFI_CMDSET_AMD_LEGACY:
543 #endif
544 		if (info->sr_supported) {
545 			flash_write_cmd(info, sect, info->addr_unlock1,
546 					 FLASH_CMD_READ_STATUS);
547 			retval = !flash_isset(info, sect, 0,
548 					       FLASH_STATUS_DONE);
549 		} else {
550 			retval = flash_toggle(info, sect, 0,
551 					       AMD_STATUS_TOGGLE);
552 		}
553 
554 		break;
555 	default:
556 		retval = 0;
557 	}
558 	debug("%s: %d\n", __func__, retval);
559 	return retval;
560 }
561 
562 /*-----------------------------------------------------------------------
563  *  wait for XSR.7 to be set. Time out with an error if it does not.
564  *  This routine does not set the flash to read-array mode.
565  */
566 static int flash_status_check(flash_info_t *info, flash_sect_t sector,
567 			       ulong tout, char *prompt)
568 {
569 	ulong start;
570 
571 #if CONFIG_SYS_HZ != 1000
572 	if ((ulong)CONFIG_SYS_HZ > 100000)
573 		tout *= (ulong)CONFIG_SYS_HZ / 1000;  /* for a big HZ, avoid overflow */
574 	else
575 		tout = DIV_ROUND_UP(tout * (ulong)CONFIG_SYS_HZ, 1000);
576 #endif
577 
578 	/* Wait for command completion */
579 #ifdef CONFIG_SYS_LOW_RES_TIMER
580 	reset_timer();
581 #endif
582 	start = get_timer(0);
583 	WATCHDOG_RESET();
584 	while (flash_is_busy(info, sector)) {
585 		if (get_timer(start) > tout) {
586 			printf("Flash %s timeout at address %lx data %lx\n",
587 				prompt, info->start[sector],
588 				flash_read_long(info, sector, 0));
589 			flash_write_cmd(info, sector, 0, info->cmd_reset);
590 			udelay(1);
591 			return ERR_TIMOUT;
592 		}
593 		udelay(1);		/* also triggers watchdog */
594 	}
595 	return ERR_OK;
596 }
597 
598 /*-----------------------------------------------------------------------
599  * Wait for XSR.7 to be set, if it times out print an error, otherwise
600  * do a full status check.
601  *
602  * This routine sets the flash to read-array mode.
603  */
604 static int flash_full_status_check(flash_info_t *info, flash_sect_t sector,
605 				    ulong tout, char *prompt)
606 {
607 	int retcode;
608 
609 	retcode = flash_status_check(info, sector, tout, prompt);
610 	switch (info->vendor) {
611 	case CFI_CMDSET_INTEL_PROG_REGIONS:
612 	case CFI_CMDSET_INTEL_EXTENDED:
613 	case CFI_CMDSET_INTEL_STANDARD:
614 		if ((retcode == ERR_OK) &&
615 			!flash_isset(info, sector, 0, FLASH_STATUS_DONE)) {
616 			retcode = ERR_INVAL;
617 			printf("Flash %s error at address %lx\n", prompt,
618 				info->start[sector]);
619 			if (flash_isset(info, sector, 0, FLASH_STATUS_ECLBS |
620 					 FLASH_STATUS_PSLBS)) {
621 				puts("Command Sequence Error.\n");
622 			} else if (flash_isset(info, sector, 0,
623 						FLASH_STATUS_ECLBS)) {
624 				puts("Block Erase Error.\n");
625 				retcode = ERR_NOT_ERASED;
626 			} else if (flash_isset(info, sector, 0,
627 						FLASH_STATUS_PSLBS)) {
628 				puts("Locking Error\n");
629 			}
630 			if (flash_isset(info, sector, 0, FLASH_STATUS_DPS)) {
631 				puts("Block locked.\n");
632 				retcode = ERR_PROTECTED;
633 			}
634 			if (flash_isset(info, sector, 0, FLASH_STATUS_VPENS))
635 				puts("Vpp Low Error.\n");
636 		}
637 		flash_write_cmd(info, sector, 0, info->cmd_reset);
638 		udelay(1);
639 		break;
640 	default:
641 		break;
642 	}
643 	return retcode;
644 }
645 
646 static int use_flash_status_poll(flash_info_t *info)
647 {
648 #ifdef CONFIG_SYS_CFI_FLASH_STATUS_POLL
649 	if (info->vendor == CFI_CMDSET_AMD_EXTENDED ||
650 	    info->vendor == CFI_CMDSET_AMD_STANDARD)
651 		return 1;
652 #endif
653 	return 0;
654 }
655 
656 static int flash_status_poll(flash_info_t *info, void *src, void *dst,
657 			     ulong tout, char *prompt)
658 {
659 #ifdef CONFIG_SYS_CFI_FLASH_STATUS_POLL
660 	ulong start;
661 	int ready;
662 
663 #if CONFIG_SYS_HZ != 1000
664 	if ((ulong)CONFIG_SYS_HZ > 100000)
665 		tout *= (ulong)CONFIG_SYS_HZ / 1000;  /* for a big HZ, avoid overflow */
666 	else
667 		tout = DIV_ROUND_UP(tout * (ulong)CONFIG_SYS_HZ, 1000);
668 #endif
669 
670 	/* Wait for command completion */
671 #ifdef CONFIG_SYS_LOW_RES_TIMER
672 	reset_timer();
673 #endif
674 	start = get_timer(0);
675 	WATCHDOG_RESET();
676 	while (1) {
677 		switch (info->portwidth) {
678 		case FLASH_CFI_8BIT:
679 			ready = flash_read8(dst) == flash_read8(src);
680 			break;
681 		case FLASH_CFI_16BIT:
682 			ready = flash_read16(dst) == flash_read16(src);
683 			break;
684 		case FLASH_CFI_32BIT:
685 			ready = flash_read32(dst) == flash_read32(src);
686 			break;
687 		case FLASH_CFI_64BIT:
688 			ready = flash_read64(dst) == flash_read64(src);
689 			break;
690 		default:
691 			ready = 0;
692 			break;
693 		}
694 		if (ready)
695 			break;
696 		if (get_timer(start) > tout) {
697 			printf("Flash %s timeout at address %lx data %lx\n",
698 			       prompt, (ulong)dst, (ulong)flash_read8(dst));
699 			return ERR_TIMOUT;
700 		}
701 		udelay(1);		/* also triggers watchdog */
702 	}
703 #endif /* CONFIG_SYS_CFI_FLASH_STATUS_POLL */
704 	return ERR_OK;
705 }
706 
707 /*-----------------------------------------------------------------------
708  */
709 static void flash_add_byte(flash_info_t *info, cfiword_t *cword, uchar c)
710 {
711 #if defined(__LITTLE_ENDIAN) && !defined(CONFIG_SYS_WRITE_SWAPPED_DATA)
712 	unsigned short	w;
713 	unsigned int	l;
714 	unsigned long long ll;
715 #endif
716 
717 	switch (info->portwidth) {
718 	case FLASH_CFI_8BIT:
719 		cword->w8 = c;
720 		break;
721 	case FLASH_CFI_16BIT:
722 #if defined(__LITTLE_ENDIAN) && !defined(CONFIG_SYS_WRITE_SWAPPED_DATA)
723 		w = c;
724 		w <<= 8;
725 		cword->w16 = (cword->w16 >> 8) | w;
726 #else
727 		cword->w16 = (cword->w16 << 8) | c;
728 #endif
729 		break;
730 	case FLASH_CFI_32BIT:
731 #if defined(__LITTLE_ENDIAN) && !defined(CONFIG_SYS_WRITE_SWAPPED_DATA)
732 		l = c;
733 		l <<= 24;
734 		cword->w32 = (cword->w32 >> 8) | l;
735 #else
736 		cword->w32 = (cword->w32 << 8) | c;
737 #endif
738 		break;
739 	case FLASH_CFI_64BIT:
740 #if defined(__LITTLE_ENDIAN) && !defined(CONFIG_SYS_WRITE_SWAPPED_DATA)
741 		ll = c;
742 		ll <<= 56;
743 		cword->w64 = (cword->w64 >> 8) | ll;
744 #else
745 		cword->w64 = (cword->w64 << 8) | c;
746 #endif
747 		break;
748 	}
749 }
750 
751 /*
752  * Loop through the sector table starting from the previously found sector.
753  * Searches forwards or backwards, dependent on the passed address.
754  */
755 static flash_sect_t find_sector(flash_info_t *info, ulong addr)
756 {
757 	static flash_sect_t saved_sector; /* previously found sector */
758 	static flash_info_t *saved_info; /* previously used flash bank */
759 	flash_sect_t sector = saved_sector;
760 
761 	if ((info != saved_info) || (sector >= info->sector_count))
762 		sector = 0;
763 
764 	while ((info->start[sector] < addr) &&
765 		(sector < info->sector_count - 1))
766 		sector++;
767 	while ((info->start[sector] > addr) && (sector > 0))
768 		/*
769 		 * also decrements the sector in case of an overshot
770 		 * in the first loop
771 		 */
772 		sector--;
773 
774 	saved_sector = sector;
775 	saved_info = info;
776 	return sector;
777 }
778 
779 /*-----------------------------------------------------------------------
780  */
781 static int flash_write_cfiword(flash_info_t *info, ulong dest,
782 				cfiword_t cword)
783 {
784 	void *dstaddr = (void *)dest;
785 	int flag;
786 	flash_sect_t sect = 0;
787 	char sect_found = 0;
788 
789 	/* Check if Flash is (sufficiently) erased */
790 	switch (info->portwidth) {
791 	case FLASH_CFI_8BIT:
792 		flag = ((flash_read8(dstaddr) & cword.w8) == cword.w8);
793 		break;
794 	case FLASH_CFI_16BIT:
795 		flag = ((flash_read16(dstaddr) & cword.w16) == cword.w16);
796 		break;
797 	case FLASH_CFI_32BIT:
798 		flag = ((flash_read32(dstaddr) & cword.w32) == cword.w32);
799 		break;
800 	case FLASH_CFI_64BIT:
801 		flag = ((flash_read64(dstaddr) & cword.w64) == cword.w64);
802 		break;
803 	default:
804 		flag = 0;
805 		break;
806 	}
807 	if (!flag)
808 		return ERR_NOT_ERASED;
809 
810 	/* Disable interrupts which might cause a timeout here */
811 	flag = disable_interrupts();
812 
813 	switch (info->vendor) {
814 	case CFI_CMDSET_INTEL_PROG_REGIONS:
815 	case CFI_CMDSET_INTEL_EXTENDED:
816 	case CFI_CMDSET_INTEL_STANDARD:
817 		flash_write_cmd(info, 0, 0, FLASH_CMD_CLEAR_STATUS);
818 		flash_write_cmd(info, 0, 0, FLASH_CMD_WRITE);
819 		break;
820 	case CFI_CMDSET_AMD_EXTENDED:
821 	case CFI_CMDSET_AMD_STANDARD:
822 		sect = find_sector(info, dest);
823 		flash_unlock_seq(info, sect);
824 		flash_write_cmd(info, sect, info->addr_unlock1, AMD_CMD_WRITE);
825 		sect_found = 1;
826 		break;
827 #ifdef CONFIG_FLASH_CFI_LEGACY
828 	case CFI_CMDSET_AMD_LEGACY:
829 		sect = find_sector(info, dest);
830 		flash_unlock_seq(info, 0);
831 		flash_write_cmd(info, 0, info->addr_unlock1, AMD_CMD_WRITE);
832 		sect_found = 1;
833 		break;
834 #endif
835 	}
836 
837 	switch (info->portwidth) {
838 	case FLASH_CFI_8BIT:
839 		flash_write8(cword.w8, dstaddr);
840 		break;
841 	case FLASH_CFI_16BIT:
842 		flash_write16(cword.w16, dstaddr);
843 		break;
844 	case FLASH_CFI_32BIT:
845 		flash_write32(cword.w32, dstaddr);
846 		break;
847 	case FLASH_CFI_64BIT:
848 		flash_write64(cword.w64, dstaddr);
849 		break;
850 	}
851 
852 	/* re-enable interrupts if necessary */
853 	if (flag)
854 		enable_interrupts();
855 
856 	if (!sect_found)
857 		sect = find_sector(info, dest);
858 
859 	if (use_flash_status_poll(info))
860 		return flash_status_poll(info, &cword, dstaddr,
861 					 info->write_tout, "write");
862 	else
863 		return flash_full_status_check(info, sect,
864 					       info->write_tout, "write");
865 }
866 
867 #ifdef CONFIG_SYS_FLASH_USE_BUFFER_WRITE
868 
869 static int flash_write_cfibuffer(flash_info_t *info, ulong dest, uchar *cp,
870 				  int len)
871 {
872 	flash_sect_t sector;
873 	int cnt;
874 	int retcode;
875 	void *src = cp;
876 	void *dst = (void *)dest;
877 	void *dst2 = dst;
878 	int flag = 1;
879 	uint offset = 0;
880 	unsigned int shift;
881 	uchar write_cmd;
882 
883 	switch (info->portwidth) {
884 	case FLASH_CFI_8BIT:
885 		shift = 0;
886 		break;
887 	case FLASH_CFI_16BIT:
888 		shift = 1;
889 		break;
890 	case FLASH_CFI_32BIT:
891 		shift = 2;
892 		break;
893 	case FLASH_CFI_64BIT:
894 		shift = 3;
895 		break;
896 	default:
897 		retcode = ERR_INVAL;
898 		goto out_unmap;
899 	}
900 
901 	cnt = len >> shift;
902 
903 	while ((cnt-- > 0) && (flag == 1)) {
904 		switch (info->portwidth) {
905 		case FLASH_CFI_8BIT:
906 			flag = ((flash_read8(dst2) & flash_read8(src)) ==
907 				flash_read8(src));
908 			src += 1, dst2 += 1;
909 			break;
910 		case FLASH_CFI_16BIT:
911 			flag = ((flash_read16(dst2) & flash_read16(src)) ==
912 				flash_read16(src));
913 			src += 2, dst2 += 2;
914 			break;
915 		case FLASH_CFI_32BIT:
916 			flag = ((flash_read32(dst2) & flash_read32(src)) ==
917 				flash_read32(src));
918 			src += 4, dst2 += 4;
919 			break;
920 		case FLASH_CFI_64BIT:
921 			flag = ((flash_read64(dst2) & flash_read64(src)) ==
922 				flash_read64(src));
923 			src += 8, dst2 += 8;
924 			break;
925 		}
926 	}
927 	if (!flag) {
928 		retcode = ERR_NOT_ERASED;
929 		goto out_unmap;
930 	}
931 
932 	src = cp;
933 	sector = find_sector(info, dest);
934 
935 	switch (info->vendor) {
936 	case CFI_CMDSET_INTEL_PROG_REGIONS:
937 	case CFI_CMDSET_INTEL_STANDARD:
938 	case CFI_CMDSET_INTEL_EXTENDED:
939 		write_cmd = (info->vendor == CFI_CMDSET_INTEL_PROG_REGIONS) ?
940 					FLASH_CMD_WRITE_BUFFER_PROG : FLASH_CMD_WRITE_TO_BUFFER;
941 		flash_write_cmd(info, sector, 0, FLASH_CMD_CLEAR_STATUS);
942 		flash_write_cmd(info, sector, 0, FLASH_CMD_READ_STATUS);
943 		flash_write_cmd(info, sector, 0, write_cmd);
944 		retcode = flash_status_check(info, sector,
945 					      info->buffer_write_tout,
946 					      "write to buffer");
947 		if (retcode == ERR_OK) {
948 			/* reduce the number of loops by the width of
949 			 * the port
950 			 */
951 			cnt = len >> shift;
952 			flash_write_cmd(info, sector, 0, cnt - 1);
953 			while (cnt-- > 0) {
954 				switch (info->portwidth) {
955 				case FLASH_CFI_8BIT:
956 					flash_write8(flash_read8(src), dst);
957 					src += 1, dst += 1;
958 					break;
959 				case FLASH_CFI_16BIT:
960 					flash_write16(flash_read16(src), dst);
961 					src += 2, dst += 2;
962 					break;
963 				case FLASH_CFI_32BIT:
964 					flash_write32(flash_read32(src), dst);
965 					src += 4, dst += 4;
966 					break;
967 				case FLASH_CFI_64BIT:
968 					flash_write64(flash_read64(src), dst);
969 					src += 8, dst += 8;
970 					break;
971 				default:
972 					retcode = ERR_INVAL;
973 					goto out_unmap;
974 				}
975 			}
976 			flash_write_cmd(info, sector, 0,
977 					 FLASH_CMD_WRITE_BUFFER_CONFIRM);
978 			retcode = flash_full_status_check(
979 				info, sector, info->buffer_write_tout,
980 				"buffer write");
981 		}
982 
983 		break;
984 
985 	case CFI_CMDSET_AMD_STANDARD:
986 	case CFI_CMDSET_AMD_EXTENDED:
987 		flash_unlock_seq(info, sector);
988 
989 #ifdef CONFIG_FLASH_SPANSION_S29WS_N
990 		offset = ((unsigned long)dst - info->start[sector]) >> shift;
991 #endif
992 		flash_write_cmd(info, sector, offset, AMD_CMD_WRITE_TO_BUFFER);
993 		cnt = len >> shift;
994 		flash_write_cmd(info, sector, offset, cnt - 1);
995 
996 		switch (info->portwidth) {
997 		case FLASH_CFI_8BIT:
998 			while (cnt-- > 0) {
999 				flash_write8(flash_read8(src), dst);
1000 				src += 1, dst += 1;
1001 			}
1002 			break;
1003 		case FLASH_CFI_16BIT:
1004 			while (cnt-- > 0) {
1005 				flash_write16(flash_read16(src), dst);
1006 				src += 2, dst += 2;
1007 			}
1008 			break;
1009 		case FLASH_CFI_32BIT:
1010 			while (cnt-- > 0) {
1011 				flash_write32(flash_read32(src), dst);
1012 				src += 4, dst += 4;
1013 			}
1014 			break;
1015 		case FLASH_CFI_64BIT:
1016 			while (cnt-- > 0) {
1017 				flash_write64(flash_read64(src), dst);
1018 				src += 8, dst += 8;
1019 			}
1020 			break;
1021 		default:
1022 			retcode = ERR_INVAL;
1023 			goto out_unmap;
1024 		}
1025 
1026 		flash_write_cmd(info, sector, 0, AMD_CMD_WRITE_BUFFER_CONFIRM);
1027 		if (use_flash_status_poll(info))
1028 			retcode = flash_status_poll(info, src - (1 << shift),
1029 						    dst - (1 << shift),
1030 						    info->buffer_write_tout,
1031 						    "buffer write");
1032 		else
1033 			retcode = flash_full_status_check(info, sector,
1034 							  info->buffer_write_tout,
1035 							  "buffer write");
1036 		break;
1037 
1038 	default:
1039 		debug("Unknown Command Set\n");
1040 		retcode = ERR_INVAL;
1041 		break;
1042 	}
1043 
1044 out_unmap:
1045 	return retcode;
1046 }
1047 #endif /* CONFIG_SYS_FLASH_USE_BUFFER_WRITE */
1048 
1049 /*-----------------------------------------------------------------------
1050  */
1051 int flash_erase(flash_info_t *info, int s_first, int s_last)
1052 {
1053 	int rcode = 0;
1054 	int prot;
1055 	flash_sect_t sect;
1056 	int st;
1057 
1058 	if (info->flash_id != FLASH_MAN_CFI) {
1059 		puts("Can't erase unknown flash type - aborted\n");
1060 		return 1;
1061 	}
1062 	if ((s_first < 0) || (s_first > s_last)) {
1063 		puts("- no sectors to erase\n");
1064 		return 1;
1065 	}
1066 
1067 	prot = 0;
1068 	for (sect = s_first; sect <= s_last; ++sect)
1069 		if (info->protect[sect])
1070 			prot++;
1071 	if (prot) {
1072 		printf("- Warning: %d protected sectors will not be erased!\n",
1073 			prot);
1074 	} else if (flash_verbose) {
1075 		putc('\n');
1076 	}
1077 
1078 	for (sect = s_first; sect <= s_last; sect++) {
1079 		if (ctrlc()) {
1080 			printf("\n");
1081 			return 1;
1082 		}
1083 
1084 		if (info->protect[sect] == 0) { /* not protected */
1085 #ifdef CONFIG_SYS_FLASH_CHECK_BLANK_BEFORE_ERASE
1086 			int k;
1087 			int size;
1088 			int erased;
1089 			u32 *flash;
1090 
1091 			/*
1092 			 * Check if whole sector is erased
1093 			 */
1094 			size = flash_sector_size(info, sect);
1095 			erased = 1;
1096 			flash = (u32 *)info->start[sect];
1097 			/* divide by 4 for longword access */
1098 			size = size >> 2;
1099 			for (k = 0; k < size; k++) {
1100 				if (flash_read32(flash++) != 0xffffffff) {
1101 					erased = 0;
1102 					break;
1103 				}
1104 			}
1105 			if (erased) {
1106 				if (flash_verbose)
1107 					putc(',');
1108 				continue;
1109 			}
1110 #endif
1111 			switch (info->vendor) {
1112 			case CFI_CMDSET_INTEL_PROG_REGIONS:
1113 			case CFI_CMDSET_INTEL_STANDARD:
1114 			case CFI_CMDSET_INTEL_EXTENDED:
1115 				flash_write_cmd(info, sect, 0,
1116 						 FLASH_CMD_CLEAR_STATUS);
1117 				flash_write_cmd(info, sect, 0,
1118 						 FLASH_CMD_BLOCK_ERASE);
1119 				flash_write_cmd(info, sect, 0,
1120 						 FLASH_CMD_ERASE_CONFIRM);
1121 				break;
1122 			case CFI_CMDSET_AMD_STANDARD:
1123 			case CFI_CMDSET_AMD_EXTENDED:
1124 				flash_unlock_seq(info, sect);
1125 				flash_write_cmd(info, sect,
1126 						info->addr_unlock1,
1127 						AMD_CMD_ERASE_START);
1128 				flash_unlock_seq(info, sect);
1129 				flash_write_cmd(info, sect, 0,
1130 						 info->cmd_erase_sector);
1131 				break;
1132 #ifdef CONFIG_FLASH_CFI_LEGACY
1133 			case CFI_CMDSET_AMD_LEGACY:
1134 				flash_unlock_seq(info, 0);
1135 				flash_write_cmd(info, 0, info->addr_unlock1,
1136 						AMD_CMD_ERASE_START);
1137 				flash_unlock_seq(info, 0);
1138 				flash_write_cmd(info, sect, 0,
1139 						AMD_CMD_ERASE_SECTOR);
1140 				break;
1141 #endif
1142 			default:
1143 				debug("Unkown flash vendor %d\n",
1144 				       info->vendor);
1145 				break;
1146 			}
1147 
1148 			if (use_flash_status_poll(info)) {
1149 				cfiword_t cword;
1150 				void *dest;
1151 
1152 				cword.w64 = 0xffffffffffffffffULL;
1153 				dest = flash_map(info, sect, 0);
1154 				st = flash_status_poll(info, &cword, dest,
1155 						       info->erase_blk_tout, "erase");
1156 				flash_unmap(info, sect, 0, dest);
1157 			} else
1158 				st = flash_full_status_check(info, sect,
1159 							     info->erase_blk_tout,
1160 							     "erase");
1161 			if (st)
1162 				rcode = 1;
1163 			else if (flash_verbose)
1164 				putc('.');
1165 		}
1166 	}
1167 
1168 	if (flash_verbose)
1169 		puts(" done\n");
1170 
1171 	return rcode;
1172 }
1173 
1174 #ifdef CONFIG_SYS_FLASH_EMPTY_INFO
1175 static int sector_erased(flash_info_t *info, int i)
1176 {
1177 	int k;
1178 	int size;
1179 	u32 *flash;
1180 
1181 	/*
1182 	 * Check if whole sector is erased
1183 	 */
1184 	size = flash_sector_size(info, i);
1185 	flash = (u32 *)info->start[i];
1186 	/* divide by 4 for longword access */
1187 	size = size >> 2;
1188 
1189 	for (k = 0; k < size; k++) {
1190 		if (flash_read32(flash++) != 0xffffffff)
1191 			return 0;	/* not erased */
1192 	}
1193 
1194 	return 1;			/* erased */
1195 }
1196 #endif /* CONFIG_SYS_FLASH_EMPTY_INFO */
1197 
1198 void flash_print_info(flash_info_t *info)
1199 {
1200 	int i;
1201 
1202 	if (info->flash_id != FLASH_MAN_CFI) {
1203 		puts("missing or unknown FLASH type\n");
1204 		return;
1205 	}
1206 
1207 	printf("%s flash (%d x %d)",
1208 		info->name,
1209 		(info->portwidth << 3), (info->chipwidth << 3));
1210 	if (info->size < 1024 * 1024)
1211 		printf("  Size: %ld kB in %d Sectors\n",
1212 			info->size >> 10, info->sector_count);
1213 	else
1214 		printf("  Size: %ld MB in %d Sectors\n",
1215 			info->size >> 20, info->sector_count);
1216 	printf("  ");
1217 	switch (info->vendor) {
1218 	case CFI_CMDSET_INTEL_PROG_REGIONS:
1219 		printf("Intel Prog Regions");
1220 		break;
1221 	case CFI_CMDSET_INTEL_STANDARD:
1222 		printf("Intel Standard");
1223 		break;
1224 	case CFI_CMDSET_INTEL_EXTENDED:
1225 		printf("Intel Extended");
1226 		break;
1227 	case CFI_CMDSET_AMD_STANDARD:
1228 		printf("AMD Standard");
1229 		break;
1230 	case CFI_CMDSET_AMD_EXTENDED:
1231 		printf("AMD Extended");
1232 		break;
1233 #ifdef CONFIG_FLASH_CFI_LEGACY
1234 	case CFI_CMDSET_AMD_LEGACY:
1235 		printf("AMD Legacy");
1236 		break;
1237 #endif
1238 	default:
1239 		printf("Unknown (%d)", info->vendor);
1240 		break;
1241 	}
1242 	printf(" command set, Manufacturer ID: 0x%02X, Device ID: 0x",
1243 		info->manufacturer_id);
1244 	printf(info->chipwidth == FLASH_CFI_16BIT ? "%04X" : "%02X",
1245 		info->device_id);
1246 	if ((info->device_id & 0xff) == 0x7E) {
1247 		printf(info->chipwidth == FLASH_CFI_16BIT ? "%04X" : "%02X",
1248 		info->device_id2);
1249 	}
1250 	if ((info->vendor == CFI_CMDSET_AMD_STANDARD) && (info->legacy_unlock))
1251 		printf("\n  Advanced Sector Protection (PPB) enabled");
1252 	printf("\n  Erase timeout: %ld ms, write timeout: %ld ms\n",
1253 		info->erase_blk_tout,
1254 		info->write_tout);
1255 	if (info->buffer_size > 1) {
1256 		printf("  Buffer write timeout: %ld ms, "
1257 			"buffer size: %d bytes\n",
1258 		info->buffer_write_tout,
1259 		info->buffer_size);
1260 	}
1261 
1262 	puts("\n  Sector Start Addresses:");
1263 	for (i = 0; i < info->sector_count; ++i) {
1264 		if (ctrlc())
1265 			break;
1266 		if ((i % 5) == 0)
1267 			putc('\n');
1268 #ifdef CONFIG_SYS_FLASH_EMPTY_INFO
1269 		/* print empty and read-only info */
1270 		printf("  %08lX %c %s ",
1271 			info->start[i],
1272 			sector_erased(info, i) ? 'E' : ' ',
1273 			info->protect[i] ? "RO" : "  ");
1274 #else	/* ! CONFIG_SYS_FLASH_EMPTY_INFO */
1275 		printf("  %08lX   %s ",
1276 			info->start[i],
1277 			info->protect[i] ? "RO" : "  ");
1278 #endif
1279 	}
1280 	putc('\n');
1281 	return;
1282 }
1283 
1284 /*-----------------------------------------------------------------------
1285  * This is used in a few places in write_buf() to show programming
1286  * progress.  Making it a function is nasty because it needs to do side
1287  * effect updates to digit and dots.  Repeated code is nasty too, so
1288  * we define it once here.
1289  */
1290 #ifdef CONFIG_FLASH_SHOW_PROGRESS
1291 #define FLASH_SHOW_PROGRESS(scale, dots, digit, dots_sub) \
1292 	if (flash_verbose) { \
1293 		dots -= dots_sub; \
1294 		if ((scale > 0) && (dots <= 0)) { \
1295 			if ((digit % 5) == 0) \
1296 				printf("%d", digit / 5); \
1297 			else \
1298 				putc('.'); \
1299 			digit--; \
1300 			dots += scale; \
1301 		} \
1302 	}
1303 #else
1304 #define FLASH_SHOW_PROGRESS(scale, dots, digit, dots_sub)
1305 #endif
1306 
1307 /*-----------------------------------------------------------------------
1308  * Copy memory to flash, returns:
1309  * 0 - OK
1310  * 1 - write timeout
1311  * 2 - Flash not erased
1312  */
1313 int write_buff(flash_info_t *info, uchar *src, ulong addr, ulong cnt)
1314 {
1315 	ulong wp;
1316 	uchar *p;
1317 	int aln;
1318 	cfiword_t cword;
1319 	int i, rc;
1320 #ifdef CONFIG_SYS_FLASH_USE_BUFFER_WRITE
1321 	int buffered_size;
1322 #endif
1323 #ifdef CONFIG_FLASH_SHOW_PROGRESS
1324 	int digit = CONFIG_FLASH_SHOW_PROGRESS;
1325 	int scale = 0;
1326 	int dots  = 0;
1327 
1328 	/*
1329 	 * Suppress if there are fewer than CONFIG_FLASH_SHOW_PROGRESS writes.
1330 	 */
1331 	if (cnt >= CONFIG_FLASH_SHOW_PROGRESS) {
1332 		scale = (int)((cnt + CONFIG_FLASH_SHOW_PROGRESS - 1) /
1333 			CONFIG_FLASH_SHOW_PROGRESS);
1334 	}
1335 #endif
1336 
1337 	/* get lower aligned address */
1338 	wp = (addr & ~(info->portwidth - 1));
1339 
1340 	/* handle unaligned start */
1341 	if ((aln = addr - wp) != 0) {
1342 		cword.w32 = 0;
1343 		p = (uchar *)wp;
1344 		for (i = 0; i < aln; ++i)
1345 			flash_add_byte(info, &cword, flash_read8(p + i));
1346 
1347 		for (; (i < info->portwidth) && (cnt > 0); i++) {
1348 			flash_add_byte(info, &cword, *src++);
1349 			cnt--;
1350 		}
1351 		for (; (cnt == 0) && (i < info->portwidth); ++i)
1352 			flash_add_byte(info, &cword, flash_read8(p + i));
1353 
1354 		rc = flash_write_cfiword(info, wp, cword);
1355 		if (rc != 0)
1356 			return rc;
1357 
1358 		wp += i;
1359 		FLASH_SHOW_PROGRESS(scale, dots, digit, i);
1360 	}
1361 
1362 	/* handle the aligned part */
1363 #ifdef CONFIG_SYS_FLASH_USE_BUFFER_WRITE
1364 	buffered_size = (info->portwidth / info->chipwidth);
1365 	buffered_size *= info->buffer_size;
1366 	while (cnt >= info->portwidth) {
1367 		/* prohibit buffer write when buffer_size is 1 */
1368 		if (info->buffer_size == 1) {
1369 			cword.w32 = 0;
1370 			for (i = 0; i < info->portwidth; i++)
1371 				flash_add_byte(info, &cword, *src++);
1372 			if ((rc = flash_write_cfiword(info, wp, cword)) != 0)
1373 				return rc;
1374 			wp += info->portwidth;
1375 			cnt -= info->portwidth;
1376 			continue;
1377 		}
1378 
1379 		/* write buffer until next buffered_size aligned boundary */
1380 		i = buffered_size - (wp % buffered_size);
1381 		if (i > cnt)
1382 			i = cnt;
1383 		if ((rc = flash_write_cfibuffer(info, wp, src, i)) != ERR_OK)
1384 			return rc;
1385 		i -= i & (info->portwidth - 1);
1386 		wp += i;
1387 		src += i;
1388 		cnt -= i;
1389 		FLASH_SHOW_PROGRESS(scale, dots, digit, i);
1390 		/* Only check every once in a while */
1391 		if ((cnt & 0xFFFF) < buffered_size && ctrlc())
1392 			return ERR_ABORTED;
1393 	}
1394 #else
1395 	while (cnt >= info->portwidth) {
1396 		cword.w32 = 0;
1397 		for (i = 0; i < info->portwidth; i++)
1398 			flash_add_byte(info, &cword, *src++);
1399 		if ((rc = flash_write_cfiword(info, wp, cword)) != 0)
1400 			return rc;
1401 		wp += info->portwidth;
1402 		cnt -= info->portwidth;
1403 		FLASH_SHOW_PROGRESS(scale, dots, digit, info->portwidth);
1404 		/* Only check every once in a while */
1405 		if ((cnt & 0xFFFF) < info->portwidth && ctrlc())
1406 			return ERR_ABORTED;
1407 	}
1408 #endif /* CONFIG_SYS_FLASH_USE_BUFFER_WRITE */
1409 
1410 	if (cnt == 0)
1411 		return (0);
1412 
1413 	/*
1414 	 * handle unaligned tail bytes
1415 	 */
1416 	cword.w32 = 0;
1417 	p = (uchar *)wp;
1418 	for (i = 0; (i < info->portwidth) && (cnt > 0); ++i) {
1419 		flash_add_byte(info, &cword, *src++);
1420 		--cnt;
1421 	}
1422 	for (; i < info->portwidth; ++i)
1423 		flash_add_byte(info, &cword, flash_read8(p + i));
1424 
1425 	return flash_write_cfiword(info, wp, cword);
1426 }
1427 
1428 static inline int manufact_match(flash_info_t *info, u32 manu)
1429 {
1430 	return info->manufacturer_id == ((manu & FLASH_VENDMASK) >> 16);
1431 }
1432 
1433 /*-----------------------------------------------------------------------
1434  */
1435 #ifdef CONFIG_SYS_FLASH_PROTECTION
1436 
1437 static int cfi_protect_bugfix(flash_info_t *info, long sector, int prot)
1438 {
1439 	if (manufact_match(info, INTEL_MANUFACT) &&
1440 		info->device_id == NUMONYX_256MBIT) {
1441 		/*
1442 		 * see errata called
1443 		 * "Numonyx Axcell P33/P30 Specification Update" :)
1444 		 */
1445 		flash_write_cmd(info, sector, 0, FLASH_CMD_READ_ID);
1446 		if (!flash_isequal(info, sector, FLASH_OFFSET_PROTECT,
1447 				   prot)) {
1448 			/*
1449 			 * cmd must come before FLASH_CMD_PROTECT + 20us
1450 			 * Disable interrupts which might cause a timeout here.
1451 			 */
1452 			int flag = disable_interrupts();
1453 			unsigned short cmd;
1454 
1455 			if (prot)
1456 				cmd = FLASH_CMD_PROTECT_SET;
1457 			else
1458 				cmd = FLASH_CMD_PROTECT_CLEAR;
1459 
1460 			flash_write_cmd(info, sector, 0, FLASH_CMD_PROTECT);
1461 			flash_write_cmd(info, sector, 0, cmd);
1462 			/* re-enable interrupts if necessary */
1463 			if (flag)
1464 				enable_interrupts();
1465 		}
1466 		return 1;
1467 	}
1468 	return 0;
1469 }
1470 
1471 int flash_real_protect(flash_info_t *info, long sector, int prot)
1472 {
1473 	int retcode = 0;
1474 
1475 	switch (info->vendor) {
1476 	case CFI_CMDSET_INTEL_PROG_REGIONS:
1477 	case CFI_CMDSET_INTEL_STANDARD:
1478 	case CFI_CMDSET_INTEL_EXTENDED:
1479 		if (!cfi_protect_bugfix(info, sector, prot)) {
1480 			flash_write_cmd(info, sector, 0,
1481 				 FLASH_CMD_CLEAR_STATUS);
1482 			flash_write_cmd(info, sector, 0,
1483 				FLASH_CMD_PROTECT);
1484 			if (prot)
1485 				flash_write_cmd(info, sector, 0,
1486 					FLASH_CMD_PROTECT_SET);
1487 			else
1488 				flash_write_cmd(info, sector, 0,
1489 					FLASH_CMD_PROTECT_CLEAR);
1490 		}
1491 		break;
1492 	case CFI_CMDSET_AMD_EXTENDED:
1493 	case CFI_CMDSET_AMD_STANDARD:
1494 		/* U-Boot only checks the first byte */
1495 		if (manufact_match(info, ATM_MANUFACT)) {
1496 			if (prot) {
1497 				flash_unlock_seq(info, 0);
1498 				flash_write_cmd(info, 0,
1499 						info->addr_unlock1,
1500 						ATM_CMD_SOFTLOCK_START);
1501 				flash_unlock_seq(info, 0);
1502 				flash_write_cmd(info, sector, 0,
1503 						ATM_CMD_LOCK_SECT);
1504 			} else {
1505 				flash_write_cmd(info, 0,
1506 						info->addr_unlock1,
1507 						AMD_CMD_UNLOCK_START);
1508 				if (info->device_id == ATM_ID_BV6416)
1509 					flash_write_cmd(info, sector,
1510 						0, ATM_CMD_UNLOCK_SECT);
1511 			}
1512 		}
1513 		if (info->legacy_unlock) {
1514 			int flag = disable_interrupts();
1515 			int lock_flag;
1516 
1517 			flash_unlock_seq(info, 0);
1518 			flash_write_cmd(info, 0, info->addr_unlock1,
1519 					AMD_CMD_SET_PPB_ENTRY);
1520 			lock_flag = flash_isset(info, sector, 0, 0x01);
1521 			if (prot) {
1522 				if (lock_flag) {
1523 					flash_write_cmd(info, sector, 0,
1524 						AMD_CMD_PPB_LOCK_BC1);
1525 					flash_write_cmd(info, sector, 0,
1526 						AMD_CMD_PPB_LOCK_BC2);
1527 				}
1528 				debug("sector %ld %slocked\n", sector,
1529 					lock_flag ? "" : "already ");
1530 			} else {
1531 				if (!lock_flag) {
1532 					debug("unlock %ld\n", sector);
1533 					flash_write_cmd(info, 0, 0,
1534 						AMD_CMD_PPB_UNLOCK_BC1);
1535 					flash_write_cmd(info, 0, 0,
1536 						AMD_CMD_PPB_UNLOCK_BC2);
1537 				}
1538 				debug("sector %ld %sunlocked\n", sector,
1539 					!lock_flag ? "" : "already ");
1540 			}
1541 			if (flag)
1542 				enable_interrupts();
1543 
1544 			if (flash_status_check(info, sector,
1545 					info->erase_blk_tout,
1546 					prot ? "protect" : "unprotect"))
1547 				printf("status check error\n");
1548 
1549 			flash_write_cmd(info, 0, 0,
1550 					AMD_CMD_SET_PPB_EXIT_BC1);
1551 			flash_write_cmd(info, 0, 0,
1552 					AMD_CMD_SET_PPB_EXIT_BC2);
1553 		}
1554 		break;
1555 #ifdef CONFIG_FLASH_CFI_LEGACY
1556 	case CFI_CMDSET_AMD_LEGACY:
1557 		flash_write_cmd(info, sector, 0, FLASH_CMD_CLEAR_STATUS);
1558 		flash_write_cmd(info, sector, 0, FLASH_CMD_PROTECT);
1559 		if (prot)
1560 			flash_write_cmd(info, sector, 0, FLASH_CMD_PROTECT_SET);
1561 		else
1562 			flash_write_cmd(info, sector, 0, FLASH_CMD_PROTECT_CLEAR);
1563 #endif
1564 	};
1565 
1566 	/*
1567 	 * Flash needs to be in status register read mode for
1568 	 * flash_full_status_check() to work correctly
1569 	 */
1570 	flash_write_cmd(info, sector, 0, FLASH_CMD_READ_STATUS);
1571 	if ((retcode =
1572 	     flash_full_status_check(info, sector, info->erase_blk_tout,
1573 				      prot ? "protect" : "unprotect")) == 0) {
1574 		info->protect[sector] = prot;
1575 
1576 		/*
1577 		 * On some of Intel's flash chips (marked via legacy_unlock)
1578 		 * unprotect unprotects all locking.
1579 		 */
1580 		if ((prot == 0) && (info->legacy_unlock)) {
1581 			flash_sect_t i;
1582 
1583 			for (i = 0; i < info->sector_count; i++) {
1584 				if (info->protect[i])
1585 					flash_real_protect(info, i, 1);
1586 			}
1587 		}
1588 	}
1589 	return retcode;
1590 }
1591 
1592 /*-----------------------------------------------------------------------
1593  * flash_read_user_serial - read the OneTimeProgramming cells
1594  */
1595 void flash_read_user_serial(flash_info_t *info, void *buffer, int offset,
1596 			     int len)
1597 {
1598 	uchar *src;
1599 	uchar *dst;
1600 
1601 	dst = buffer;
1602 	src = flash_map(info, 0, FLASH_OFFSET_USER_PROTECTION);
1603 	flash_write_cmd(info, 0, 0, FLASH_CMD_READ_ID);
1604 	memcpy(dst, src + offset, len);
1605 	flash_write_cmd(info, 0, 0, info->cmd_reset);
1606 	udelay(1);
1607 	flash_unmap(info, 0, FLASH_OFFSET_USER_PROTECTION, src);
1608 }
1609 
1610 /*
1611  * flash_read_factory_serial - read the device Id from the protection area
1612  */
1613 void flash_read_factory_serial(flash_info_t *info, void *buffer, int offset,
1614 				int len)
1615 {
1616 	uchar *src;
1617 
1618 	src = flash_map(info, 0, FLASH_OFFSET_INTEL_PROTECTION);
1619 	flash_write_cmd(info, 0, 0, FLASH_CMD_READ_ID);
1620 	memcpy(buffer, src + offset, len);
1621 	flash_write_cmd(info, 0, 0, info->cmd_reset);
1622 	udelay(1);
1623 	flash_unmap(info, 0, FLASH_OFFSET_INTEL_PROTECTION, src);
1624 }
1625 
1626 #endif /* CONFIG_SYS_FLASH_PROTECTION */
1627 
1628 /*-----------------------------------------------------------------------
1629  * Reverse the order of the erase regions in the CFI QRY structure.
1630  * This is needed for chips that are either a) correctly detected as
1631  * top-boot, or b) buggy.
1632  */
1633 static void cfi_reverse_geometry(struct cfi_qry *qry)
1634 {
1635 	unsigned int i, j;
1636 	u32 tmp;
1637 
1638 	for (i = 0, j = qry->num_erase_regions - 1; i < j; i++, j--) {
1639 		tmp = get_unaligned(&(qry->erase_region_info[i]));
1640 		put_unaligned(get_unaligned(&(qry->erase_region_info[j])),
1641 			      &(qry->erase_region_info[i]));
1642 		put_unaligned(tmp, &(qry->erase_region_info[j]));
1643 	}
1644 }
1645 
1646 /*-----------------------------------------------------------------------
1647  * read jedec ids from device and set corresponding fields in info struct
1648  *
1649  * Note: assume cfi->vendor, cfi->portwidth and cfi->chipwidth are correct
1650  *
1651  */
1652 static void cmdset_intel_read_jedec_ids(flash_info_t *info)
1653 {
1654 	flash_write_cmd(info, 0, 0, FLASH_CMD_RESET);
1655 	udelay(1);
1656 	flash_write_cmd(info, 0, 0, FLASH_CMD_READ_ID);
1657 	udelay(1000); /* some flash are slow to respond */
1658 	info->manufacturer_id = flash_read_uchar(info,
1659 					FLASH_OFFSET_MANUFACTURER_ID);
1660 	info->device_id = (info->chipwidth == FLASH_CFI_16BIT) ?
1661 			flash_read_word(info, FLASH_OFFSET_DEVICE_ID) :
1662 			flash_read_uchar(info, FLASH_OFFSET_DEVICE_ID);
1663 	flash_write_cmd(info, 0, 0, FLASH_CMD_RESET);
1664 }
1665 
1666 static int cmdset_intel_init(flash_info_t *info, struct cfi_qry *qry)
1667 {
1668 	info->cmd_reset = FLASH_CMD_RESET;
1669 
1670 	cmdset_intel_read_jedec_ids(info);
1671 	flash_write_cmd(info, 0, info->cfi_offset, FLASH_CMD_CFI);
1672 
1673 #ifdef CONFIG_SYS_FLASH_PROTECTION
1674 	/* read legacy lock/unlock bit from intel flash */
1675 	if (info->ext_addr) {
1676 		info->legacy_unlock = flash_read_uchar(info,
1677 				info->ext_addr + 5) & 0x08;
1678 	}
1679 #endif
1680 
1681 	return 0;
1682 }
1683 
1684 static void cmdset_amd_read_jedec_ids(flash_info_t *info)
1685 {
1686 	ushort bankId = 0;
1687 	uchar  manuId;
1688 	uchar  feature;
1689 
1690 	flash_write_cmd(info, 0, 0, AMD_CMD_RESET);
1691 	flash_unlock_seq(info, 0);
1692 	flash_write_cmd(info, 0, info->addr_unlock1, FLASH_CMD_READ_ID);
1693 	udelay(1000); /* some flash are slow to respond */
1694 
1695 	manuId = flash_read_uchar(info, FLASH_OFFSET_MANUFACTURER_ID);
1696 	/* JEDEC JEP106Z specifies ID codes up to bank 7 */
1697 	while (manuId == FLASH_CONTINUATION_CODE && bankId < 0x800) {
1698 		bankId += 0x100;
1699 		manuId = flash_read_uchar(info,
1700 			bankId | FLASH_OFFSET_MANUFACTURER_ID);
1701 	}
1702 	info->manufacturer_id = manuId;
1703 
1704 	debug("info->ext_addr = 0x%x, cfi_version = 0x%x\n",
1705 	      info->ext_addr, info->cfi_version);
1706 	if (info->ext_addr && info->cfi_version >= 0x3134) {
1707 		/* read software feature (at 0x53) */
1708 		feature = flash_read_uchar(info, info->ext_addr + 0x13);
1709 		debug("feature = 0x%x\n", feature);
1710 		info->sr_supported = feature & 0x1;
1711 	}
1712 
1713 	switch (info->chipwidth) {
1714 	case FLASH_CFI_8BIT:
1715 		info->device_id = flash_read_uchar(info,
1716 						FLASH_OFFSET_DEVICE_ID);
1717 		if (info->device_id == 0x7E) {
1718 			/* AMD 3-byte (expanded) device ids */
1719 			info->device_id2 = flash_read_uchar(info,
1720 						FLASH_OFFSET_DEVICE_ID2);
1721 			info->device_id2 <<= 8;
1722 			info->device_id2 |= flash_read_uchar(info,
1723 						FLASH_OFFSET_DEVICE_ID3);
1724 		}
1725 		break;
1726 	case FLASH_CFI_16BIT:
1727 		info->device_id = flash_read_word(info,
1728 						FLASH_OFFSET_DEVICE_ID);
1729 		if ((info->device_id & 0xff) == 0x7E) {
1730 			/* AMD 3-byte (expanded) device ids */
1731 			info->device_id2 = flash_read_uchar(info,
1732 						FLASH_OFFSET_DEVICE_ID2);
1733 			info->device_id2 <<= 8;
1734 			info->device_id2 |= flash_read_uchar(info,
1735 						FLASH_OFFSET_DEVICE_ID3);
1736 		}
1737 		break;
1738 	default:
1739 		break;
1740 	}
1741 	flash_write_cmd(info, 0, 0, AMD_CMD_RESET);
1742 	udelay(1);
1743 }
1744 
1745 static int cmdset_amd_init(flash_info_t *info, struct cfi_qry *qry)
1746 {
1747 	info->cmd_reset = AMD_CMD_RESET;
1748 	info->cmd_erase_sector = AMD_CMD_ERASE_SECTOR;
1749 
1750 	cmdset_amd_read_jedec_ids(info);
1751 	flash_write_cmd(info, 0, info->cfi_offset, FLASH_CMD_CFI);
1752 
1753 #ifdef CONFIG_SYS_FLASH_PROTECTION
1754 	if (info->ext_addr) {
1755 		/* read sector protect/unprotect scheme (at 0x49) */
1756 		if (flash_read_uchar(info, info->ext_addr + 9) == 0x8)
1757 			info->legacy_unlock = 1;
1758 	}
1759 #endif
1760 
1761 	return 0;
1762 }
1763 
1764 #ifdef CONFIG_FLASH_CFI_LEGACY
1765 static void flash_read_jedec_ids(flash_info_t *info)
1766 {
1767 	info->manufacturer_id = 0;
1768 	info->device_id       = 0;
1769 	info->device_id2      = 0;
1770 
1771 	switch (info->vendor) {
1772 	case CFI_CMDSET_INTEL_PROG_REGIONS:
1773 	case CFI_CMDSET_INTEL_STANDARD:
1774 	case CFI_CMDSET_INTEL_EXTENDED:
1775 		cmdset_intel_read_jedec_ids(info);
1776 		break;
1777 	case CFI_CMDSET_AMD_STANDARD:
1778 	case CFI_CMDSET_AMD_EXTENDED:
1779 		cmdset_amd_read_jedec_ids(info);
1780 		break;
1781 	default:
1782 		break;
1783 	}
1784 }
1785 
1786 /*-----------------------------------------------------------------------
1787  * Call board code to request info about non-CFI flash.
1788  * board_flash_get_legacy needs to fill in at least:
1789  * info->portwidth, info->chipwidth and info->interface for Jedec probing.
1790  */
1791 static int flash_detect_legacy(phys_addr_t base, int banknum)
1792 {
1793 	flash_info_t *info = &flash_info[banknum];
1794 
1795 	if (board_flash_get_legacy(base, banknum, info)) {
1796 		/* board code may have filled info completely. If not, we
1797 		 * use JEDEC ID probing.
1798 		 */
1799 		if (!info->vendor) {
1800 			int modes[] = {
1801 				CFI_CMDSET_AMD_STANDARD,
1802 				CFI_CMDSET_INTEL_STANDARD
1803 			};
1804 			int i;
1805 
1806 			for (i = 0; i < ARRAY_SIZE(modes); i++) {
1807 				info->vendor = modes[i];
1808 				info->start[0] =
1809 					(ulong)map_physmem(base,
1810 							   info->portwidth,
1811 							   MAP_NOCACHE);
1812 				if (info->portwidth == FLASH_CFI_8BIT &&
1813 					info->interface == FLASH_CFI_X8X16) {
1814 					info->addr_unlock1 = 0x2AAA;
1815 					info->addr_unlock2 = 0x5555;
1816 				} else {
1817 					info->addr_unlock1 = 0x5555;
1818 					info->addr_unlock2 = 0x2AAA;
1819 				}
1820 				flash_read_jedec_ids(info);
1821 				debug("JEDEC PROBE: ID %x %x %x\n",
1822 						info->manufacturer_id,
1823 						info->device_id,
1824 						info->device_id2);
1825 				if (jedec_flash_match(info, info->start[0]))
1826 					break;
1827 				else
1828 					unmap_physmem((void *)info->start[0],
1829 						      info->portwidth);
1830 			}
1831 		}
1832 
1833 		switch (info->vendor) {
1834 		case CFI_CMDSET_INTEL_PROG_REGIONS:
1835 		case CFI_CMDSET_INTEL_STANDARD:
1836 		case CFI_CMDSET_INTEL_EXTENDED:
1837 			info->cmd_reset = FLASH_CMD_RESET;
1838 			break;
1839 		case CFI_CMDSET_AMD_STANDARD:
1840 		case CFI_CMDSET_AMD_EXTENDED:
1841 		case CFI_CMDSET_AMD_LEGACY:
1842 			info->cmd_reset = AMD_CMD_RESET;
1843 			break;
1844 		}
1845 		info->flash_id = FLASH_MAN_CFI;
1846 		return 1;
1847 	}
1848 	return 0; /* use CFI */
1849 }
1850 #else
1851 static inline int flash_detect_legacy(phys_addr_t base, int banknum)
1852 {
1853 	return 0; /* use CFI */
1854 }
1855 #endif
1856 
1857 /*-----------------------------------------------------------------------
1858  * detect if flash is compatible with the Common Flash Interface (CFI)
1859  * http://www.jedec.org/download/search/jesd68.pdf
1860  */
1861 static void flash_read_cfi(flash_info_t *info, void *buf,
1862 		unsigned int start, size_t len)
1863 {
1864 	u8 *p = buf;
1865 	unsigned int i;
1866 
1867 	for (i = 0; i < len; i++)
1868 		p[i] = flash_read_uchar(info, start + i);
1869 }
1870 
1871 static void __flash_cmd_reset(flash_info_t *info)
1872 {
1873 	/*
1874 	 * We do not yet know what kind of commandset to use, so we issue
1875 	 * the reset command in both Intel and AMD variants, in the hope
1876 	 * that AMD flash roms ignore the Intel command.
1877 	 */
1878 	flash_write_cmd(info, 0, 0, AMD_CMD_RESET);
1879 	udelay(1);
1880 	flash_write_cmd(info, 0, 0, FLASH_CMD_RESET);
1881 }
1882 
1883 void flash_cmd_reset(flash_info_t *info)
1884 	__attribute__((weak, alias("__flash_cmd_reset")));
1885 
1886 static int __flash_detect_cfi(flash_info_t *info, struct cfi_qry *qry)
1887 {
1888 	int cfi_offset;
1889 
1890 	/* Issue FLASH reset command */
1891 	flash_cmd_reset(info);
1892 
1893 	for (cfi_offset = 0; cfi_offset < ARRAY_SIZE(flash_offset_cfi);
1894 	     cfi_offset++) {
1895 		flash_write_cmd(info, 0, flash_offset_cfi[cfi_offset],
1896 				 FLASH_CMD_CFI);
1897 		if (flash_isequal(info, 0, FLASH_OFFSET_CFI_RESP, 'Q') &&
1898 			flash_isequal(info, 0, FLASH_OFFSET_CFI_RESP + 1, 'R') &&
1899 			flash_isequal(info, 0, FLASH_OFFSET_CFI_RESP + 2, 'Y')) {
1900 			flash_read_cfi(info, qry, FLASH_OFFSET_CFI_RESP,
1901 					sizeof(struct cfi_qry));
1902 			info->interface	= le16_to_cpu(qry->interface_desc);
1903 
1904 			info->cfi_offset = flash_offset_cfi[cfi_offset];
1905 			debug("device interface is %d\n",
1906 			       info->interface);
1907 			debug("found port %d chip %d ",
1908 			       info->portwidth, info->chipwidth);
1909 			debug("port %d bits chip %d bits\n",
1910 			       info->portwidth << CFI_FLASH_SHIFT_WIDTH,
1911 			       info->chipwidth << CFI_FLASH_SHIFT_WIDTH);
1912 
1913 			/* calculate command offsets as in the Linux driver */
1914 			info->addr_unlock1 = 0x555;
1915 			info->addr_unlock2 = 0x2aa;
1916 
1917 			/*
1918 			 * modify the unlock address if we are
1919 			 * in compatibility mode
1920 			 */
1921 			if (/* x8/x16 in x8 mode */
1922 			    ((info->chipwidth == FLASH_CFI_BY8) &&
1923 				(info->interface == FLASH_CFI_X8X16)) ||
1924 			    /* x16/x32 in x16 mode */
1925 			    ((info->chipwidth == FLASH_CFI_BY16) &&
1926 				(info->interface == FLASH_CFI_X16X32)))
1927 			{
1928 				info->addr_unlock1 = 0xaaa;
1929 				info->addr_unlock2 = 0x555;
1930 			}
1931 
1932 			info->name = "CFI conformant";
1933 			return 1;
1934 		}
1935 	}
1936 
1937 	return 0;
1938 }
1939 
1940 static int flash_detect_cfi(flash_info_t *info, struct cfi_qry *qry)
1941 {
1942 	debug("flash detect cfi\n");
1943 
1944 	for (info->portwidth = CONFIG_SYS_FLASH_CFI_WIDTH;
1945 	     info->portwidth <= FLASH_CFI_64BIT; info->portwidth <<= 1) {
1946 		for (info->chipwidth = FLASH_CFI_BY8;
1947 		     info->chipwidth <= info->portwidth;
1948 		     info->chipwidth <<= 1)
1949 			if (__flash_detect_cfi(info, qry))
1950 				return 1;
1951 	}
1952 	debug("not found\n");
1953 	return 0;
1954 }
1955 
1956 /*
1957  * Manufacturer-specific quirks. Add workarounds for geometry
1958  * reversal, etc. here.
1959  */
1960 static void flash_fixup_amd(flash_info_t *info, struct cfi_qry *qry)
1961 {
1962 	/* check if flash geometry needs reversal */
1963 	if (qry->num_erase_regions > 1) {
1964 		/* reverse geometry if top boot part */
1965 		if (info->cfi_version < 0x3131) {
1966 			/* CFI < 1.1, try to guess from device id */
1967 			if ((info->device_id & 0x80) != 0)
1968 				cfi_reverse_geometry(qry);
1969 		} else if (flash_read_uchar(info, info->ext_addr + 0xf) == 3) {
1970 			/* CFI >= 1.1, deduct from top/bottom flag */
1971 			/* note: ext_addr is valid since cfi_version > 0 */
1972 			cfi_reverse_geometry(qry);
1973 		}
1974 	}
1975 }
1976 
1977 static void flash_fixup_atmel(flash_info_t *info, struct cfi_qry *qry)
1978 {
1979 	int reverse_geometry = 0;
1980 
1981 	/* Check the "top boot" bit in the PRI */
1982 	if (info->ext_addr && !(flash_read_uchar(info, info->ext_addr + 6) & 1))
1983 		reverse_geometry = 1;
1984 
1985 	/* AT49BV6416(T) list the erase regions in the wrong order.
1986 	 * However, the device ID is identical with the non-broken
1987 	 * AT49BV642D they differ in the high byte.
1988 	 */
1989 	if (info->device_id == 0xd6 || info->device_id == 0xd2)
1990 		reverse_geometry = !reverse_geometry;
1991 
1992 	if (reverse_geometry)
1993 		cfi_reverse_geometry(qry);
1994 }
1995 
1996 static void flash_fixup_stm(flash_info_t *info, struct cfi_qry *qry)
1997 {
1998 	/* check if flash geometry needs reversal */
1999 	if (qry->num_erase_regions > 1) {
2000 		/* reverse geometry if top boot part */
2001 		if (info->cfi_version < 0x3131) {
2002 			/* CFI < 1.1, guess by device id */
2003 			if (info->device_id == 0x22CA || /* M29W320DT */
2004 			    info->device_id == 0x2256 || /* M29W320ET */
2005 			    info->device_id == 0x22D7) { /* M29W800DT */
2006 				cfi_reverse_geometry(qry);
2007 			}
2008 		} else if (flash_read_uchar(info, info->ext_addr + 0xf) == 3) {
2009 			/* CFI >= 1.1, deduct from top/bottom flag */
2010 			/* note: ext_addr is valid since cfi_version > 0 */
2011 			cfi_reverse_geometry(qry);
2012 		}
2013 	}
2014 }
2015 
2016 static void flash_fixup_sst(flash_info_t *info, struct cfi_qry *qry)
2017 {
2018 	/*
2019 	 * SST, for many recent nor parallel flashes, says they are
2020 	 * CFI-conformant. This is not true, since qry struct.
2021 	 * reports a std. AMD command set (0x0002), while SST allows to
2022 	 * erase two different sector sizes for the same memory.
2023 	 * 64KB sector (SST call it block)  needs 0x30 to be erased.
2024 	 * 4KB  sector (SST call it sector) needs 0x50 to be erased.
2025 	 * Since CFI query detect the 4KB number of sectors, users expects
2026 	 * a sector granularity of 4KB, and it is here set.
2027 	 */
2028 	if (info->device_id == 0x5D23 || /* SST39VF3201B */
2029 	    info->device_id == 0x5C23) { /* SST39VF3202B */
2030 		/* set sector granularity to 4KB */
2031 		info->cmd_erase_sector = 0x50;
2032 	}
2033 }
2034 
2035 static void flash_fixup_num(flash_info_t *info, struct cfi_qry *qry)
2036 {
2037 	/*
2038 	 * The M29EW devices seem to report the CFI information wrong
2039 	 * when it's in 8 bit mode.
2040 	 * There's an app note from Numonyx on this issue.
2041 	 * So adjust the buffer size for M29EW while operating in 8-bit mode
2042 	 */
2043 	if (((qry->max_buf_write_size) > 0x8) &&
2044 			(info->device_id == 0x7E) &&
2045 			(info->device_id2 == 0x2201 ||
2046 			info->device_id2 == 0x2301 ||
2047 			info->device_id2 == 0x2801 ||
2048 			info->device_id2 == 0x4801)) {
2049 		debug("Adjusted buffer size on Numonyx flash"
2050 			" M29EW family in 8 bit mode\n");
2051 		qry->max_buf_write_size = 0x8;
2052 	}
2053 }
2054 
2055 /*
2056  * The following code cannot be run from FLASH!
2057  *
2058  */
2059 ulong flash_get_size(phys_addr_t base, int banknum)
2060 {
2061 	flash_info_t *info = &flash_info[banknum];
2062 	int i, j;
2063 	flash_sect_t sect_cnt;
2064 	phys_addr_t sector;
2065 	unsigned long tmp;
2066 	int size_ratio;
2067 	uchar num_erase_regions;
2068 	int erase_region_size;
2069 	int erase_region_count;
2070 	struct cfi_qry qry;
2071 	unsigned long max_size;
2072 
2073 	memset(&qry, 0, sizeof(qry));
2074 
2075 	info->ext_addr = 0;
2076 	info->cfi_version = 0;
2077 #ifdef CONFIG_SYS_FLASH_PROTECTION
2078 	info->legacy_unlock = 0;
2079 #endif
2080 
2081 	info->start[0] = (ulong)map_physmem(base, info->portwidth, MAP_NOCACHE);
2082 
2083 	if (flash_detect_cfi(info, &qry)) {
2084 		info->vendor = le16_to_cpu(get_unaligned(&(qry.p_id)));
2085 		info->ext_addr = le16_to_cpu(get_unaligned(&(qry.p_adr)));
2086 		num_erase_regions = qry.num_erase_regions;
2087 
2088 		if (info->ext_addr) {
2089 			info->cfi_version = (ushort)flash_read_uchar(info,
2090 						info->ext_addr + 3) << 8;
2091 			info->cfi_version |= (ushort)flash_read_uchar(info,
2092 						info->ext_addr + 4);
2093 		}
2094 
2095 #ifdef DEBUG
2096 		flash_printqry(&qry);
2097 #endif
2098 
2099 		switch (info->vendor) {
2100 		case CFI_CMDSET_INTEL_PROG_REGIONS:
2101 		case CFI_CMDSET_INTEL_STANDARD:
2102 		case CFI_CMDSET_INTEL_EXTENDED:
2103 			cmdset_intel_init(info, &qry);
2104 			break;
2105 		case CFI_CMDSET_AMD_STANDARD:
2106 		case CFI_CMDSET_AMD_EXTENDED:
2107 			cmdset_amd_init(info, &qry);
2108 			break;
2109 		default:
2110 			printf("CFI: Unknown command set 0x%x\n",
2111 					info->vendor);
2112 			/*
2113 			 * Unfortunately, this means we don't know how
2114 			 * to get the chip back to Read mode. Might
2115 			 * as well try an Intel-style reset...
2116 			 */
2117 			flash_write_cmd(info, 0, 0, FLASH_CMD_RESET);
2118 			return 0;
2119 		}
2120 
2121 		/* Do manufacturer-specific fixups */
2122 		switch (info->manufacturer_id) {
2123 		case 0x0001: /* AMD */
2124 		case 0x0037: /* AMIC */
2125 			flash_fixup_amd(info, &qry);
2126 			break;
2127 		case 0x001f:
2128 			flash_fixup_atmel(info, &qry);
2129 			break;
2130 		case 0x0020:
2131 			flash_fixup_stm(info, &qry);
2132 			break;
2133 		case 0x00bf: /* SST */
2134 			flash_fixup_sst(info, &qry);
2135 			break;
2136 		case 0x0089: /* Numonyx */
2137 			flash_fixup_num(info, &qry);
2138 			break;
2139 		}
2140 
2141 		debug("manufacturer is %d\n", info->vendor);
2142 		debug("manufacturer id is 0x%x\n", info->manufacturer_id);
2143 		debug("device id is 0x%x\n", info->device_id);
2144 		debug("device id2 is 0x%x\n", info->device_id2);
2145 		debug("cfi version is 0x%04x\n", info->cfi_version);
2146 
2147 		size_ratio = info->portwidth / info->chipwidth;
2148 		/* if the chip is x8/x16 reduce the ratio by half */
2149 		if ((info->interface == FLASH_CFI_X8X16) &&
2150 			(info->chipwidth == FLASH_CFI_BY8)) {
2151 			size_ratio >>= 1;
2152 		}
2153 		debug("size_ratio %d port %d bits chip %d bits\n",
2154 		       size_ratio, info->portwidth << CFI_FLASH_SHIFT_WIDTH,
2155 		       info->chipwidth << CFI_FLASH_SHIFT_WIDTH);
2156 		info->size = 1 << qry.dev_size;
2157 		/* multiply the size by the number of chips */
2158 		info->size *= size_ratio;
2159 		max_size = cfi_flash_bank_size(banknum);
2160 		if (max_size && (info->size > max_size)) {
2161 			debug("[truncated from %ldMiB]", info->size >> 20);
2162 			info->size = max_size;
2163 		}
2164 		debug("found %d erase regions\n", num_erase_regions);
2165 		sect_cnt = 0;
2166 		sector = base;
2167 		for (i = 0; i < num_erase_regions; i++) {
2168 			if (i > NUM_ERASE_REGIONS) {
2169 				printf("%d erase regions found, only %d used\n",
2170 					num_erase_regions, NUM_ERASE_REGIONS);
2171 				break;
2172 			}
2173 
2174 			tmp = le32_to_cpu(get_unaligned(
2175 						&(qry.erase_region_info[i])));
2176 			debug("erase region %u: 0x%08lx\n", i, tmp);
2177 
2178 			erase_region_count = (tmp & 0xffff) + 1;
2179 			tmp >>= 16;
2180 			erase_region_size =
2181 				(tmp & 0xffff) ? ((tmp & 0xffff) * 256) : 128;
2182 			debug("erase_region_count = %d erase_region_size = %d\n",
2183 				erase_region_count, erase_region_size);
2184 			for (j = 0; j < erase_region_count; j++) {
2185 				if (sector - base >= info->size)
2186 					break;
2187 				if (sect_cnt >= CONFIG_SYS_MAX_FLASH_SECT) {
2188 					printf("ERROR: too many flash sectors\n");
2189 					break;
2190 				}
2191 				info->start[sect_cnt] =
2192 					(ulong)map_physmem(sector,
2193 							   info->portwidth,
2194 							   MAP_NOCACHE);
2195 				sector += (erase_region_size * size_ratio);
2196 
2197 				/*
2198 				 * Only read protection status from
2199 				 * supported devices (intel...)
2200 				 */
2201 				switch (info->vendor) {
2202 				case CFI_CMDSET_INTEL_PROG_REGIONS:
2203 				case CFI_CMDSET_INTEL_EXTENDED:
2204 				case CFI_CMDSET_INTEL_STANDARD:
2205 					/*
2206 					 * Set flash to read-id mode. Otherwise
2207 					 * reading protected status is not
2208 					 * guaranteed.
2209 					 */
2210 					flash_write_cmd(info, sect_cnt, 0,
2211 							FLASH_CMD_READ_ID);
2212 					info->protect[sect_cnt] =
2213 						flash_isset(info, sect_cnt,
2214 							     FLASH_OFFSET_PROTECT,
2215 							     FLASH_STATUS_PROTECT);
2216 					flash_write_cmd(info, sect_cnt, 0,
2217 							FLASH_CMD_RESET);
2218 					break;
2219 				case CFI_CMDSET_AMD_EXTENDED:
2220 				case CFI_CMDSET_AMD_STANDARD:
2221 					if (!info->legacy_unlock) {
2222 						/* default: not protected */
2223 						info->protect[sect_cnt] = 0;
2224 						break;
2225 					}
2226 
2227 					/* Read protection (PPB) from sector */
2228 					flash_write_cmd(info, 0, 0,
2229 							info->cmd_reset);
2230 					flash_unlock_seq(info, 0);
2231 					flash_write_cmd(info, 0,
2232 							info->addr_unlock1,
2233 							FLASH_CMD_READ_ID);
2234 					info->protect[sect_cnt] =
2235 						flash_isset(
2236 							info, sect_cnt,
2237 							FLASH_OFFSET_PROTECT,
2238 							FLASH_STATUS_PROTECT);
2239 					break;
2240 				default:
2241 					/* default: not protected */
2242 					info->protect[sect_cnt] = 0;
2243 				}
2244 
2245 				sect_cnt++;
2246 			}
2247 		}
2248 
2249 		info->sector_count = sect_cnt;
2250 		info->buffer_size = 1 << le16_to_cpu(qry.max_buf_write_size);
2251 		tmp = 1 << qry.block_erase_timeout_typ;
2252 		info->erase_blk_tout = tmp *
2253 			(1 << qry.block_erase_timeout_max);
2254 		tmp = (1 << qry.buf_write_timeout_typ) *
2255 			(1 << qry.buf_write_timeout_max);
2256 
2257 		/* round up when converting to ms */
2258 		info->buffer_write_tout = (tmp + 999) / 1000;
2259 		tmp = (1 << qry.word_write_timeout_typ) *
2260 			(1 << qry.word_write_timeout_max);
2261 		/* round up when converting to ms */
2262 		info->write_tout = (tmp + 999) / 1000;
2263 		info->flash_id = FLASH_MAN_CFI;
2264 		if ((info->interface == FLASH_CFI_X8X16) &&
2265 		    (info->chipwidth == FLASH_CFI_BY8)) {
2266 			/* XXX - Need to test on x8/x16 in parallel. */
2267 			info->portwidth >>= 1;
2268 		}
2269 
2270 		flash_write_cmd(info, 0, 0, info->cmd_reset);
2271 	}
2272 
2273 	return (info->size);
2274 }
2275 
2276 #ifdef CONFIG_FLASH_CFI_MTD
2277 void flash_set_verbose(uint v)
2278 {
2279 	flash_verbose = v;
2280 }
2281 #endif
2282 
2283 static void cfi_flash_set_config_reg(u32 base, u16 val)
2284 {
2285 #ifdef CONFIG_SYS_CFI_FLASH_CONFIG_REGS
2286 	/*
2287 	 * Only set this config register if really defined
2288 	 * to a valid value (0xffff is invalid)
2289 	 */
2290 	if (val == 0xffff)
2291 		return;
2292 
2293 	/*
2294 	 * Set configuration register. Data is "encrypted" in the 16 lower
2295 	 * address bits.
2296 	 */
2297 	flash_write16(FLASH_CMD_SETUP, (void *)(base + (val << 1)));
2298 	flash_write16(FLASH_CMD_SET_CR_CONFIRM, (void *)(base + (val << 1)));
2299 
2300 	/*
2301 	 * Finally issue reset-command to bring device back to
2302 	 * read-array mode
2303 	 */
2304 	flash_write16(FLASH_CMD_RESET, (void *)base);
2305 #endif
2306 }
2307 
2308 /*-----------------------------------------------------------------------
2309  */
2310 
2311 static void flash_protect_default(void)
2312 {
2313 #if defined(CONFIG_SYS_FLASH_AUTOPROTECT_LIST)
2314 	int i;
2315 	struct apl_s {
2316 		ulong start;
2317 		ulong size;
2318 	} apl[] = CONFIG_SYS_FLASH_AUTOPROTECT_LIST;
2319 #endif
2320 
2321 	/* Monitor protection ON by default */
2322 #if (CONFIG_SYS_MONITOR_BASE >= CONFIG_SYS_FLASH_BASE) && \
2323 	(!defined(CONFIG_MONITOR_IS_IN_RAM))
2324 	flash_protect(FLAG_PROTECT_SET,
2325 		       CONFIG_SYS_MONITOR_BASE,
2326 		       CONFIG_SYS_MONITOR_BASE + monitor_flash_len  - 1,
2327 		       flash_get_info(CONFIG_SYS_MONITOR_BASE));
2328 #endif
2329 
2330 	/* Environment protection ON by default */
2331 #ifdef CONFIG_ENV_IS_IN_FLASH
2332 	flash_protect(FLAG_PROTECT_SET,
2333 		       CONFIG_ENV_ADDR,
2334 		       CONFIG_ENV_ADDR + CONFIG_ENV_SECT_SIZE - 1,
2335 		       flash_get_info(CONFIG_ENV_ADDR));
2336 #endif
2337 
2338 	/* Redundant environment protection ON by default */
2339 #ifdef CONFIG_ENV_ADDR_REDUND
2340 	flash_protect(FLAG_PROTECT_SET,
2341 		       CONFIG_ENV_ADDR_REDUND,
2342 		       CONFIG_ENV_ADDR_REDUND + CONFIG_ENV_SECT_SIZE - 1,
2343 		       flash_get_info(CONFIG_ENV_ADDR_REDUND));
2344 #endif
2345 
2346 #if defined(CONFIG_SYS_FLASH_AUTOPROTECT_LIST)
2347 	for (i = 0; i < ARRAY_SIZE(apl); i++) {
2348 		debug("autoprotecting from %08lx to %08lx\n",
2349 		      apl[i].start, apl[i].start + apl[i].size - 1);
2350 		flash_protect(FLAG_PROTECT_SET,
2351 			       apl[i].start,
2352 			       apl[i].start + apl[i].size - 1,
2353 			       flash_get_info(apl[i].start));
2354 	}
2355 #endif
2356 }
2357 
2358 unsigned long flash_init(void)
2359 {
2360 	unsigned long size = 0;
2361 	int i;
2362 
2363 #ifdef CONFIG_SYS_FLASH_PROTECTION
2364 	/* read environment from EEPROM */
2365 	char s[64];
2366 
2367 	env_get_f("unlock", s, sizeof(s));
2368 #endif
2369 
2370 #ifdef CONFIG_CFI_FLASH /* for driver model */
2371 	cfi_flash_init_dm();
2372 #endif
2373 
2374 	/* Init: no FLASHes known */
2375 	for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; ++i) {
2376 		flash_info[i].flash_id = FLASH_UNKNOWN;
2377 
2378 		/* Optionally write flash configuration register */
2379 		cfi_flash_set_config_reg(cfi_flash_bank_addr(i),
2380 					 cfi_flash_config_reg(i));
2381 
2382 		if (!flash_detect_legacy(cfi_flash_bank_addr(i), i))
2383 			flash_get_size(cfi_flash_bank_addr(i), i);
2384 		size += flash_info[i].size;
2385 		if (flash_info[i].flash_id == FLASH_UNKNOWN) {
2386 #ifndef CONFIG_SYS_FLASH_QUIET_TEST
2387 			printf("## Unknown flash on Bank %d "
2388 				"- Size = 0x%08lx = %ld MB\n",
2389 				i + 1, flash_info[i].size,
2390 				flash_info[i].size >> 20);
2391 #endif /* CONFIG_SYS_FLASH_QUIET_TEST */
2392 		}
2393 #ifdef CONFIG_SYS_FLASH_PROTECTION
2394 		else if (strcmp(s, "yes") == 0) {
2395 			/*
2396 			 * Only the U-Boot image and it's environment
2397 			 * is protected, all other sectors are
2398 			 * unprotected (unlocked) if flash hardware
2399 			 * protection is used (CONFIG_SYS_FLASH_PROTECTION)
2400 			 * and the environment variable "unlock" is
2401 			 * set to "yes".
2402 			 */
2403 			if (flash_info[i].legacy_unlock) {
2404 				int k;
2405 
2406 				/*
2407 				 * Disable legacy_unlock temporarily,
2408 				 * since flash_real_protect would
2409 				 * relock all other sectors again
2410 				 * otherwise.
2411 				 */
2412 				flash_info[i].legacy_unlock = 0;
2413 
2414 				/*
2415 				 * Legacy unlocking (e.g. Intel J3) ->
2416 				 * unlock only one sector. This will
2417 				 * unlock all sectors.
2418 				 */
2419 				flash_real_protect(&flash_info[i], 0, 0);
2420 
2421 				flash_info[i].legacy_unlock = 1;
2422 
2423 				/*
2424 				 * Manually mark other sectors as
2425 				 * unlocked (unprotected)
2426 				 */
2427 				for (k = 1; k < flash_info[i].sector_count; k++)
2428 					flash_info[i].protect[k] = 0;
2429 			} else {
2430 				/*
2431 				 * No legancy unlocking -> unlock all sectors
2432 				 */
2433 				flash_protect(FLAG_PROTECT_CLEAR,
2434 					       flash_info[i].start[0],
2435 					       flash_info[i].start[0]
2436 					       + flash_info[i].size - 1,
2437 					       &flash_info[i]);
2438 			}
2439 		}
2440 #endif /* CONFIG_SYS_FLASH_PROTECTION */
2441 	}
2442 
2443 	flash_protect_default();
2444 #ifdef CONFIG_FLASH_CFI_MTD
2445 	cfi_mtd_init();
2446 #endif
2447 
2448 	return (size);
2449 }
2450 
2451 #ifdef CONFIG_CFI_FLASH /* for driver model */
2452 static int cfi_flash_probe(struct udevice *dev)
2453 {
2454 	void *blob = (void *)gd->fdt_blob;
2455 	int node = dev_of_offset(dev);
2456 	const fdt32_t *cell;
2457 	phys_addr_t addr;
2458 	int parent, addrc, sizec;
2459 	int len, idx;
2460 
2461 	parent = fdt_parent_offset(blob, node);
2462 	fdt_support_default_count_cells(blob, parent, &addrc, &sizec);
2463 	/* decode regs, there may be multiple reg tuples. */
2464 	cell = fdt_getprop(blob, node, "reg", &len);
2465 	if (!cell)
2466 		return -ENOENT;
2467 	idx = 0;
2468 	len /= sizeof(fdt32_t);
2469 	while (idx < len) {
2470 		addr = fdt_translate_address((void *)blob,
2471 					     node, cell + idx);
2472 		flash_info[cfi_flash_num_flash_banks].dev = dev;
2473 		flash_info[cfi_flash_num_flash_banks].base = addr;
2474 		cfi_flash_num_flash_banks++;
2475 		idx += addrc + sizec;
2476 	}
2477 	gd->bd->bi_flashstart = flash_info[0].base;
2478 
2479 	return 0;
2480 }
2481 
2482 static const struct udevice_id cfi_flash_ids[] = {
2483 	{ .compatible = "cfi-flash" },
2484 	{ .compatible = "jedec-flash" },
2485 	{}
2486 };
2487 
2488 U_BOOT_DRIVER(cfi_flash) = {
2489 	.name	= "cfi_flash",
2490 	.id	= UCLASS_MTD,
2491 	.of_match = cfi_flash_ids,
2492 	.probe = cfi_flash_probe,
2493 };
2494 #endif /* CONFIG_CFI_FLASH */
2495