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