]> git.gag.com Git - fw/openocd/blob - src/flash/nor/cfi.c
flash: stm32f2x incorrectly using 512 as max family size
[fw/openocd] / src / flash / nor / cfi.c
1 /***************************************************************************
2  *   Copyright (C) 2005, 2007 by Dominic Rath                              *
3  *   Dominic.Rath@gmx.de                                                   *
4  *   Copyright (C) 2009 Michael Schwingen                                  *
5  *   michael@schwingen.org                                                 *
6  *   Copyright (C) 2010 Ã˜yvind Harboe <oyvind.harboe@zylin.com>            *
7  *   Copyright (C) 2010 by Antonio Borneo <borneo.antonio@gmail.com>       *
8  *                                                                         *
9  *   This program is free software; you can redistribute it and/or modify  *
10  *   it under the terms of the GNU General Public License as published by  *
11  *   the Free Software Foundation; either version 2 of the License, or     *
12  *   (at your option) any later version.                                   *
13  *                                                                         *
14  *   This program is distributed in the hope that it will be useful,       *
15  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
16  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
17  *   GNU General Public License for more details.                          *
18  *                                                                         *
19  *   You should have received a copy of the GNU General Public License     *
20  *   along with this program; if not, write to the                         *
21  *   Free Software Foundation, Inc.,                                       *
22  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
23  ***************************************************************************/
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include "imp.h"
29 #include "cfi.h"
30 #include "non_cfi.h"
31 #include <target/arm.h>
32 #include <target/arm7_9_common.h>
33 #include <target/armv7m.h>
34 #include <target/mips32.h>
35 #include <helper/binarybuffer.h>
36 #include <target/algorithm.h>
37
38
39 #define CFI_MAX_BUS_WIDTH       4
40 #define CFI_MAX_CHIP_WIDTH      4
41
42 /* defines internal maximum size for code fragment in cfi_intel_write_block() */
43 #define CFI_MAX_INTEL_CODESIZE 256
44
45 /* some id-types with specific handling */
46 #define AT49BV6416      0x00d6
47 #define AT49BV6416T     0x00d2
48
49 static struct cfi_unlock_addresses cfi_unlock_addresses[] =
50 {
51         [CFI_UNLOCK_555_2AA] = { .unlock1 = 0x555, .unlock2 = 0x2aa },
52         [CFI_UNLOCK_5555_2AAA] = { .unlock1 = 0x5555, .unlock2 = 0x2aaa },
53 };
54
55 /* CFI fixups foward declarations */
56 static void cfi_fixup_0002_erase_regions(struct flash_bank *bank, void *param);
57 static void cfi_fixup_0002_unlock_addresses(struct flash_bank *bank, void *param);
58 static void cfi_fixup_reversed_erase_regions(struct flash_bank *bank, void *param);
59 static void cfi_fixup_0002_write_buffer(struct flash_bank *bank, void *param);
60
61 /* fixup after reading cmdset 0002 primary query table */
62 static const struct cfi_fixup cfi_0002_fixups[] = {
63         {CFI_MFR_SST, 0x00D4, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
64         {CFI_MFR_SST, 0x00D5, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
65         {CFI_MFR_SST, 0x00D6, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
66         {CFI_MFR_SST, 0x00D7, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
67         {CFI_MFR_SST, 0x2780, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
68         {CFI_MFR_SST, 0x274b, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
69         {CFI_MFR_SST, 0x236d, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
70         {CFI_MFR_ATMEL, 0x00C8, cfi_fixup_reversed_erase_regions, NULL},
71         {CFI_MFR_ST, 0x22C4, cfi_fixup_reversed_erase_regions, NULL}, /* M29W160ET */
72         {CFI_MFR_FUJITSU, 0x22ea, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
73         {CFI_MFR_FUJITSU, 0x226b, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
74         {CFI_MFR_AMIC, 0xb31a, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
75         {CFI_MFR_MX, 0x225b, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
76         {CFI_MFR_EON, 0x225b, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
77         {CFI_MFR_AMD, 0x225b, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
78         {CFI_MFR_ANY, CFI_ID_ANY, cfi_fixup_0002_erase_regions, NULL},
79         {CFI_MFR_ST, 0x227E, cfi_fixup_0002_write_buffer, NULL}, /* M29W128G */
80         {0, 0, NULL, NULL}
81 };
82
83 /* fixup after reading cmdset 0001 primary query table */
84 static const struct cfi_fixup cfi_0001_fixups[] = {
85         {0, 0, NULL, NULL}
86 };
87
88 static void cfi_fixup(struct flash_bank *bank, const struct cfi_fixup *fixups)
89 {
90         struct cfi_flash_bank *cfi_info = bank->driver_priv;
91         const struct cfi_fixup *f;
92
93         for (f = fixups; f->fixup; f++)
94         {
95                 if (((f->mfr == CFI_MFR_ANY) || (f->mfr == cfi_info->manufacturer)) &&
96                         ((f->id  == CFI_ID_ANY)  || (f->id  == cfi_info->device_id)))
97                 {
98                         f->fixup(bank, f->param);
99                 }
100         }
101 }
102
103 /* inline uint32_t flash_address(struct flash_bank *bank, int sector, uint32_t offset) */
104 static __inline__ uint32_t flash_address(struct flash_bank *bank, int sector, uint32_t offset)
105 {
106         struct cfi_flash_bank *cfi_info = bank->driver_priv;
107
108         if (cfi_info->x16_as_x8) offset *= 2;
109
110         /* while the sector list isn't built, only accesses to sector 0 work */
111         if (sector == 0)
112                 return bank->base + offset * bank->bus_width;
113         else
114         {
115                 if (!bank->sectors)
116                 {
117                         LOG_ERROR("BUG: sector list not yet built");
118                         exit(-1);
119                 }
120                 return bank->base + bank->sectors[sector].offset + offset * bank->bus_width;
121         }
122 }
123
124 static void cfi_command(struct flash_bank *bank, uint8_t cmd, uint8_t *cmd_buf)
125 {
126         int i;
127
128         /* clear whole buffer, to ensure bits that exceed the bus_width
129          * are set to zero
130          */
131         for (i = 0; i < CFI_MAX_BUS_WIDTH; i++)
132                 cmd_buf[i] = 0;
133
134         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
135         {
136                 for (i = bank->bus_width; i > 0; i--)
137                 {
138                         *cmd_buf++ = (i & (bank->chip_width - 1)) ? 0x0 : cmd;
139                 }
140         }
141         else
142         {
143                 for (i = 1; i <= bank->bus_width; i++)
144                 {
145                         *cmd_buf++ = (i & (bank->chip_width - 1)) ? 0x0 : cmd;
146                 }
147         }
148 }
149
150 static int cfi_send_command(struct flash_bank *bank, uint8_t cmd, uint32_t address)
151 {
152         uint8_t command[CFI_MAX_BUS_WIDTH];
153
154         cfi_command(bank, cmd, command);
155         return target_write_memory(bank->target, address, bank->bus_width, 1, command);
156 }
157
158 /* read unsigned 8-bit value from the bank
159  * flash banks are expected to be made of similar chips
160  * the query result should be the same for all
161  */
162 static int cfi_query_u8(struct flash_bank *bank, int sector, uint32_t offset, uint8_t *val)
163 {
164         struct target *target = bank->target;
165         uint8_t data[CFI_MAX_BUS_WIDTH];
166
167         int retval;
168         retval = target_read_memory(target, flash_address(bank, sector, offset),
169                         bank->bus_width, 1, data);
170         if (retval != ERROR_OK)
171                 return retval;
172
173         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
174                 *val = data[0];
175         else
176                 *val = data[bank->bus_width - 1];
177
178         return ERROR_OK;
179 }
180
181 /* read unsigned 8-bit value from the bank
182  * in case of a bank made of multiple chips,
183  * the individual values are ORed
184  */
185 static int cfi_get_u8(struct flash_bank *bank, int sector, uint32_t offset, uint8_t *val)
186 {
187         struct target *target = bank->target;
188         uint8_t data[CFI_MAX_BUS_WIDTH];
189         int i;
190
191         int retval;
192         retval = target_read_memory(target, flash_address(bank, sector, offset),
193                         bank->bus_width, 1, data);
194         if (retval != ERROR_OK)
195                 return retval;
196
197         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
198         {
199                 for (i = 0; i < bank->bus_width / bank->chip_width; i++)
200                         data[0] |= data[i];
201
202                 *val = data[0];
203         }
204         else
205         {
206                 uint8_t value = 0;
207                 for (i = 0; i < bank->bus_width / bank->chip_width; i++)
208                         value |= data[bank->bus_width - 1 - i];
209
210                 *val = value;
211         }
212         return ERROR_OK;
213 }
214
215 static int cfi_query_u16(struct flash_bank *bank, int sector, uint32_t offset, uint16_t *val)
216 {
217         struct target *target = bank->target;
218         struct cfi_flash_bank *cfi_info = bank->driver_priv;
219         uint8_t data[CFI_MAX_BUS_WIDTH * 2];
220         int retval;
221
222         if (cfi_info->x16_as_x8)
223         {
224                 uint8_t i;
225                 for (i = 0;i < 2;i++)
226                 {
227                         retval = target_read_memory(target, flash_address(bank, sector, offset + i),
228                                         bank->bus_width, 1, &data[i * bank->bus_width]);
229                         if (retval != ERROR_OK)
230                                 return retval;
231                 }
232         } else
233         {
234                 retval = target_read_memory(target, flash_address(bank, sector, offset),
235                                 bank->bus_width, 2, data);
236                 if (retval != ERROR_OK)
237                         return retval;
238         }
239
240         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
241                 *val = data[0] | data[bank->bus_width] << 8;
242         else
243                 *val = data[bank->bus_width - 1] | data[(2 * bank->bus_width) - 1] << 8;
244
245         return ERROR_OK;
246 }
247
248 static int cfi_query_u32(struct flash_bank *bank, int sector, uint32_t offset, uint32_t *val)
249 {
250         struct target *target = bank->target;
251         struct cfi_flash_bank *cfi_info = bank->driver_priv;
252         uint8_t data[CFI_MAX_BUS_WIDTH * 4];
253         int retval;
254
255         if (cfi_info->x16_as_x8)
256         {
257                 uint8_t i;
258                 for (i = 0;i < 4;i++)
259                 {
260                         retval = target_read_memory(target, flash_address(bank, sector, offset + i),
261                                         bank->bus_width, 1, &data[i * bank->bus_width]);
262                         if (retval != ERROR_OK)
263                                 return retval;
264                 }
265         }
266         else
267         {
268                 retval = target_read_memory(target, flash_address(bank, sector, offset),
269                                 bank->bus_width, 4, data);
270                 if (retval != ERROR_OK)
271                         return retval;
272         }
273
274         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
275                 *val = data[0] | data[bank->bus_width] << 8 |
276                                 data[bank->bus_width * 2] << 16 | data[bank->bus_width * 3] << 24;
277         else
278                 *val = data[bank->bus_width - 1] | data[(2* bank->bus_width) - 1] << 8 |
279                                 data[(3 * bank->bus_width) - 1] << 16 | data[(4 * bank->bus_width) - 1] << 24;
280
281         return ERROR_OK;
282 }
283
284 static int cfi_reset(struct flash_bank *bank)
285 {
286         struct cfi_flash_bank *cfi_info = bank->driver_priv;
287         int retval = ERROR_OK;
288
289         if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
290         {
291                 return retval;
292         }
293
294         if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
295         {
296                 return retval;
297         }
298
299         if (cfi_info->manufacturer == 0x20 &&
300                         (cfi_info->device_id == 0x227E || cfi_info->device_id == 0x7E))
301         {
302                 /* Numonix M29W128G is cmd 0xFF intolerant - causes internal undefined state
303                  * so we send an extra 0xF0 reset to fix the bug */
304                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x00))) != ERROR_OK)
305                 {
306                         return retval;
307                 }
308         }
309
310         return retval;
311 }
312
313 static void cfi_intel_clear_status_register(struct flash_bank *bank)
314 {
315         cfi_send_command(bank, 0x50, flash_address(bank, 0, 0x0));
316 }
317
318 static int cfi_intel_wait_status_busy(struct flash_bank *bank, int timeout, uint8_t *val)
319 {
320         uint8_t status;
321
322         int retval = ERROR_OK;
323
324         for (;;)
325         {
326                 if (timeout-- < 0)
327                 {
328                         LOG_ERROR("timeout while waiting for WSM to become ready");
329                         return ERROR_FAIL;
330                 }
331
332                 retval = cfi_get_u8(bank, 0, 0x0, &status);
333                 if (retval != ERROR_OK)
334                         return retval;
335
336                 if (status & 0x80)
337                         break;
338
339                 alive_sleep(1);
340         }
341
342         /* mask out bit 0 (reserved) */
343         status = status & 0xfe;
344
345         LOG_DEBUG("status: 0x%x", status);
346
347         if (status != 0x80)
348         {
349                 LOG_ERROR("status register: 0x%x", status);
350                 if (status & 0x2)
351                         LOG_ERROR("Block Lock-Bit Detected, Operation Abort");
352                 if (status & 0x4)
353                         LOG_ERROR("Program suspended");
354                 if (status & 0x8)
355                         LOG_ERROR("Low Programming Voltage Detected, Operation Aborted");
356                 if (status & 0x10)
357                         LOG_ERROR("Program Error / Error in Setting Lock-Bit");
358                 if (status & 0x20)
359                         LOG_ERROR("Error in Block Erasure or Clear Lock-Bits");
360                 if (status & 0x40)
361                         LOG_ERROR("Block Erase Suspended");
362
363                 cfi_intel_clear_status_register(bank);
364
365                 retval = ERROR_FAIL;
366         }
367
368         *val = status;
369         return retval;
370 }
371
372 static int cfi_spansion_wait_status_busy(struct flash_bank *bank, int timeout)
373 {
374         uint8_t status, oldstatus;
375         struct cfi_flash_bank *cfi_info = bank->driver_priv;
376         int retval;
377
378         retval = cfi_get_u8(bank, 0, 0x0, &oldstatus);
379         if (retval != ERROR_OK)
380                 return retval;
381
382         do {
383                 retval = cfi_get_u8(bank, 0, 0x0, &status);
384
385                 if (retval != ERROR_OK)
386                         return retval;
387
388                 if ((status ^ oldstatus) & 0x40) {
389                         if (status & cfi_info->status_poll_mask & 0x20) {
390                                 retval = cfi_get_u8(bank, 0, 0x0, &oldstatus);
391                                 if (retval != ERROR_OK)
392                                         return retval;
393                                 retval = cfi_get_u8(bank, 0, 0x0, &status);
394                                 if (retval != ERROR_OK)
395                                         return retval;
396                                 if ((status ^ oldstatus) & 0x40) {
397                                         LOG_ERROR("dq5 timeout, status: 0x%x", status);
398                                         return(ERROR_FLASH_OPERATION_FAILED);
399                                 } else {
400                                         LOG_DEBUG("status: 0x%x", status);
401                                         return(ERROR_OK);
402                                 }
403                         }
404                 } else { /* no toggle: finished, OK */
405                         LOG_DEBUG("status: 0x%x", status);
406                         return(ERROR_OK);
407                 }
408
409                 oldstatus = status;
410                 alive_sleep(1);
411         } while (timeout-- > 0);
412
413         LOG_ERROR("timeout, status: 0x%x", status);
414
415         return(ERROR_FLASH_BUSY);
416 }
417
418 static int cfi_read_intel_pri_ext(struct flash_bank *bank)
419 {
420         int retval;
421         struct cfi_flash_bank *cfi_info = bank->driver_priv;
422         struct cfi_intel_pri_ext *pri_ext;
423
424         if (cfi_info->pri_ext)
425                 free(cfi_info->pri_ext);
426
427         pri_ext = malloc(sizeof(struct cfi_intel_pri_ext));
428         if (pri_ext == NULL)
429         {
430                 LOG_ERROR("Out of memory");
431                 return ERROR_FAIL;
432         }
433         cfi_info->pri_ext = pri_ext;
434
435         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0, &pri_ext->pri[0]);
436         if (retval != ERROR_OK)
437                 return retval;
438         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 1, &pri_ext->pri[1]);
439         if (retval != ERROR_OK)
440                 return retval;
441         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 2, &pri_ext->pri[2]);
442         if (retval != ERROR_OK)
443                 return retval;
444
445         if ((pri_ext->pri[0] != 'P') || (pri_ext->pri[1] != 'R') || (pri_ext->pri[2] != 'I'))
446         {
447                 if ((retval = cfi_reset(bank)) != ERROR_OK)
448                 {
449                         return retval;
450                 }
451                 LOG_ERROR("Could not read bank flash bank information");
452                 return ERROR_FLASH_BANK_INVALID;
453         }
454
455         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 3, &pri_ext->major_version);
456         if (retval != ERROR_OK)
457                 return retval;
458         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 4, &pri_ext->minor_version);
459         if (retval != ERROR_OK)
460                 return retval;
461
462         LOG_DEBUG("pri: '%c%c%c', version: %c.%c", pri_ext->pri[0], pri_ext->pri[1],
463                         pri_ext->pri[2], pri_ext->major_version, pri_ext->minor_version);
464
465         retval = cfi_query_u32(bank, 0, cfi_info->pri_addr + 5, &pri_ext->feature_support);
466         if (retval != ERROR_OK)
467                 return retval;
468         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 9, &pri_ext->suspend_cmd_support);
469         if (retval != ERROR_OK)
470                 return retval;
471         retval = cfi_query_u16(bank, 0, cfi_info->pri_addr + 0xa, &pri_ext->blk_status_reg_mask);
472         if (retval != ERROR_OK)
473                 return retval;
474
475         LOG_DEBUG("feature_support: 0x%" PRIx32 ", suspend_cmd_support: "
476                         "0x%x, blk_status_reg_mask: 0x%x",
477                         pri_ext->feature_support,
478                         pri_ext->suspend_cmd_support,
479                         pri_ext->blk_status_reg_mask);
480
481         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0xc, &pri_ext->vcc_optimal);
482         if (retval != ERROR_OK)
483                 return retval;
484         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0xd, &pri_ext->vpp_optimal);
485         if (retval != ERROR_OK)
486                 return retval;
487
488         LOG_DEBUG("Vcc opt: %x.%x, Vpp opt: %u.%x",
489                         (pri_ext->vcc_optimal & 0xf0) >> 4, pri_ext->vcc_optimal & 0x0f,
490                         (pri_ext->vpp_optimal & 0xf0) >> 4, pri_ext->vpp_optimal & 0x0f);
491
492         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0xe, &pri_ext->num_protection_fields);
493         if (retval != ERROR_OK)
494                 return retval;
495         if (pri_ext->num_protection_fields != 1)
496         {
497                 LOG_WARNING("expected one protection register field, but found %i",
498                                 pri_ext->num_protection_fields);
499         }
500
501         retval = cfi_query_u16(bank, 0, cfi_info->pri_addr + 0xf, &pri_ext->prot_reg_addr);
502         if (retval != ERROR_OK)
503                 return retval;
504         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0x11, &pri_ext->fact_prot_reg_size);
505         if (retval != ERROR_OK)
506                 return retval;
507         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0x12, &pri_ext->user_prot_reg_size);
508         if (retval != ERROR_OK)
509                 return retval;
510
511         LOG_DEBUG("protection_fields: %i, prot_reg_addr: 0x%x, "
512                         "factory pre-programmed: %i, user programmable: %i",
513                         pri_ext->num_protection_fields, pri_ext->prot_reg_addr,
514                         1 << pri_ext->fact_prot_reg_size, 1 << pri_ext->user_prot_reg_size);
515
516         return ERROR_OK;
517 }
518
519 static int cfi_read_spansion_pri_ext(struct flash_bank *bank)
520 {
521         int retval;
522         struct cfi_flash_bank *cfi_info = bank->driver_priv;
523         struct cfi_spansion_pri_ext *pri_ext;
524
525         if (cfi_info->pri_ext)
526                 free(cfi_info->pri_ext);
527
528         pri_ext = malloc(sizeof(struct cfi_spansion_pri_ext));
529         if (pri_ext == NULL)
530         {
531                 LOG_ERROR("Out of memory");
532                 return ERROR_FAIL;
533         }
534         cfi_info->pri_ext = pri_ext;
535
536         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0, &pri_ext->pri[0]);
537         if (retval != ERROR_OK)
538                 return retval;
539         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 1, &pri_ext->pri[1]);
540         if (retval != ERROR_OK)
541                 return retval;
542         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 2, &pri_ext->pri[2]);
543         if (retval != ERROR_OK)
544                 return retval;
545
546         if ((pri_ext->pri[0] != 'P') || (pri_ext->pri[1] != 'R') || (pri_ext->pri[2] != 'I'))
547         {
548                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
549                 {
550                         return retval;
551                 }
552                 LOG_ERROR("Could not read spansion bank information");
553                 return ERROR_FLASH_BANK_INVALID;
554         }
555
556         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 3, &pri_ext->major_version);
557         if (retval != ERROR_OK)
558                 return retval;
559         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 4, &pri_ext->minor_version);
560         if (retval != ERROR_OK)
561                 return retval;
562
563         LOG_DEBUG("pri: '%c%c%c', version: %c.%c", pri_ext->pri[0], pri_ext->pri[1],
564                         pri_ext->pri[2], pri_ext->major_version, pri_ext->minor_version);
565
566         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 5, &pri_ext->SiliconRevision);
567         if (retval != ERROR_OK)
568                 return retval;
569         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 6, &pri_ext->EraseSuspend);
570         if (retval != ERROR_OK)
571                 return retval;
572         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 7, &pri_ext->BlkProt);
573         if (retval != ERROR_OK)
574                 return retval;
575         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 8, &pri_ext->TmpBlkUnprotect);
576         if (retval != ERROR_OK)
577                 return retval;
578         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 9, &pri_ext->BlkProtUnprot);
579         if (retval != ERROR_OK)
580                 return retval;
581         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 10, &pri_ext->SimultaneousOps);
582         if (retval != ERROR_OK)
583                 return retval;
584         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 11, &pri_ext->BurstMode);
585         if (retval != ERROR_OK)
586                 return retval;
587         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 12, &pri_ext->PageMode);
588         if (retval != ERROR_OK)
589                 return retval;
590         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 13, &pri_ext->VppMin);
591         if (retval != ERROR_OK)
592                 return retval;
593         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 14, &pri_ext->VppMax);
594         if (retval != ERROR_OK)
595                 return retval;
596         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 15, &pri_ext->TopBottom);
597         if (retval != ERROR_OK)
598                 return retval;
599
600         LOG_DEBUG("Silicon Revision: 0x%x, Erase Suspend: 0x%x, Block protect: 0x%x",
601                         pri_ext->SiliconRevision, pri_ext->EraseSuspend, pri_ext->BlkProt);
602
603         LOG_DEBUG("Temporary Unprotect: 0x%x, Block Protect Scheme: 0x%x, "
604                         "Simultaneous Ops: 0x%x", pri_ext->TmpBlkUnprotect,
605                         pri_ext->BlkProtUnprot, pri_ext->SimultaneousOps);
606
607         LOG_DEBUG("Burst Mode: 0x%x, Page Mode: 0x%x, ", pri_ext->BurstMode, pri_ext->PageMode);
608
609
610         LOG_DEBUG("Vpp min: %u.%x, Vpp max: %u.%x",
611                   (pri_ext->VppMin & 0xf0) >> 4, pri_ext->VppMin & 0x0f,
612                   (pri_ext->VppMax & 0xf0) >> 4, pri_ext->VppMax & 0x0f);
613
614         LOG_DEBUG("WP# protection 0x%x", pri_ext->TopBottom);
615
616         /* default values for implementation specific workarounds */
617         pri_ext->_unlock1 = cfi_unlock_addresses[CFI_UNLOCK_555_2AA].unlock1;
618         pri_ext->_unlock2 = cfi_unlock_addresses[CFI_UNLOCK_555_2AA].unlock2;
619         pri_ext->_reversed_geometry = 0;
620
621         return ERROR_OK;
622 }
623
624 static int cfi_read_atmel_pri_ext(struct flash_bank *bank)
625 {
626         int retval;
627         struct cfi_atmel_pri_ext atmel_pri_ext;
628         struct cfi_flash_bank *cfi_info = bank->driver_priv;
629         struct cfi_spansion_pri_ext *pri_ext;
630
631         if (cfi_info->pri_ext)
632                 free(cfi_info->pri_ext);
633
634         pri_ext = malloc(sizeof(struct cfi_spansion_pri_ext));
635         if (pri_ext == NULL)
636         {
637                 LOG_ERROR("Out of memory");
638                 return ERROR_FAIL;
639         }
640
641         /* ATMEL devices use the same CFI primary command set (0x2) as AMD/Spansion,
642          * but a different primary extended query table.
643          * We read the atmel table, and prepare a valid AMD/Spansion query table.
644          */
645
646         memset(pri_ext, 0, sizeof(struct cfi_spansion_pri_ext));
647
648         cfi_info->pri_ext = pri_ext;
649
650         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0, &atmel_pri_ext.pri[0]);
651         if (retval != ERROR_OK)
652                 return retval;
653         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 1, &atmel_pri_ext.pri[1]);
654         if (retval != ERROR_OK)
655                 return retval;
656         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 2, &atmel_pri_ext.pri[2]);
657         if (retval != ERROR_OK)
658                 return retval;
659
660         if ((atmel_pri_ext.pri[0] != 'P') || (atmel_pri_ext.pri[1] != 'R')
661                         || (atmel_pri_ext.pri[2] != 'I'))
662         {
663                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
664                 {
665                         return retval;
666                 }
667                 LOG_ERROR("Could not read atmel bank information");
668                 return ERROR_FLASH_BANK_INVALID;
669         }
670
671         pri_ext->pri[0] = atmel_pri_ext.pri[0];
672         pri_ext->pri[1] = atmel_pri_ext.pri[1];
673         pri_ext->pri[2] = atmel_pri_ext.pri[2];
674
675         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 3, &atmel_pri_ext.major_version);
676         if (retval != ERROR_OK)
677                 return retval;
678         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 4, &atmel_pri_ext.minor_version);
679         if (retval != ERROR_OK)
680                 return retval;
681
682         LOG_DEBUG("pri: '%c%c%c', version: %c.%c", atmel_pri_ext.pri[0],
683                         atmel_pri_ext.pri[1], atmel_pri_ext.pri[2],
684                         atmel_pri_ext.major_version, atmel_pri_ext.minor_version);
685
686         pri_ext->major_version = atmel_pri_ext.major_version;
687         pri_ext->minor_version = atmel_pri_ext.minor_version;
688
689         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 5, &atmel_pri_ext.features);
690         if (retval != ERROR_OK)
691                 return retval;
692         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 6, &atmel_pri_ext.bottom_boot);
693         if (retval != ERROR_OK)
694                 return retval;
695         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 7, &atmel_pri_ext.burst_mode);
696         if (retval != ERROR_OK)
697                 return retval;
698         retval = cfi_query_u8(bank, 0, cfi_info->pri_addr + 8, &atmel_pri_ext.page_mode);
699         if (retval != ERROR_OK)
700                 return retval;
701
702         LOG_DEBUG("features: 0x%2.2x, bottom_boot: 0x%2.2x, burst_mode: 0x%2.2x, page_mode: 0x%2.2x",
703                 atmel_pri_ext.features, atmel_pri_ext.bottom_boot,
704                 atmel_pri_ext.burst_mode, atmel_pri_ext.page_mode);
705
706         if (atmel_pri_ext.features & 0x02)
707                 pri_ext->EraseSuspend = 2;
708
709         /* some chips got it backwards... */
710         if (cfi_info->device_id == AT49BV6416 ||
711             cfi_info->device_id == AT49BV6416T) {
712                 if (atmel_pri_ext.bottom_boot)
713                         pri_ext->TopBottom = 3;
714                 else
715                         pri_ext->TopBottom = 2;
716         } else {
717                 if (atmel_pri_ext.bottom_boot)
718                         pri_ext->TopBottom = 2;
719                 else
720                         pri_ext->TopBottom = 3;
721         }
722
723         pri_ext->_unlock1 = cfi_unlock_addresses[CFI_UNLOCK_555_2AA].unlock1;
724         pri_ext->_unlock2 = cfi_unlock_addresses[CFI_UNLOCK_555_2AA].unlock2;
725
726         return ERROR_OK;
727 }
728
729 static int cfi_read_0002_pri_ext(struct flash_bank *bank)
730 {
731         struct cfi_flash_bank *cfi_info = bank->driver_priv;
732
733         if (cfi_info->manufacturer == CFI_MFR_ATMEL)
734         {
735                 return cfi_read_atmel_pri_ext(bank);
736         }
737         else
738         {
739                 return cfi_read_spansion_pri_ext(bank);
740         }
741 }
742
743 static int cfi_spansion_info(struct flash_bank *bank, char *buf, int buf_size)
744 {
745         int printed;
746         struct cfi_flash_bank *cfi_info = bank->driver_priv;
747         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
748
749         printed = snprintf(buf, buf_size, "\nSpansion primary algorithm extend information:\n");
750         buf += printed;
751         buf_size -= printed;
752
753         printed = snprintf(buf, buf_size, "pri: '%c%c%c', version: %c.%c\n", pri_ext->pri[0],
754                         pri_ext->pri[1], pri_ext->pri[2],
755                         pri_ext->major_version, pri_ext->minor_version);
756         buf += printed;
757         buf_size -= printed;
758
759         printed = snprintf(buf, buf_size, "Silicon Rev.: 0x%x, Address Sensitive unlock: 0x%x\n",
760                         (pri_ext->SiliconRevision) >> 2,
761                         (pri_ext->SiliconRevision) & 0x03);
762         buf += printed;
763         buf_size -= printed;
764
765         printed = snprintf(buf, buf_size, "Erase Suspend: 0x%x, Sector Protect: 0x%x\n",
766                         pri_ext->EraseSuspend,
767                         pri_ext->BlkProt);
768         buf += printed;
769         buf_size -= printed;
770
771         snprintf(buf, buf_size, "VppMin: %u.%x, VppMax: %u.%x\n",
772                         (pri_ext->VppMin & 0xf0) >> 4, pri_ext->VppMin & 0x0f,
773                         (pri_ext->VppMax & 0xf0) >> 4, pri_ext->VppMax & 0x0f);
774
775         return ERROR_OK;
776 }
777
778 static int cfi_intel_info(struct flash_bank *bank, char *buf, int buf_size)
779 {
780         int printed;
781         struct cfi_flash_bank *cfi_info = bank->driver_priv;
782         struct cfi_intel_pri_ext *pri_ext = cfi_info->pri_ext;
783
784         printed = snprintf(buf, buf_size, "\nintel primary algorithm extend information:\n");
785         buf += printed;
786         buf_size -= printed;
787
788         printed = snprintf(buf, buf_size, "pri: '%c%c%c', version: %c.%c\n", pri_ext->pri[0],
789                         pri_ext->pri[1], pri_ext->pri[2], pri_ext->major_version, pri_ext->minor_version);
790         buf += printed;
791         buf_size -= printed;
792
793         printed = snprintf(buf, buf_size, "feature_support: 0x%" PRIx32 ", "
794                         "suspend_cmd_support: 0x%x, blk_status_reg_mask: 0x%x\n",
795                         pri_ext->feature_support, pri_ext->suspend_cmd_support, pri_ext->blk_status_reg_mask);
796         buf += printed;
797         buf_size -= printed;
798
799         printed = snprintf(buf, buf_size, "Vcc opt: %x.%x, Vpp opt: %u.%x\n",
800                         (pri_ext->vcc_optimal & 0xf0) >> 4, pri_ext->vcc_optimal & 0x0f,
801                         (pri_ext->vpp_optimal & 0xf0) >> 4, pri_ext->vpp_optimal & 0x0f);
802         buf += printed;
803         buf_size -= printed;
804
805         snprintf(buf, buf_size, "protection_fields: %i, prot_reg_addr: 0x%x, "
806                         "factory pre-programmed: %i, user programmable: %i\n",
807                         pri_ext->num_protection_fields, pri_ext->prot_reg_addr,
808                         1 << pri_ext->fact_prot_reg_size, 1 << pri_ext->user_prot_reg_size);
809
810         return ERROR_OK;
811 }
812
813 /* flash_bank cfi <base> <size> <chip_width> <bus_width> <target#> [options]
814  */
815 FLASH_BANK_COMMAND_HANDLER(cfi_flash_bank_command)
816 {
817         struct cfi_flash_bank *cfi_info;
818
819         if (CMD_ARGC < 6)
820         {
821                 return ERROR_COMMAND_SYNTAX_ERROR;
822         }
823
824         /* both widths must:
825          * - not exceed max value;
826          * - not be null;
827          * - be equal to a power of 2.
828          * bus must be wide enought to hold one chip */
829         if ((bank->chip_width > CFI_MAX_CHIP_WIDTH)
830                         || (bank->bus_width > CFI_MAX_BUS_WIDTH)
831                         || (bank->chip_width == 0)
832                         || (bank->bus_width == 0)
833                         || (bank->chip_width & (bank->chip_width - 1))
834                         || (bank->bus_width & (bank->bus_width - 1))
835                         || (bank->chip_width > bank->bus_width))
836         {
837                 LOG_ERROR("chip and bus width have to specified in bytes");
838                 return ERROR_FLASH_BANK_INVALID;
839         }
840
841         cfi_info = malloc(sizeof(struct cfi_flash_bank));
842         cfi_info->probed = 0;
843         cfi_info->erase_region_info = NULL;
844         cfi_info->pri_ext = NULL;
845         bank->driver_priv = cfi_info;
846
847         cfi_info->write_algorithm = NULL;
848
849         cfi_info->x16_as_x8 = 0;
850         cfi_info->jedec_probe = 0;
851         cfi_info->not_cfi = 0;
852
853         for (unsigned i = 6; i < CMD_ARGC; i++)
854         {
855                 if (strcmp(CMD_ARGV[i], "x16_as_x8") == 0)
856                 {
857                         cfi_info->x16_as_x8 = 1;
858                 }
859                 else if (strcmp(CMD_ARGV[i], "jedec_probe") == 0)
860                 {
861                         cfi_info->jedec_probe = 1;
862                 }
863         }
864
865         cfi_info->write_algorithm = NULL;
866
867         /* bank wasn't probed yet */
868         cfi_info->qry[0] = 0xff;
869
870         return ERROR_OK;
871 }
872
873 static int cfi_intel_erase(struct flash_bank *bank, int first, int last)
874 {
875         int retval;
876         struct cfi_flash_bank *cfi_info = bank->driver_priv;
877         int i;
878
879         cfi_intel_clear_status_register(bank);
880
881         for (i = first; i <= last; i++)
882         {
883                 if ((retval = cfi_send_command(bank, 0x20, flash_address(bank, i, 0x0))) != ERROR_OK)
884                 {
885                         return retval;
886                 }
887
888                 if ((retval = cfi_send_command(bank, 0xd0, flash_address(bank, i, 0x0))) != ERROR_OK)
889                 {
890                         return retval;
891                 }
892
893                 uint8_t status;
894                 retval = cfi_intel_wait_status_busy(bank, cfi_info->block_erase_timeout, &status);
895                 if (retval != ERROR_OK)
896                         return retval;
897
898                 if (status == 0x80)
899                         bank->sectors[i].is_erased = 1;
900                 else
901                 {
902                         if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
903                         {
904                                 return retval;
905                         }
906
907                         LOG_ERROR("couldn't erase block %i of flash bank at base 0x%" PRIx32 , i, bank->base);
908                         return ERROR_FLASH_OPERATION_FAILED;
909                 }
910         }
911
912         return cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0));
913 }
914
915 static int cfi_spansion_erase(struct flash_bank *bank, int first, int last)
916 {
917         int retval;
918         struct cfi_flash_bank *cfi_info = bank->driver_priv;
919         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
920         int i;
921
922         for (i = first; i <= last; i++)
923         {
924                 if ((retval = cfi_send_command(bank, 0xaa,
925                                 flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
926                 {
927                         return retval;
928                 }
929
930                 if ((retval = cfi_send_command(bank, 0x55,
931                                 flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
932                 {
933                         return retval;
934                 }
935
936                 if ((retval = cfi_send_command(bank, 0x80,
937                                 flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
938                 {
939                         return retval;
940                 }
941
942                 if ((retval = cfi_send_command(bank, 0xaa,
943                                 flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
944                 {
945                         return retval;
946                 }
947
948                 if ((retval = cfi_send_command(bank, 0x55,
949                                 flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
950                 {
951                         return retval;
952                 }
953
954                 if ((retval = cfi_send_command(bank, 0x30,
955                                 flash_address(bank, i, 0x0))) != ERROR_OK)
956                 {
957                         return retval;
958                 }
959
960                 if (cfi_spansion_wait_status_busy(bank, cfi_info->block_erase_timeout) == ERROR_OK)
961                 {
962                         bank->sectors[i].is_erased = 1;
963                 }
964                 else
965                 {
966                         if ((retval = cfi_send_command(bank, 0xf0,
967                                         flash_address(bank, 0, 0x0))) != ERROR_OK)
968                         {
969                                 return retval;
970                         }
971
972                         LOG_ERROR("couldn't erase block %i of flash bank at base 0x%"
973                                         PRIx32, i, bank->base);
974                         return ERROR_FLASH_OPERATION_FAILED;
975                 }
976         }
977
978         return  cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0));
979 }
980
981 static int cfi_erase(struct flash_bank *bank, int first, int last)
982 {
983         struct cfi_flash_bank *cfi_info = bank->driver_priv;
984
985         if (bank->target->state != TARGET_HALTED)
986         {
987                 LOG_ERROR("Target not halted");
988                 return ERROR_TARGET_NOT_HALTED;
989         }
990
991         if ((first < 0) || (last < first) || (last >= bank->num_sectors))
992         {
993                 return ERROR_FLASH_SECTOR_INVALID;
994         }
995
996         if (cfi_info->qry[0] != 'Q')
997                 return ERROR_FLASH_BANK_NOT_PROBED;
998
999         switch (cfi_info->pri_id)
1000         {
1001                 case 1:
1002                 case 3:
1003                         return cfi_intel_erase(bank, first, last);
1004                         break;
1005                 case 2:
1006                         return cfi_spansion_erase(bank, first, last);
1007                         break;
1008                 default:
1009                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
1010                         break;
1011         }
1012
1013         return ERROR_OK;
1014 }
1015
1016 static int cfi_intel_protect(struct flash_bank *bank, int set, int first, int last)
1017 {
1018         int retval;
1019         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1020         struct cfi_intel_pri_ext *pri_ext = cfi_info->pri_ext;
1021         int retry = 0;
1022         int i;
1023
1024         /* if the device supports neither legacy lock/unlock (bit 3) nor
1025          * instant individual block locking (bit 5).
1026          */
1027         if (!(pri_ext->feature_support & 0x28))
1028         {
1029                 LOG_ERROR("lock/unlock not supported on flash");
1030                 return ERROR_FLASH_OPERATION_FAILED;
1031         }
1032
1033         cfi_intel_clear_status_register(bank);
1034
1035         for (i = first; i <= last; i++)
1036         {
1037                 if ((retval = cfi_send_command(bank, 0x60, flash_address(bank, i, 0x0))) != ERROR_OK)
1038                 {
1039                         return retval;
1040                 }
1041                 if (set)
1042                 {
1043                         if ((retval = cfi_send_command(bank, 0x01, flash_address(bank, i, 0x0))) != ERROR_OK)
1044                         {
1045                                 return retval;
1046                         }
1047                         bank->sectors[i].is_protected = 1;
1048                 }
1049                 else
1050                 {
1051                         if ((retval = cfi_send_command(bank, 0xd0, flash_address(bank, i, 0x0))) != ERROR_OK)
1052                         {
1053                                 return retval;
1054                         }
1055                         bank->sectors[i].is_protected = 0;
1056                 }
1057
1058                 /* instant individual block locking doesn't require reading of the status register */
1059                 if (!(pri_ext->feature_support & 0x20))
1060                 {
1061                         /* Clear lock bits operation may take up to 1.4s */
1062                         uint8_t status;
1063                         retval = cfi_intel_wait_status_busy(bank, 1400, &status);
1064                         if (retval != ERROR_OK)
1065                                 return retval;
1066                 }
1067                 else
1068                 {
1069                         uint8_t block_status;
1070                         /* read block lock bit, to verify status */
1071                         if ((retval = cfi_send_command(bank, 0x90, flash_address(bank, 0, 0x55))) != ERROR_OK)
1072                         {
1073                                 return retval;
1074                         }
1075                         retval = cfi_get_u8(bank, i, 0x2, &block_status);
1076                         if (retval != ERROR_OK)
1077                                 return retval;
1078
1079                         if ((block_status & 0x1) != set)
1080                         {
1081                                 LOG_ERROR("couldn't change block lock status (set = %i, block_status = 0x%2.2x)",
1082                                                 set, block_status);
1083                                 if ((retval = cfi_send_command(bank, 0x70,
1084                                                 flash_address(bank, 0, 0x55))) != ERROR_OK)
1085                                 {
1086                                         return retval;
1087                                 }
1088                                 uint8_t status;
1089                                 retval = cfi_intel_wait_status_busy(bank, 10, &status);
1090                                 if (retval != ERROR_OK)
1091                                         return retval;
1092
1093                                 if (retry > 10)
1094                                         return ERROR_FLASH_OPERATION_FAILED;
1095                                 else
1096                                 {
1097                                         i--;
1098                                         retry++;
1099                                 }
1100                         }
1101                 }
1102         }
1103
1104         /* if the device doesn't support individual block lock bits set/clear,
1105          * all blocks have been unlocked in parallel, so we set those that should be protected
1106          */
1107         if ((!set) && (!(pri_ext->feature_support & 0x20)))
1108         {
1109                 /* FIX!!! this code path is broken!!!
1110                  *
1111                  * The correct approach is:
1112                  *
1113                  * 1. read out current protection status
1114                  *
1115                  * 2. override read out protection status w/unprotected.
1116                  *
1117                  * 3. re-protect what should be protected.
1118                  *
1119                  */
1120                 for (i = 0; i < bank->num_sectors; i++)
1121                 {
1122                         if (bank->sectors[i].is_protected == 1)
1123                         {
1124                                 cfi_intel_clear_status_register(bank);
1125
1126                                 if ((retval = cfi_send_command(bank, 0x60,
1127                                                 flash_address(bank, i, 0x0))) != ERROR_OK)
1128                                 {
1129                                         return retval;
1130                                 }
1131
1132                                 if ((retval = cfi_send_command(bank, 0x01,
1133                                                 flash_address(bank, i, 0x0))) != ERROR_OK)
1134                                 {
1135                                         return retval;
1136                                 }
1137
1138                                 uint8_t status;
1139                                 retval = cfi_intel_wait_status_busy(bank, 100, &status);
1140                                 if (retval != ERROR_OK)
1141                                         return retval;
1142                         }
1143                 }
1144         }
1145
1146         return cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0));
1147 }
1148
1149 static int cfi_protect(struct flash_bank *bank, int set, int first, int last)
1150 {
1151         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1152
1153         if (bank->target->state != TARGET_HALTED)
1154         {
1155                 LOG_ERROR("Target not halted");
1156                 return ERROR_TARGET_NOT_HALTED;
1157         }
1158
1159         if ((first < 0) || (last < first) || (last >= bank->num_sectors))
1160         {
1161                 LOG_ERROR("Invalid sector range");
1162                 return ERROR_FLASH_SECTOR_INVALID;
1163         }
1164
1165         if (cfi_info->qry[0] != 'Q')
1166                 return ERROR_FLASH_BANK_NOT_PROBED;
1167
1168         switch (cfi_info->pri_id)
1169         {
1170                 case 1:
1171                 case 3:
1172                         return cfi_intel_protect(bank, set, first, last);
1173                         break;
1174                 default:
1175                         LOG_WARNING("protect: cfi primary command set %i unsupported", cfi_info->pri_id);
1176                         return ERROR_OK;
1177         }
1178 }
1179
1180 /* Convert code image to target endian */
1181 /* FIXME create general block conversion fcts in target.c?) */
1182 static void cfi_fix_code_endian(struct target *target, uint8_t *dest,
1183                 const uint32_t *src, uint32_t count)
1184 {
1185         uint32_t i;
1186         for (i = 0; i< count; i++)
1187         {
1188                 target_buffer_set_u32(target, dest, *src);
1189                 dest += 4;
1190                 src++;
1191         }
1192 }
1193
1194 static uint32_t cfi_command_val(struct flash_bank *bank, uint8_t cmd)
1195 {
1196         struct target *target = bank->target;
1197
1198         uint8_t buf[CFI_MAX_BUS_WIDTH];
1199         cfi_command(bank, cmd, buf);
1200         switch (bank->bus_width)
1201         {
1202         case 1 :
1203                 return buf[0];
1204                 break;
1205         case 2 :
1206                 return target_buffer_get_u16(target, buf);
1207                 break;
1208         case 4 :
1209                 return target_buffer_get_u32(target, buf);
1210                 break;
1211         default :
1212                 LOG_ERROR("Unsupported bank buswidth %d, can't do block memory writes", bank->bus_width);
1213                 return 0;
1214         }
1215 }
1216
1217 static int cfi_intel_write_block(struct flash_bank *bank, uint8_t *buffer,
1218                 uint32_t address, uint32_t count)
1219 {
1220         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1221         struct target *target = bank->target;
1222         struct reg_param reg_params[7];
1223         struct arm_algorithm armv4_5_info;
1224         struct working_area *source = NULL;
1225         uint32_t buffer_size = 32768;
1226         uint32_t write_command_val, busy_pattern_val, error_pattern_val;
1227
1228         /* algorithm register usage:
1229          * r0: source address (in RAM)
1230          * r1: target address (in Flash)
1231          * r2: count
1232          * r3: flash write command
1233          * r4: status byte (returned to host)
1234          * r5: busy test pattern
1235          * r6: error test pattern
1236          */
1237
1238         /* see contib/loaders/flash/armv4_5_cfi_intel_32.s for src */
1239         static const uint32_t word_32_code[] = {
1240                 0xe4904004,   /* loop:  ldr r4, [r0], #4 */
1241                 0xe5813000,   /*                str r3, [r1] */
1242                 0xe5814000,   /*                str r4, [r1] */
1243                 0xe5914000,   /* busy:  ldr r4, [r1] */
1244                 0xe0047005,   /*                and r7, r4, r5 */
1245                 0xe1570005,   /*                cmp r7, r5 */
1246                 0x1afffffb,   /*                bne busy */
1247                 0xe1140006,   /*                tst r4, r6 */
1248                 0x1a000003,   /*                bne done */
1249                 0xe2522001,   /*                subs r2, r2, #1 */
1250                 0x0a000001,   /*                beq done */
1251                 0xe2811004,   /*                add r1, r1 #4 */
1252                 0xeafffff2,   /*                b loop */
1253                 0xeafffffe    /* done:  b -2 */
1254         };
1255
1256         /* see contib/loaders/flash/armv4_5_cfi_intel_16.s for src */
1257         static const uint32_t word_16_code[] = {
1258                 0xe0d040b2,   /* loop:  ldrh r4, [r0], #2 */
1259                 0xe1c130b0,   /*                strh r3, [r1] */
1260                 0xe1c140b0,   /*                strh r4, [r1] */
1261                 0xe1d140b0,   /* busy   ldrh r4, [r1] */
1262                 0xe0047005,   /*                and r7, r4, r5 */
1263                 0xe1570005,   /*                cmp r7, r5 */
1264                 0x1afffffb,   /*                bne busy */
1265                 0xe1140006,   /*                tst r4, r6 */
1266                 0x1a000003,   /*                bne done */
1267                 0xe2522001,   /*                subs r2, r2, #1 */
1268                 0x0a000001,   /*                beq done */
1269                 0xe2811002,   /*                add r1, r1 #2 */
1270                 0xeafffff2,   /*                b loop */
1271                 0xeafffffe    /* done:  b -2 */
1272         };
1273
1274         /* see contib/loaders/flash/armv4_5_cfi_intel_8.s for src */
1275         static const uint32_t word_8_code[] = {
1276                 0xe4d04001,   /* loop:  ldrb r4, [r0], #1 */
1277                 0xe5c13000,   /*                strb r3, [r1] */
1278                 0xe5c14000,   /*                strb r4, [r1] */
1279                 0xe5d14000,   /* busy   ldrb r4, [r1] */
1280                 0xe0047005,   /*                and r7, r4, r5 */
1281                 0xe1570005,   /*                cmp r7, r5 */
1282                 0x1afffffb,   /*                bne busy */
1283                 0xe1140006,   /*                tst r4, r6 */
1284                 0x1a000003,   /*                bne done */
1285                 0xe2522001,   /*                subs r2, r2, #1 */
1286                 0x0a000001,   /*                beq done */
1287                 0xe2811001,   /*                add r1, r1 #1 */
1288                 0xeafffff2,   /*                b loop */
1289                 0xeafffffe    /* done:  b -2 */
1290         };
1291         uint8_t target_code[4*CFI_MAX_INTEL_CODESIZE];
1292         const uint32_t *target_code_src;
1293         uint32_t target_code_size;
1294         int retval = ERROR_OK;
1295
1296         /*  todo:  if ( (!is_armv7m(target_to_armv7m(target)) && (!is_arm(target_to_arm(target)) ) */
1297         if (strncmp(target_type_name(target),"mips_m4k",8) == 0)
1298         {
1299                 LOG_ERROR("Your target has no flash block write support yet.");
1300                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1301         }
1302
1303         cfi_intel_clear_status_register(bank);
1304
1305         armv4_5_info.common_magic = ARM_COMMON_MAGIC;
1306         armv4_5_info.core_mode = ARM_MODE_SVC;
1307         armv4_5_info.core_state = ARM_STATE_ARM;
1308
1309         /* If we are setting up the write_algorith, we need target_code_src */
1310         /* if not we only need target_code_size. */
1311
1312         /* However, we don't want to create multiple code paths, so we */
1313         /* do the unecessary evaluation of target_code_src, which the */
1314         /* compiler will probably nicely optimize away if not needed */
1315
1316         /* prepare algorithm code for target endian */
1317         switch (bank->bus_width)
1318         {
1319         case 1 :
1320                 target_code_src = word_8_code;
1321                 target_code_size = sizeof(word_8_code);
1322                 break;
1323         case 2 :
1324                 target_code_src = word_16_code;
1325                 target_code_size = sizeof(word_16_code);
1326                 break;
1327         case 4 :
1328                 target_code_src = word_32_code;
1329                 target_code_size = sizeof(word_32_code);
1330                 break;
1331         default:
1332                 LOG_ERROR("Unsupported bank buswidth %d, can't do block memory writes", bank->bus_width);
1333                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1334         }
1335
1336         /* flash write code */
1337         if (!cfi_info->write_algorithm)
1338         {
1339                 if (target_code_size > sizeof(target_code))
1340                 {
1341                         LOG_WARNING("Internal error - target code buffer to small. "
1342                                         "Increase CFI_MAX_INTEL_CODESIZE and recompile.");
1343                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1344                 }
1345                 cfi_fix_code_endian(target, target_code, target_code_src, target_code_size / 4);
1346
1347                 /* Get memory for block write handler */
1348                 retval = target_alloc_working_area(target, target_code_size, &cfi_info->write_algorithm);
1349                 if (retval != ERROR_OK)
1350                 {
1351                         LOG_WARNING("No working area available, can't do block memory writes");
1352                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1353                 };
1354
1355                 /* write algorithm code to working area */
1356                 retval = target_write_buffer(target, cfi_info->write_algorithm->address,
1357                                 target_code_size, target_code);
1358                 if (retval != ERROR_OK)
1359                 {
1360                         LOG_ERROR("Unable to write block write code to target");
1361                         goto cleanup;
1362                 }
1363         }
1364
1365         /* Get a workspace buffer for the data to flash starting with 32k size.
1366            Half size until buffer would be smaller 256 Bytem then fail back */
1367         /* FIXME Why 256 bytes, why not 32 bytes (smallest flash write page */
1368         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK)
1369         {
1370                 buffer_size /= 2;
1371                 if (buffer_size <= 256)
1372                 {
1373                         LOG_WARNING("no large enough working area available, can't do block memory writes");
1374                         retval = ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1375                         goto cleanup;
1376                 }
1377         };
1378
1379         /* setup algo registers */
1380         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
1381         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
1382         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
1383         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
1384         init_reg_param(&reg_params[4], "r4", 32, PARAM_IN);
1385         init_reg_param(&reg_params[5], "r5", 32, PARAM_OUT);
1386         init_reg_param(&reg_params[6], "r6", 32, PARAM_OUT);
1387
1388         /* prepare command and status register patterns */
1389         write_command_val = cfi_command_val(bank, 0x40);
1390         busy_pattern_val  = cfi_command_val(bank, 0x80);
1391         error_pattern_val = cfi_command_val(bank, 0x7e);
1392
1393         LOG_DEBUG("Using target buffer at 0x%08" PRIx32 " and of size 0x%04" PRIx32,
1394                         source->address, buffer_size);
1395
1396         /* Programming main loop */
1397         while (count > 0)
1398         {
1399                 uint32_t thisrun_count = (count > buffer_size) ? buffer_size : count;
1400                 uint32_t wsm_error;
1401
1402                 if ((retval = target_write_buffer(target, source->address,
1403                                 thisrun_count, buffer)) != ERROR_OK)
1404                 {
1405                         goto cleanup;
1406                 }
1407
1408                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
1409                 buf_set_u32(reg_params[1].value, 0, 32, address);
1410                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count / bank->bus_width);
1411
1412                 buf_set_u32(reg_params[3].value, 0, 32, write_command_val);
1413                 buf_set_u32(reg_params[5].value, 0, 32, busy_pattern_val);
1414                 buf_set_u32(reg_params[6].value, 0, 32, error_pattern_val);
1415
1416                 LOG_DEBUG("Write 0x%04" PRIx32 " bytes to flash at 0x%08" PRIx32 , thisrun_count, address);
1417
1418                 /* Execute algorithm, assume breakpoint for last instruction */
1419                 retval = target_run_algorithm(target, 0, NULL, 7, reg_params,
1420                         cfi_info->write_algorithm->address,
1421                         cfi_info->write_algorithm->address + target_code_size - sizeof(uint32_t),
1422                         10000, /* 10s should be enough for max. 32k of data */
1423                         &armv4_5_info);
1424
1425                 /* On failure try a fall back to direct word writes */
1426                 if (retval != ERROR_OK)
1427                 {
1428                         cfi_intel_clear_status_register(bank);
1429                         LOG_ERROR("Execution of flash algorythm failed. Can't fall back. Please report.");
1430                         retval = ERROR_FLASH_OPERATION_FAILED;
1431                         /* retval = ERROR_TARGET_RESOURCE_NOT_AVAILABLE; */
1432                         /* FIXME To allow fall back or recovery, we must save the actual status
1433                          * somewhere, so that a higher level code can start recovery. */
1434                         goto cleanup;
1435                 }
1436
1437                 /* Check return value from algo code */
1438                 wsm_error = buf_get_u32(reg_params[4].value, 0, 32) & error_pattern_val;
1439                 if (wsm_error)
1440                 {
1441                         /* read status register (outputs debug inforation) */
1442                         uint8_t status;
1443                         cfi_intel_wait_status_busy(bank, 100, &status);
1444                         cfi_intel_clear_status_register(bank);
1445                         retval = ERROR_FLASH_OPERATION_FAILED;
1446                         goto cleanup;
1447                 }
1448
1449                 buffer += thisrun_count;
1450                 address += thisrun_count;
1451                 count -= thisrun_count;
1452
1453                 keep_alive();
1454         }
1455
1456         /* free up resources */
1457 cleanup:
1458         if (source)
1459                 target_free_working_area(target, source);
1460
1461         if (cfi_info->write_algorithm)
1462         {
1463                 target_free_working_area(target, cfi_info->write_algorithm);
1464                 cfi_info->write_algorithm = NULL;
1465         }
1466
1467         destroy_reg_param(&reg_params[0]);
1468         destroy_reg_param(&reg_params[1]);
1469         destroy_reg_param(&reg_params[2]);
1470         destroy_reg_param(&reg_params[3]);
1471         destroy_reg_param(&reg_params[4]);
1472         destroy_reg_param(&reg_params[5]);
1473         destroy_reg_param(&reg_params[6]);
1474
1475         return retval;
1476 }
1477
1478 static int cfi_spansion_write_block_mips(struct flash_bank *bank, uint8_t *buffer,
1479                 uint32_t address, uint32_t count)
1480 {
1481         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1482         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
1483         struct target *target = bank->target;
1484         struct reg_param reg_params[10];
1485         struct mips32_algorithm mips32_info;
1486         struct working_area *source;
1487         uint32_t buffer_size = 32768;
1488         uint32_t status;
1489         int retval = ERROR_OK;
1490
1491         /* input parameters - */
1492         /*      4  A0 = source address */
1493         /*      5  A1 = destination address */
1494         /*      6  A2 = number of writes */
1495         /*      7  A3 = flash write command */
1496         /*      8  T0 = constant to mask DQ7 bits (also used for Dq5 with shift) */
1497         /* output parameters - */
1498         /*      9  T1 = 0x80 ok 0x00 bad */
1499         /* temp registers - */
1500         /*      10 T2 = value read from flash to test status */
1501         /*      11 T3 = holding register */
1502         /* unlock registers - */
1503         /*  12 T4 = unlock1_addr */
1504         /*  13 T5 = unlock1_cmd */
1505         /*  14 T6 = unlock2_addr */
1506         /*  15 T7 = unlock2_cmd */
1507
1508         static const uint32_t mips_word_16_code[] = {
1509                                                                                                                         /* start:       */
1510                 MIPS32_LHU(9,0,4),              /* lhu $t1, ($a0)               ; out = &saddr                          */
1511                 MIPS32_ADDI(4,4,2),             /* addi $a0, $a0, 2             ; saddr += 2                            */
1512                 MIPS32_SH(13,0,12),             /* sh $t5, ($t4)                ; *fl_unl_addr1 = fl_unl_cmd1           */
1513                 MIPS32_SH(15,0,14),             /* sh $t7, ($t6)                ; *fl_unl_addr2 = fl_unl_cmd2           */
1514                 MIPS32_SH(7,0,12),              /* sh $a3, ($t4)                ; *fl_unl_addr1 = fl_write_cmd          */
1515                 MIPS32_SH(9,0,5),               /* sh $t1, ($a1)                ; *daddr = out                          */
1516                 MIPS32_NOP,                     /* nop                                                                  */
1517                                                                                                                         /* busy:        */
1518                 MIPS32_LHU(10,0,5),             /* lhu $t2, ($a1)               ; temp1 = *daddr                        */
1519                 MIPS32_XOR(11,9,10),            /* xor $t3, $a0, $t2            ; temp2 = out ^ temp1;                  */
1520                 MIPS32_AND(11,8,11),            /* and $t3, $t0, $t3            ; temp2 = temp2 & DQ7mask               */
1521                 MIPS32_BNE(11,8, 13),           /* bne $t3, $t0, cont           ; if (temp2 != DQ7mask) goto cont       */
1522                 MIPS32_NOP,                     /* nop                                                                  */
1523
1524                 MIPS32_SRL(10,8,2),             /* srl $t2,$t0,2                ; temp1 = DQ7mask >> 2                  */
1525                 MIPS32_AND(11,10,11),           /* and $t3, $t2, $t3            ; temp2 = temp2 & temp1                 */
1526                 MIPS32_BNE(11,10, NEG16(8)),    /* bne $t3, $t2, busy           ; if (temp2 != temp1) goto busy         */
1527                 MIPS32_NOP,                     /* nop                                                                  */
1528
1529                 MIPS32_LHU(10,0,5),             /* lhu $t2, ($a1)               ; temp1 = *daddr                        */
1530                 MIPS32_XOR(11,9,10),            /* xor $t3, $a0, $t2            ; temp2 = out ^ temp1;                  */
1531                 MIPS32_AND(11,8,11),            /* and $t3, $t0, $t3            ; temp2 = temp2 & DQ7mask               */
1532                 MIPS32_BNE(11,8, 4),            /* bne $t3, $t0, cont           ; if (temp2 != DQ7mask) goto cont       */
1533                 MIPS32_NOP,                     /* nop                                                                  */
1534
1535                 MIPS32_XOR(9,9,9),              /* xor $t1, $t1, $t1            ; out = 0                               */
1536                 MIPS32_BEQ(9,0, 11),            /* beq $t1, $zero, done         ; if (out == 0) goto done               */
1537                 MIPS32_NOP,                     /* nop                                                                  */
1538                                                                                                                         /* cont:        */
1539                 MIPS32_ADDI(6,6,NEG16(1)),      /* addi, $a2, $a2, -1           ; numwrites--                           */
1540                 MIPS32_BNE(6,0, 5),             /* bne $a2, $zero, cont2        ; if (numwrite != 0) goto cont2         */
1541                 MIPS32_NOP,                     /* nop                                                                  */
1542                 
1543                 MIPS32_LUI(9,0),                /* lui $t1, 0                                                           */
1544                 MIPS32_ORI(9,9,0x80),           /* ori $t1, $t1, 0x80           ; out = 0x80                            */
1545
1546                 MIPS32_B(4),                    /* b done                       ; goto done                             */
1547                 MIPS32_NOP,                     /* nop                                                                  */
1548                                                                                                                         /* cont2:       */
1549                 MIPS32_ADDI(5,5,2),             /* addi $a0, $a0, 2             ; daddr += 2                            */
1550                 MIPS32_B(NEG16(33)),            /* b start                      ; goto start                            */
1551                 MIPS32_NOP,                     /* nop                                                                  */
1552                                                                                                                         /* done:        */
1553                 /*MIPS32_B(NEG16(1)),   */      /* b done                       ; goto done                             */
1554                 MIPS32_SDBBP,                   /* sdbbp                        ; break();                              */
1555                 /*MIPS32_B(NEG16(33)),  */      /* b start                      ; goto start                            */
1556                 /* MIPS32_NOP, */
1557         };
1558
1559         mips32_info.common_magic = MIPS32_COMMON_MAGIC;
1560         mips32_info.isa_mode = MIPS32_ISA_MIPS32;
1561
1562         int target_code_size = 0;
1563         const uint32_t *target_code_src = NULL;
1564
1565         switch (bank->bus_width)
1566         {
1567         case 2 :
1568                 /* Check for DQ5 support */
1569                 if( cfi_info->status_poll_mask & (1 << 5) )
1570                 {
1571                         target_code_src = mips_word_16_code;
1572                         target_code_size = sizeof(mips_word_16_code);
1573                 }
1574                 else
1575                 {
1576                         LOG_ERROR("Need DQ5 support");
1577                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1578                         //target_code_src = mips_word_16_code_dq7only;
1579                         //target_code_size = sizeof(mips_word_16_code_dq7only);
1580                 }
1581                 break;
1582         default:
1583                 LOG_ERROR("Unsupported bank buswidth %d, can't do block memory writes", bank->bus_width);
1584                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1585         }
1586
1587         /* flash write code */
1588         if (!cfi_info->write_algorithm)
1589         {
1590                 uint8_t *target_code;
1591
1592                 /* convert bus-width dependent algorithm code to correct endiannes */
1593                 target_code = malloc(target_code_size);
1594                 if (target_code == NULL)
1595                 {
1596                         LOG_ERROR("Out of memory");
1597                         return ERROR_FAIL;
1598                 }
1599                 cfi_fix_code_endian(target, target_code, target_code_src, target_code_size / 4);
1600
1601                 /* allocate working area */
1602                 retval = target_alloc_working_area(target, target_code_size,
1603                                 &cfi_info->write_algorithm);
1604                 if (retval != ERROR_OK)
1605                 {
1606                         free(target_code);
1607                         return retval;
1608                 }
1609
1610                 /* write algorithm code to working area */
1611                 if ((retval = target_write_buffer(target, cfi_info->write_algorithm->address,
1612                                 target_code_size, target_code)) != ERROR_OK)
1613                 {
1614                         free(target_code);
1615                         return retval;
1616                 }
1617
1618                 free(target_code);
1619         }
1620         /* the following code still assumes target code is fixed 24*4 bytes */
1621
1622         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK)
1623         {
1624                 buffer_size /= 2;
1625                 if (buffer_size <= 256)
1626                 {
1627                         /* if we already allocated the writing code, but failed to get a
1628                          * buffer, free the algorithm */
1629                         if (cfi_info->write_algorithm)
1630                                 target_free_working_area(target, cfi_info->write_algorithm);
1631
1632                         LOG_WARNING("not enough working area available, can't do block memory writes");
1633                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1634                 }
1635         };
1636
1637         init_reg_param(&reg_params[0], "a0", 32, PARAM_OUT);
1638         init_reg_param(&reg_params[1], "a1", 32, PARAM_OUT);
1639         init_reg_param(&reg_params[2], "a2", 32, PARAM_OUT);
1640         init_reg_param(&reg_params[3], "a3", 32, PARAM_OUT);
1641         init_reg_param(&reg_params[4], "t0", 32, PARAM_OUT);
1642         init_reg_param(&reg_params[5], "t1", 32, PARAM_IN);
1643         init_reg_param(&reg_params[6], "t4", 32, PARAM_OUT);
1644         init_reg_param(&reg_params[7], "t5", 32, PARAM_OUT);
1645         init_reg_param(&reg_params[8], "t6", 32, PARAM_OUT);
1646         init_reg_param(&reg_params[9], "t7", 32, PARAM_OUT);
1647
1648         while (count > 0)
1649         {
1650                 uint32_t thisrun_count = (count > buffer_size) ? buffer_size : count;
1651
1652                 retval = target_write_buffer(target, source->address, thisrun_count, buffer);
1653                 if (retval != ERROR_OK)
1654                 {
1655                         break;
1656                 }
1657
1658                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
1659                 buf_set_u32(reg_params[1].value, 0, 32, address);
1660                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count / bank->bus_width);
1661                 buf_set_u32(reg_params[3].value, 0, 32, cfi_command_val(bank, 0xA0));
1662                 buf_set_u32(reg_params[4].value, 0, 32, cfi_command_val(bank, 0x80));
1663                 buf_set_u32(reg_params[6].value, 0, 32, flash_address(bank, 0, pri_ext->_unlock1));
1664                 buf_set_u32(reg_params[7].value, 0, 32, 0xaaaaaaaa);
1665                 buf_set_u32(reg_params[8].value, 0, 32, flash_address(bank, 0, pri_ext->_unlock2));
1666                 buf_set_u32(reg_params[9].value, 0, 32, 0x55555555);
1667
1668                 retval = target_run_algorithm(target, 0, NULL, 10, reg_params,
1669                                 cfi_info->write_algorithm->address,
1670                                 cfi_info->write_algorithm->address + ((target_code_size) - 4),
1671                                 10000, &mips32_info);
1672                 if (retval != ERROR_OK)
1673                 {
1674                         break;
1675                 }
1676
1677                 status = buf_get_u32(reg_params[5].value, 0, 32);
1678                 if (status != 0x80)
1679                 {
1680                         LOG_ERROR("flash write block failed status: 0x%" PRIx32 , status);
1681                         retval = ERROR_FLASH_OPERATION_FAILED;
1682                         break;
1683                 }
1684
1685                 buffer += thisrun_count;
1686                 address += thisrun_count;
1687                 count -= thisrun_count;
1688         }
1689
1690         target_free_all_working_areas(target);
1691
1692         destroy_reg_param(&reg_params[0]);
1693         destroy_reg_param(&reg_params[1]);
1694         destroy_reg_param(&reg_params[2]);
1695         destroy_reg_param(&reg_params[3]);
1696         destroy_reg_param(&reg_params[4]);
1697         destroy_reg_param(&reg_params[5]);
1698         destroy_reg_param(&reg_params[6]);
1699         destroy_reg_param(&reg_params[7]);
1700         destroy_reg_param(&reg_params[8]);
1701         destroy_reg_param(&reg_params[9]);
1702
1703         return retval;
1704 }
1705
1706 static int cfi_spansion_write_block(struct flash_bank *bank, uint8_t *buffer,
1707                 uint32_t address, uint32_t count)
1708 {
1709         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1710         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
1711         struct target *target = bank->target;
1712         struct reg_param reg_params[10];
1713         struct arm_algorithm armv4_5_info;
1714         struct working_area *source;
1715         uint32_t buffer_size = 32768;
1716         uint32_t status;
1717         int retval = ERROR_OK;
1718
1719         /* input parameters - */
1720         /*      R0 = source address */
1721         /*      R1 = destination address */
1722         /*      R2 = number of writes */
1723         /*      R3 = flash write command */
1724         /*      R4 = constant to mask DQ7 bits (also used for Dq5 with shift) */
1725         /* output parameters - */
1726         /*      R5 = 0x80 ok 0x00 bad */
1727         /* temp registers - */
1728         /*      R6 = value read from flash to test status */
1729         /*      R7 = holding register */
1730         /* unlock registers - */
1731         /*  R8 = unlock1_addr */
1732         /*  R9 = unlock1_cmd */
1733         /*  R10 = unlock2_addr */
1734         /*  R11 = unlock2_cmd */
1735
1736         /* see contib/loaders/flash/armv4_5_cfi_span_32.s for src */
1737         static const uint32_t armv4_5_word_32_code[] = {
1738                                                 /* 00008100 <sp_32_code>:               */
1739                 0xe4905004,             /* ldr  r5, [r0], #4                    */
1740                 0xe5889000,             /* str  r9, [r8]                                */
1741                 0xe58ab000,             /* str  r11, [r10]                              */
1742                 0xe5883000,             /* str  r3, [r8]                                */
1743                 0xe5815000,             /* str  r5, [r1]                                */
1744                 0xe1a00000,             /* nop                                                  */
1745                                                 /*                                                              */
1746                                                 /* 00008110 <sp_32_busy>:               */
1747                 0xe5916000,             /* ldr  r6, [r1]                                */
1748                 0xe0257006,             /* eor  r7, r5, r6                              */
1749                 0xe0147007,             /* ands r7, r4, r7                              */
1750                 0x0a000007,             /* beq  8140 <sp_32_cont> ; b if DQ7 == Data7 */
1751                 0xe0166124,             /* ands r6, r6, r4, lsr #2              */
1752                 0x0afffff9,             /* beq  8110 <sp_32_busy> ;     b if DQ5 low */
1753                 0xe5916000,             /* ldr  r6, [r1]                                */
1754                 0xe0257006,             /* eor  r7, r5, r6                              */
1755                 0xe0147007,             /* ands r7, r4, r7                              */
1756                 0x0a000001,             /* beq  8140 <sp_32_cont> ; b if DQ7 == Data7 */
1757                 0xe3a05000,             /* mov  r5, #0  ; 0x0 - return 0x00, error */
1758                 0x1a000004,             /* bne  8154 <sp_32_done>               */
1759                                                 /*                                                              */
1760                                                 /* 00008140 <sp_32_cont>:               */
1761                 0xe2522001,             /* subs r2, r2, #1      ; 0x1           */
1762                 0x03a05080,             /* moveq        r5, #128        ; 0x80  */
1763                 0x0a000001,             /* beq  8154 <sp_32_done>               */
1764                 0xe2811004,             /* add  r1, r1, #4      ; 0x4           */
1765                 0xeaffffe8,             /* b    8100 <sp_32_code>               */
1766                                                 /*                                                              */
1767                                                 /* 00008154 <sp_32_done>:               */
1768                 0xeafffffe              /* b    8154 <sp_32_done>               */
1769         };
1770
1771         /* see contib/loaders/flash/armv4_5_cfi_span_16.s for src */
1772         static const uint32_t armv4_5_word_16_code[] = {
1773                                                 /* 00008158 <sp_16_code>:               */
1774                 0xe0d050b2,             /* ldrh r5, [r0], #2                    */
1775                 0xe1c890b0,             /* strh r9, [r8]                                */
1776                 0xe1cab0b0,             /* strh r11, [r10]                              */
1777                 0xe1c830b0,             /* strh r3, [r8]                                */
1778                 0xe1c150b0,             /* strh r5, [r1]                                */
1779                 0xe1a00000,             /* nop                  (mov r0,r0)             */
1780                                                 /*                                                              */
1781                                                 /* 00008168 <sp_16_busy>:               */
1782                 0xe1d160b0,             /* ldrh r6, [r1]                                */
1783                 0xe0257006,             /* eor  r7, r5, r6                              */
1784                 0xe0147007,             /* ands r7, r4, r7                              */
1785                 0x0a000007,             /* beq  8198 <sp_16_cont>               */
1786                 0xe0166124,             /* ands r6, r6, r4, lsr #2              */
1787                 0x0afffff9,             /* beq  8168 <sp_16_busy>               */
1788                 0xe1d160b0,             /* ldrh r6, [r1]                                */
1789                 0xe0257006,             /* eor  r7, r5, r6                              */
1790                 0xe0147007,             /* ands r7, r4, r7                              */
1791                 0x0a000001,             /* beq  8198 <sp_16_cont>               */
1792                 0xe3a05000,             /* mov  r5, #0  ; 0x0                   */
1793                 0x1a000004,             /* bne  81ac <sp_16_done>               */
1794                                                 /*                                                              */
1795                                                 /* 00008198 <sp_16_cont>:               */
1796                 0xe2522001,     /* subs r2, r2, #1      ; 0x1           */
1797                 0x03a05080,     /* moveq        r5, #128        ; 0x80  */
1798                 0x0a000001,     /* beq  81ac <sp_16_done>               */
1799                 0xe2811002,     /* add  r1, r1, #2      ; 0x2           */
1800                 0xeaffffe8,     /* b    8158 <sp_16_code>               */
1801                                                 /*                                                              */
1802                                                 /* 000081ac <sp_16_done>:               */
1803                 0xeafffffe              /* b    81ac <sp_16_done>               */
1804         };
1805
1806         /* see contib/loaders/flash/armv7m_cfi_span_16.s for src */
1807         static const uint32_t armv7m_word_16_code[] = {
1808                 0x5B02F830,
1809                 0x9000F8A8,
1810                 0xB000F8AA,
1811                 0x3000F8A8,
1812                 0xBF00800D,
1813                 0xEA85880E,
1814                 0x40270706,
1815                 0xEA16D00A,
1816                 0xD0F70694,
1817                 0xEA85880E,
1818                 0x40270706,
1819                 0xF04FD002,
1820                 0xD1070500,
1821                 0xD0023A01,
1822                 0x0102F101,
1823                 0xF04FE7E0,
1824                 0xE7FF0580,
1825                 0x0000BE00
1826         };
1827
1828         /* see contib/loaders/flash/armv4_5_cfi_span_16_dq7.s for src */
1829         static const uint32_t armv4_5_word_16_code_dq7only[] = {
1830                                                 /* <sp_16_code>:                                */
1831                 0xe0d050b2,             /* ldrh r5, [r0], #2                    */
1832                 0xe1c890b0,             /* strh r9, [r8]                                */
1833                 0xe1cab0b0,             /* strh r11, [r10]                              */
1834                 0xe1c830b0,             /* strh r3, [r8]                                */
1835                 0xe1c150b0,             /* strh r5, [r1]                                */
1836                 0xe1a00000,             /* nop                  (mov r0,r0)             */
1837                                                 /*                                                              */
1838                                                 /* <sp_16_busy>:                                */
1839                 0xe1d160b0,             /* ldrh r6, [r1]                                */
1840                 0xe0257006,             /* eor  r7, r5, r6                              */
1841                 0xe2177080,             /* ands r7, #0x80                               */
1842                 0x1afffffb,             /* bne  8168 <sp_16_busy>               */
1843                                                 /*                                                              */
1844                 0xe2522001,             /* subs r2, r2, #1      ; 0x1           */
1845                 0x03a05080,             /* moveq        r5, #128        ; 0x80  */
1846                 0x0a000001,             /* beq  81ac <sp_16_done>               */
1847                 0xe2811002,             /* add  r1, r1, #2      ; 0x2           */
1848                 0xeafffff0,             /* b    8158 <sp_16_code>               */
1849                                                 /*                                                              */
1850                                                 /* 000081ac <sp_16_done>:               */
1851                 0xeafffffe              /* b    81ac <sp_16_done>               */
1852         };
1853
1854         /* see contib/loaders/flash/armv4_5_cfi_span_8.s for src */
1855         static const uint32_t armv4_5_word_8_code[] = {
1856                                                 /* 000081b0 <sp_16_code_end>:   */
1857                 0xe4d05001,             /* ldrb r5, [r0], #1                    */
1858                 0xe5c89000,             /* strb r9, [r8]                                */
1859                 0xe5cab000,             /* strb r11, [r10]                              */
1860                 0xe5c83000,             /* strb r3, [r8]                                */
1861                 0xe5c15000,             /* strb r5, [r1]                                */
1862                 0xe1a00000,             /* nop                  (mov r0,r0)             */
1863                                                 /*                                                              */
1864                                                 /* 000081c0 <sp_8_busy>:                */
1865                 0xe5d16000,             /* ldrb r6, [r1]                                */
1866                 0xe0257006,             /* eor  r7, r5, r6                              */
1867                 0xe0147007,             /* ands r7, r4, r7                              */
1868                 0x0a000007,             /* beq  81f0 <sp_8_cont>                */
1869                 0xe0166124,             /* ands r6, r6, r4, lsr #2              */
1870                 0x0afffff9,             /* beq  81c0 <sp_8_busy>                */
1871                 0xe5d16000,             /* ldrb r6, [r1]                                */
1872                 0xe0257006,             /* eor  r7, r5, r6                              */
1873                 0xe0147007,             /* ands r7, r4, r7                              */
1874                 0x0a000001,             /* beq  81f0 <sp_8_cont>                */
1875                 0xe3a05000,             /* mov  r5, #0  ; 0x0                   */
1876                 0x1a000004,             /* bne  8204 <sp_8_done>                */
1877                                                 /*                                                              */
1878                                                 /* 000081f0 <sp_8_cont>:                */
1879                 0xe2522001,             /* subs r2, r2, #1      ; 0x1           */
1880                 0x03a05080,             /* moveq        r5, #128        ; 0x80  */
1881                 0x0a000001,             /* beq  8204 <sp_8_done>                */
1882                 0xe2811001,             /* add  r1, r1, #1      ; 0x1           */
1883                 0xeaffffe8,             /* b    81b0 <sp_16_code_end>   */
1884                                                 /*                                                              */
1885                                                 /* 00008204 <sp_8_done>:                */
1886                 0xeafffffe              /* b    8204 <sp_8_done>                */
1887         };
1888
1889         if (strncmp(target_type_name(target),"mips_m4k",8) == 0)
1890         {
1891                 return cfi_spansion_write_block_mips(bank,buffer,address,count);
1892         }
1893
1894         if (is_armv7m(target_to_armv7m(target))) /* Cortex-M3 target */
1895         {
1896                 armv4_5_info.common_magic = ARMV7M_COMMON_MAGIC;
1897                 armv4_5_info.core_mode = ARMV7M_MODE_HANDLER;
1898                 armv4_5_info.core_state = ARM_STATE_ARM;
1899         } else if (is_arm7_9(target_to_arm7_9(target)))
1900         {
1901                 /* All other ARM CPUs have 32 bit instructions */
1902                 armv4_5_info.common_magic = ARM_COMMON_MAGIC;
1903                 armv4_5_info.core_mode = ARM_MODE_SVC;
1904                 armv4_5_info.core_state = ARM_STATE_ARM;
1905         } else {
1906                 LOG_ERROR("Unknown ARM architecture");
1907                 return ERROR_FAIL;
1908         }
1909
1910         int target_code_size = 0;
1911         const uint32_t *target_code_src = NULL;
1912
1913         switch (bank->bus_width)
1914         {
1915         case 1 :
1916                 if (armv4_5_info.common_magic != ARM_COMMON_MAGIC) {
1917                         LOG_ERROR("Unknown ARM architecture");
1918                         return ERROR_FAIL;
1919                 }
1920                 target_code_src = armv4_5_word_8_code;
1921                 target_code_size = sizeof(armv4_5_word_8_code);
1922                 break;
1923         case 2 :
1924                 /* Check for DQ5 support */
1925                 if( cfi_info->status_poll_mask & (1 << 5) )
1926                 {
1927                         if(armv4_5_info.common_magic == ARM_COMMON_MAGIC) /* armv4_5 target */
1928                         {
1929                                 target_code_src = armv4_5_word_16_code;
1930                                 target_code_size = sizeof(armv4_5_word_16_code);
1931                         }
1932                         else if (armv4_5_info.common_magic == ARMV7M_COMMON_MAGIC) /* cortex-m3 target */
1933                         {
1934                                 target_code_src = armv7m_word_16_code;
1935                                 target_code_size = sizeof(armv7m_word_16_code);
1936                         }
1937                 }
1938                 else
1939                 {
1940                         /* No DQ5 support. Use DQ7 DATA# polling only. */
1941                         if (armv4_5_info.common_magic != ARM_COMMON_MAGIC) {
1942                                 LOG_ERROR("Unknown ARM architecture");
1943                                 return ERROR_FAIL;
1944                         }
1945                         target_code_src = armv4_5_word_16_code_dq7only;
1946                         target_code_size = sizeof(armv4_5_word_16_code_dq7only);
1947                 }
1948                 break;
1949         case 4 :
1950                 if (armv4_5_info.common_magic != ARM_COMMON_MAGIC) {
1951                         LOG_ERROR("Unknown ARM architecture");
1952                         return ERROR_FAIL;
1953                 }
1954                 target_code_src = armv4_5_word_32_code;
1955                 target_code_size = sizeof(armv4_5_word_32_code);
1956                 break;
1957         default:
1958                 LOG_ERROR("Unsupported bank buswidth %d, can't do block memory writes", bank->bus_width);
1959                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1960         }
1961
1962         /* flash write code */
1963         if (!cfi_info->write_algorithm)
1964         {
1965                 uint8_t *target_code;
1966
1967                 /* convert bus-width dependent algorithm code to correct endiannes */
1968                 target_code = malloc(target_code_size);
1969                 if (target_code == NULL)
1970                 {
1971                         LOG_ERROR("Out of memory");
1972                         return ERROR_FAIL;
1973                 }
1974                 cfi_fix_code_endian(target, target_code, target_code_src, target_code_size / 4);
1975
1976                 /* allocate working area */
1977                 retval = target_alloc_working_area(target, target_code_size,
1978                                 &cfi_info->write_algorithm);
1979                 if (retval != ERROR_OK)
1980                 {
1981                         free(target_code);
1982                         return retval;
1983                 }
1984
1985                 /* write algorithm code to working area */
1986                 if ((retval = target_write_buffer(target, cfi_info->write_algorithm->address,
1987                                 target_code_size, target_code)) != ERROR_OK)
1988                 {
1989                         free(target_code);
1990                         return retval;
1991                 }
1992
1993                 free(target_code);
1994         }
1995         /* the following code still assumes target code is fixed 24*4 bytes */
1996
1997         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK)
1998         {
1999                 buffer_size /= 2;
2000                 if (buffer_size <= 256)
2001                 {
2002                         /* if we already allocated the writing code, but failed to get a
2003                          * buffer, free the algorithm */
2004                         if (cfi_info->write_algorithm)
2005                                 target_free_working_area(target, cfi_info->write_algorithm);
2006
2007                         LOG_WARNING("not enough working area available, can't do block memory writes");
2008                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2009                 }
2010         };
2011
2012         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
2013         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
2014         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
2015         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
2016         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
2017         init_reg_param(&reg_params[5], "r5", 32, PARAM_IN);
2018         init_reg_param(&reg_params[6], "r8", 32, PARAM_OUT);
2019         init_reg_param(&reg_params[7], "r9", 32, PARAM_OUT);
2020         init_reg_param(&reg_params[8], "r10", 32, PARAM_OUT);
2021         init_reg_param(&reg_params[9], "r11", 32, PARAM_OUT);
2022
2023         while (count > 0)
2024         {
2025                 uint32_t thisrun_count = (count > buffer_size) ? buffer_size : count;
2026
2027                 retval = target_write_buffer(target, source->address, thisrun_count, buffer);
2028                 if (retval != ERROR_OK)
2029                 {
2030                         break;
2031                 }
2032
2033                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
2034                 buf_set_u32(reg_params[1].value, 0, 32, address);
2035                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count / bank->bus_width);
2036                 buf_set_u32(reg_params[3].value, 0, 32, cfi_command_val(bank, 0xA0));
2037                 buf_set_u32(reg_params[4].value, 0, 32, cfi_command_val(bank, 0x80));
2038                 buf_set_u32(reg_params[6].value, 0, 32, flash_address(bank, 0, pri_ext->_unlock1));
2039                 buf_set_u32(reg_params[7].value, 0, 32, 0xaaaaaaaa);
2040                 buf_set_u32(reg_params[8].value, 0, 32, flash_address(bank, 0, pri_ext->_unlock2));
2041                 buf_set_u32(reg_params[9].value, 0, 32, 0x55555555);
2042
2043                 retval = target_run_algorithm(target, 0, NULL, 10, reg_params,
2044                                 cfi_info->write_algorithm->address,
2045                                 cfi_info->write_algorithm->address + ((target_code_size) - 4),
2046                                 10000, &armv4_5_info);
2047                 if (retval != ERROR_OK)
2048                 {
2049                         break;
2050                 }
2051
2052                 status = buf_get_u32(reg_params[5].value, 0, 32);
2053                 if (status != 0x80)
2054                 {
2055                         LOG_ERROR("flash write block failed status: 0x%" PRIx32 , status);
2056                         retval = ERROR_FLASH_OPERATION_FAILED;
2057                         break;
2058                 }
2059
2060                 buffer += thisrun_count;
2061                 address += thisrun_count;
2062                 count -= thisrun_count;
2063         }
2064
2065         target_free_all_working_areas(target);
2066
2067         destroy_reg_param(&reg_params[0]);
2068         destroy_reg_param(&reg_params[1]);
2069         destroy_reg_param(&reg_params[2]);
2070         destroy_reg_param(&reg_params[3]);
2071         destroy_reg_param(&reg_params[4]);
2072         destroy_reg_param(&reg_params[5]);
2073         destroy_reg_param(&reg_params[6]);
2074         destroy_reg_param(&reg_params[7]);
2075         destroy_reg_param(&reg_params[8]);
2076         destroy_reg_param(&reg_params[9]);
2077
2078         return retval;
2079 }
2080
2081 static int cfi_intel_write_word(struct flash_bank *bank, uint8_t *word, uint32_t address)
2082 {
2083         int retval;
2084         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2085         struct target *target = bank->target;
2086
2087         cfi_intel_clear_status_register(bank);
2088         if ((retval = cfi_send_command(bank, 0x40, address)) != ERROR_OK)
2089         {
2090                 return retval;
2091         }
2092
2093         if ((retval = target_write_memory(target, address, bank->bus_width, 1, word)) != ERROR_OK)
2094         {
2095                 return retval;
2096         }
2097
2098         uint8_t status;
2099         retval = cfi_intel_wait_status_busy(bank, cfi_info->word_write_timeout, &status);
2100         if (retval != 0x80)
2101         {
2102                 if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
2103                 {
2104                         return retval;
2105                 }
2106
2107                 LOG_ERROR("couldn't write word at base 0x%" PRIx32 ", address 0x%" PRIx32,
2108                                 bank->base, address);
2109                 return ERROR_FLASH_OPERATION_FAILED;
2110         }
2111
2112         return ERROR_OK;
2113 }
2114
2115 static int cfi_intel_write_words(struct flash_bank *bank, uint8_t *word,
2116                 uint32_t wordcount, uint32_t address)
2117 {
2118         int retval;
2119         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2120         struct target *target = bank->target;
2121
2122         /* Calculate buffer size and boundary mask */
2123         /* buffersize is (buffer size per chip) * (number of chips) */
2124         /* bufferwsize is buffersize in words */
2125         uint32_t buffersize = (1UL << cfi_info->max_buf_write_size) * (bank->bus_width / bank->chip_width);
2126         uint32_t buffermask = buffersize-1;
2127         uint32_t bufferwsize = buffersize / bank->bus_width;
2128
2129         /* Check for valid range */
2130         if (address & buffermask)
2131         {
2132                 LOG_ERROR("Write address at base 0x%" PRIx32 ", address 0x%" PRIx32
2133                                 " not aligned to 2^%d boundary",
2134                                 bank->base, address, cfi_info->max_buf_write_size);
2135                 return ERROR_FLASH_OPERATION_FAILED;
2136         }
2137
2138         /* Check for valid size */
2139         if (wordcount > bufferwsize)
2140         {
2141                 LOG_ERROR("Number of data words %" PRId32 " exceeds available buffersize %" PRId32,
2142                                 wordcount, buffersize);
2143                 return ERROR_FLASH_OPERATION_FAILED;
2144         }
2145
2146         /* Write to flash buffer */
2147         cfi_intel_clear_status_register(bank);
2148
2149         /* Initiate buffer operation _*/
2150         if ((retval = cfi_send_command(bank, 0xe8, address)) != ERROR_OK)
2151         {
2152                 return retval;
2153         }
2154         uint8_t status;
2155         retval = cfi_intel_wait_status_busy(bank, cfi_info->buf_write_timeout, &status);
2156         if (retval != ERROR_OK)
2157                 return retval;
2158         if (status != 0x80)
2159         {
2160                 if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
2161                 {
2162                         return retval;
2163                 }
2164
2165                 LOG_ERROR("couldn't start buffer write operation at base 0x%" PRIx32 ", address 0x%" PRIx32,
2166                                 bank->base, address);
2167                 return ERROR_FLASH_OPERATION_FAILED;
2168         }
2169
2170         /* Write buffer wordcount-1 and data words */
2171         if ((retval = cfi_send_command(bank, bufferwsize-1, address)) != ERROR_OK)
2172         {
2173                 return retval;
2174         }
2175
2176         if ((retval = target_write_memory(target,
2177                         address, bank->bus_width, bufferwsize, word)) != ERROR_OK)
2178         {
2179                 return retval;
2180         }
2181
2182         /* Commit write operation */
2183         if ((retval = cfi_send_command(bank, 0xd0, address)) != ERROR_OK)
2184         {
2185                 return retval;
2186         }
2187
2188         retval = cfi_intel_wait_status_busy(bank, cfi_info->buf_write_timeout, &status);
2189         if (retval != ERROR_OK)
2190                 return retval;
2191
2192         if (status != 0x80)
2193         {
2194                 if ((retval = cfi_send_command(bank, 0xff,
2195                                 flash_address(bank, 0, 0x0))) != ERROR_OK)
2196                 {
2197                         return retval;
2198                 }
2199
2200                 LOG_ERROR("Buffer write at base 0x%" PRIx32
2201                                 ", address 0x%" PRIx32 " failed.", bank->base, address);
2202                 return ERROR_FLASH_OPERATION_FAILED;
2203         }
2204
2205         return ERROR_OK;
2206 }
2207
2208 static int cfi_spansion_write_word(struct flash_bank *bank, uint8_t *word, uint32_t address)
2209 {
2210         int retval;
2211         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2212         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2213         struct target *target = bank->target;
2214
2215         if ((retval = cfi_send_command(bank, 0xaa,
2216                         flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
2217         {
2218                 return retval;
2219         }
2220
2221         if ((retval = cfi_send_command(bank, 0x55,
2222                         flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
2223         {
2224                 return retval;
2225         }
2226
2227         if ((retval = cfi_send_command(bank, 0xa0,
2228                         flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
2229         {
2230                 return retval;
2231         }
2232
2233         if ((retval = target_write_memory(target,
2234                         address, bank->bus_width, 1, word)) != ERROR_OK)
2235         {
2236                 return retval;
2237         }
2238
2239         if (cfi_spansion_wait_status_busy(bank, cfi_info->word_write_timeout) != ERROR_OK)
2240         {
2241                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
2242                 {
2243                         return retval;
2244                 }
2245
2246                 LOG_ERROR("couldn't write word at base 0x%" PRIx32
2247                                 ", address 0x%" PRIx32 , bank->base, address);
2248                 return ERROR_FLASH_OPERATION_FAILED;
2249         }
2250
2251         return ERROR_OK;
2252 }
2253
2254 static int cfi_spansion_write_words(struct flash_bank *bank, uint8_t *word,
2255                 uint32_t wordcount, uint32_t address)
2256 {
2257         int retval;
2258         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2259         struct target *target = bank->target;
2260         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2261
2262         /* Calculate buffer size and boundary mask */
2263         /* buffersize is (buffer size per chip) * (number of chips) */
2264         /* bufferwsize is buffersize in words */
2265         uint32_t buffersize = (1UL << cfi_info->max_buf_write_size) * (bank->bus_width / bank->chip_width);
2266         uint32_t buffermask = buffersize-1;
2267         uint32_t bufferwsize = buffersize / bank->bus_width;
2268
2269         /* Check for valid range */
2270         if (address & buffermask)
2271         {
2272                 LOG_ERROR("Write address at base 0x%" PRIx32
2273                                 ", address 0x%" PRIx32 " not aligned to 2^%d boundary",
2274                                 bank->base, address, cfi_info->max_buf_write_size);
2275                 return ERROR_FLASH_OPERATION_FAILED;
2276         }
2277
2278         /* Check for valid size */
2279         if (wordcount > bufferwsize)
2280         {
2281                 LOG_ERROR("Number of data words %" PRId32 " exceeds available buffersize %"
2282                                 PRId32, wordcount, buffersize);
2283                 return ERROR_FLASH_OPERATION_FAILED;
2284         }
2285
2286         /* Unlock */
2287         if ((retval = cfi_send_command(bank, 0xaa,
2288                         flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
2289         {
2290                 return retval;
2291         }
2292
2293         if ((retval = cfi_send_command(bank, 0x55,
2294                         flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
2295         {
2296                 return retval;
2297         }
2298
2299         /* Buffer load command */
2300         if ((retval = cfi_send_command(bank, 0x25, address)) != ERROR_OK)
2301         {
2302                 return retval;
2303         }
2304
2305         /* Write buffer wordcount-1 and data words */
2306         if ((retval = cfi_send_command(bank, bufferwsize-1, address)) != ERROR_OK)
2307         {
2308                 return retval;
2309         }
2310
2311         if ((retval = target_write_memory(target,
2312                         address, bank->bus_width, bufferwsize, word)) != ERROR_OK)
2313         {
2314                 return retval;
2315         }
2316
2317         /* Commit write operation */
2318         if ((retval = cfi_send_command(bank, 0x29, address)) != ERROR_OK)
2319         {
2320                 return retval;
2321         }
2322
2323         if (cfi_spansion_wait_status_busy(bank, cfi_info->buf_write_timeout) != ERROR_OK)
2324         {
2325                 if ((retval = cfi_send_command(bank, 0xf0,
2326                                 flash_address(bank, 0, 0x0))) != ERROR_OK)
2327                 {
2328                         return retval;
2329                 }
2330
2331                 LOG_ERROR("couldn't write block at base 0x%" PRIx32
2332                                 ", address 0x%" PRIx32 ", size 0x%" PRIx32, bank->base, address, bufferwsize);
2333                 return ERROR_FLASH_OPERATION_FAILED;
2334         }
2335
2336         return ERROR_OK;
2337 }
2338
2339 static int cfi_write_word(struct flash_bank *bank, uint8_t *word, uint32_t address)
2340 {
2341         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2342
2343         switch (cfi_info->pri_id)
2344         {
2345                 case 1:
2346                 case 3:
2347                         return cfi_intel_write_word(bank, word, address);
2348                         break;
2349                 case 2:
2350                         return cfi_spansion_write_word(bank, word, address);
2351                         break;
2352                 default:
2353                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2354                         break;
2355         }
2356
2357         return ERROR_FLASH_OPERATION_FAILED;
2358 }
2359
2360 static int cfi_write_words(struct flash_bank *bank, uint8_t *word,
2361                 uint32_t wordcount, uint32_t address)
2362 {
2363         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2364
2365         if (cfi_info->buf_write_timeout_typ == 0)
2366         {
2367                 /* buffer writes are not supported */
2368                 LOG_DEBUG("Buffer Writes Not Supported");
2369                 return ERROR_FLASH_OPER_UNSUPPORTED;
2370         }
2371
2372         switch (cfi_info->pri_id)
2373         {
2374                 case 1:
2375                 case 3:
2376                         return cfi_intel_write_words(bank, word, wordcount, address);
2377                         break;
2378                 case 2:
2379                         return cfi_spansion_write_words(bank, word, wordcount, address);
2380                         break;
2381                 default:
2382                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2383                         break;
2384         }
2385
2386         return ERROR_FLASH_OPERATION_FAILED;
2387 }
2388
2389 static int cfi_read(struct flash_bank *bank, uint8_t *buffer, uint32_t offset, uint32_t count)
2390 {
2391         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2392         struct target *target = bank->target;
2393         uint32_t address = bank->base + offset;
2394         uint32_t read_p;
2395         int align;      /* number of unaligned bytes */
2396         uint8_t current_word[CFI_MAX_BUS_WIDTH];
2397         int i;
2398         int retval;
2399
2400         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
2401                 (int)count, (unsigned)offset);
2402
2403         if (bank->target->state != TARGET_HALTED)
2404         {
2405                 LOG_ERROR("Target not halted");
2406                 return ERROR_TARGET_NOT_HALTED;
2407         }
2408
2409         if (offset + count > bank->size)
2410                 return ERROR_FLASH_DST_OUT_OF_BANK;
2411
2412         if (cfi_info->qry[0] != 'Q')
2413                 return ERROR_FLASH_BANK_NOT_PROBED;
2414
2415         /* start at the first byte of the first word (bus_width size) */
2416         read_p = address & ~(bank->bus_width - 1);
2417         if ((align = address - read_p) != 0)
2418         {
2419                 LOG_INFO("Fixup %d unaligned read head bytes", align);
2420
2421                 /* read a complete word from flash */
2422                 if ((retval = target_read_memory(target, read_p,
2423                                 bank->bus_width, 1, current_word)) != ERROR_OK)
2424                         return retval;
2425
2426                 /* take only bytes we need */
2427                 for (i = align; (i < bank->bus_width) && (count > 0); i++, count--)
2428                         *buffer++ = current_word[i];
2429
2430                 read_p += bank->bus_width;
2431         }
2432
2433         align = count / bank->bus_width;
2434         if (align)
2435         {
2436                 if ((retval = target_read_memory(target, read_p,
2437                                 bank->bus_width, align, buffer)) != ERROR_OK)
2438                         return retval;
2439
2440                 read_p += align * bank->bus_width;
2441                 buffer += align * bank->bus_width;
2442                 count -= align * bank->bus_width;
2443         }
2444
2445         if (count)
2446         {
2447                 LOG_INFO("Fixup %d unaligned read tail bytes", count);
2448
2449                 /* read a complete word from flash */
2450                 if ((retval = target_read_memory(target, read_p,
2451                                 bank->bus_width, 1, current_word)) != ERROR_OK)
2452                         return retval;
2453
2454                 /* take only bytes we need */
2455                 for (i = 0; (i < bank->bus_width) && (count > 0); i++, count--)
2456                         *buffer++ = current_word[i];
2457         }
2458
2459         return ERROR_OK;
2460 }
2461
2462 static int cfi_write(struct flash_bank *bank, uint8_t *buffer, uint32_t offset, uint32_t count)
2463 {
2464         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2465         struct target *target = bank->target;
2466         uint32_t address = bank->base + offset; /* address of first byte to be programmed */
2467         uint32_t write_p;
2468         int align;      /* number of unaligned bytes */
2469         int blk_count; /* number of bus_width bytes for block copy */
2470         uint8_t current_word[CFI_MAX_BUS_WIDTH * 4];    /* word (bus_width size) currently being programmed */
2471         int i;
2472         int retval;
2473
2474         if (bank->target->state != TARGET_HALTED)
2475         {
2476                 LOG_ERROR("Target not halted");
2477                 return ERROR_TARGET_NOT_HALTED;
2478         }
2479
2480         if (offset + count > bank->size)
2481                 return ERROR_FLASH_DST_OUT_OF_BANK;
2482
2483         if (cfi_info->qry[0] != 'Q')
2484                 return ERROR_FLASH_BANK_NOT_PROBED;
2485
2486         /* start at the first byte of the first word (bus_width size) */
2487         write_p = address & ~(bank->bus_width - 1);
2488         if ((align = address - write_p) != 0)
2489         {
2490                 LOG_INFO("Fixup %d unaligned head bytes", align);
2491
2492                 /* read a complete word from flash */
2493                 if ((retval = target_read_memory(target, write_p,
2494                                 bank->bus_width, 1, current_word)) != ERROR_OK)
2495                         return retval;
2496
2497                 /* replace only bytes that must be written */
2498                 for (i = align; (i < bank->bus_width) && (count > 0); i++, count--)
2499                         current_word[i] = *buffer++;
2500
2501                 retval = cfi_write_word(bank, current_word, write_p);
2502                 if (retval != ERROR_OK)
2503                         return retval;
2504                 write_p += bank->bus_width;
2505         }
2506
2507         /* handle blocks of bus_size aligned bytes */
2508         blk_count = count & ~(bank->bus_width - 1); /* round down, leave tail bytes */
2509         switch (cfi_info->pri_id)
2510         {
2511                 /* try block writes (fails without working area) */
2512                 case 1:
2513                 case 3:
2514                         retval = cfi_intel_write_block(bank, buffer, write_p, blk_count);
2515                         break;
2516                 case 2:
2517                         retval = cfi_spansion_write_block(bank, buffer, write_p, blk_count);
2518                         break;
2519                 default:
2520                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2521                         retval = ERROR_FLASH_OPERATION_FAILED;
2522                         break;
2523         }
2524         if (retval == ERROR_OK)
2525         {
2526                 /* Increment pointers and decrease count on succesful block write */
2527                 buffer += blk_count;
2528                 write_p += blk_count;
2529                 count -= blk_count;
2530         }
2531         else
2532         {
2533                 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2534                 {
2535                         /* Calculate buffer size and boundary mask */
2536                         /* buffersize is (buffer size per chip) * (number of chips) */
2537                         /* bufferwsize is buffersize in words */
2538                         uint32_t buffersize = (1UL << cfi_info->max_buf_write_size) * (bank->bus_width / bank->chip_width);
2539                         uint32_t buffermask = buffersize-1;
2540                         uint32_t bufferwsize = buffersize / bank->bus_width;
2541
2542                         /* fall back to memory writes */
2543                         while (count >= (uint32_t)bank->bus_width)
2544                         {
2545                                 int fallback;
2546                                 if ((write_p & 0xff) == 0)
2547                                 {
2548                                         LOG_INFO("Programming at 0x%08" PRIx32 ", count 0x%08"
2549                                                         PRIx32 " bytes remaining", write_p, count);
2550                                 }
2551                                 fallback = 1;
2552                                 if ((bufferwsize > 0) && (count >= buffersize) && !(write_p & buffermask))
2553                                 {
2554                                         retval = cfi_write_words(bank, buffer, bufferwsize, write_p);
2555                                         if (retval == ERROR_OK)
2556                                         {
2557                                                 buffer += buffersize;
2558                                                 write_p += buffersize;
2559                                                 count -= buffersize;
2560                                                 fallback = 0;
2561                                         }
2562                                         else if (retval != ERROR_FLASH_OPER_UNSUPPORTED)
2563                                                 return retval;
2564                                 }
2565                                 /* try the slow way? */
2566                                 if (fallback)
2567                                 {
2568                                         for (i = 0; i < bank->bus_width; i++)
2569                                                 current_word[i] = *buffer++;
2570
2571                                         retval = cfi_write_word(bank, current_word, write_p);
2572                                         if (retval != ERROR_OK)
2573                                                 return retval;
2574
2575                                         write_p += bank->bus_width;
2576                                         count -= bank->bus_width;
2577                                 }
2578                         }
2579                 }
2580                 else
2581                         return retval;
2582         }
2583
2584         /* return to read array mode, so we can read from flash again for padding */
2585         if ((retval = cfi_reset(bank)) != ERROR_OK)
2586         {
2587                 return retval;
2588         }
2589
2590         /* handle unaligned tail bytes */
2591         if (count > 0)
2592         {
2593                 LOG_INFO("Fixup %" PRId32 " unaligned tail bytes", count);
2594
2595                 /* read a complete word from flash */
2596                 if ((retval = target_read_memory(target, write_p,
2597                                 bank->bus_width, 1, current_word)) != ERROR_OK)
2598                         return retval;
2599
2600                 /* replace only bytes that must be written */
2601                 for (i = 0; (i < bank->bus_width) && (count > 0); i++, count--)
2602                         current_word[i] = *buffer++;
2603
2604                 retval = cfi_write_word(bank, current_word, write_p);
2605                 if (retval != ERROR_OK)
2606                         return retval;
2607         }
2608
2609         /* return to read array mode */
2610         return cfi_reset(bank);
2611 }
2612
2613 static void cfi_fixup_reversed_erase_regions(struct flash_bank *bank, void *param)
2614 {
2615         (void) param;
2616         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2617         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2618
2619         pri_ext->_reversed_geometry = 1;
2620 }
2621
2622 static void cfi_fixup_0002_erase_regions(struct flash_bank *bank, void *param)
2623 {
2624         int i;
2625         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2626         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2627         (void) param;
2628
2629         if ((pri_ext->_reversed_geometry) || (pri_ext->TopBottom == 3))
2630         {
2631                 LOG_DEBUG("swapping reversed erase region information on cmdset 0002 device");
2632
2633                 for (i = 0; i < cfi_info->num_erase_regions / 2; i++)
2634                 {
2635                         int j = (cfi_info->num_erase_regions - 1) - i;
2636                         uint32_t swap;
2637
2638                         swap = cfi_info->erase_region_info[i];
2639                         cfi_info->erase_region_info[i] = cfi_info->erase_region_info[j];
2640                         cfi_info->erase_region_info[j] = swap;
2641                 }
2642         }
2643 }
2644
2645 static void cfi_fixup_0002_unlock_addresses(struct flash_bank *bank, void *param)
2646 {
2647         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2648         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2649         struct cfi_unlock_addresses *unlock_addresses = param;
2650
2651         pri_ext->_unlock1 = unlock_addresses->unlock1;
2652         pri_ext->_unlock2 = unlock_addresses->unlock2;
2653 }
2654
2655
2656 static int cfi_query_string(struct flash_bank *bank, int address)
2657 {
2658         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2659         int retval;
2660
2661         if ((retval = cfi_send_command(bank, 0x98, flash_address(bank, 0, address))) != ERROR_OK)
2662         {
2663                 return retval;
2664         }
2665
2666         retval = cfi_query_u8(bank, 0, 0x10, &cfi_info->qry[0]);
2667         if (retval != ERROR_OK)
2668                 return retval;
2669         retval = cfi_query_u8(bank, 0, 0x11, &cfi_info->qry[1]);
2670         if (retval != ERROR_OK)
2671                 return retval;
2672         retval = cfi_query_u8(bank, 0, 0x12, &cfi_info->qry[2]);
2673         if (retval != ERROR_OK)
2674                 return retval;
2675
2676         LOG_DEBUG("CFI qry returned: 0x%2.2x 0x%2.2x 0x%2.2x",
2677                         cfi_info->qry[0], cfi_info->qry[1], cfi_info->qry[2]);
2678
2679         if ((cfi_info->qry[0] != 'Q') || (cfi_info->qry[1] != 'R') || (cfi_info->qry[2] != 'Y'))
2680         {
2681                 if ((retval = cfi_reset(bank)) != ERROR_OK)
2682                 {
2683                         return retval;
2684                 }
2685                 LOG_ERROR("Could not probe bank: no QRY");
2686                 return ERROR_FLASH_BANK_INVALID;
2687         }
2688
2689         return ERROR_OK;
2690 }
2691
2692 static int cfi_probe(struct flash_bank *bank)
2693 {
2694         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2695         struct target *target = bank->target;
2696         int num_sectors = 0;
2697         int i;
2698         int sector = 0;
2699         uint32_t unlock1 = 0x555;
2700         uint32_t unlock2 = 0x2aa;
2701         int retval;
2702         uint8_t value_buf0[CFI_MAX_BUS_WIDTH], value_buf1[CFI_MAX_BUS_WIDTH];
2703
2704         if (bank->target->state != TARGET_HALTED)
2705         {
2706                 LOG_ERROR("Target not halted");
2707                 return ERROR_TARGET_NOT_HALTED;
2708         }
2709
2710         cfi_info->probed = 0;
2711         cfi_info->num_erase_regions = 0;
2712         if (bank->sectors)
2713         {
2714                 free(bank->sectors);
2715                 bank->sectors = NULL;
2716         }
2717         if(cfi_info->erase_region_info)
2718         {
2719                 free(cfi_info->erase_region_info);
2720                 cfi_info->erase_region_info = NULL;
2721         }
2722
2723         /* JEDEC standard JESD21C uses 0x5555 and 0x2aaa as unlock addresses,
2724          * while CFI compatible AMD/Spansion flashes use 0x555 and 0x2aa
2725          */
2726         if (cfi_info->jedec_probe)
2727         {
2728                 unlock1 = 0x5555;
2729                 unlock2 = 0x2aaa;
2730         }
2731
2732         /* switch to read identifier codes mode ("AUTOSELECT") */
2733         if ((retval = cfi_send_command(bank, 0xaa, flash_address(bank, 0, unlock1))) != ERROR_OK)
2734         {
2735                 return retval;
2736         }
2737         if ((retval = cfi_send_command(bank, 0x55, flash_address(bank, 0, unlock2))) != ERROR_OK)
2738         {
2739                 return retval;
2740         }
2741         if ((retval = cfi_send_command(bank, 0x90, flash_address(bank, 0, unlock1))) != ERROR_OK)
2742         {
2743                 return retval;
2744         }
2745
2746         if ((retval = target_read_memory(target, flash_address(bank, 0, 0x00),
2747                         bank->bus_width, 1, value_buf0)) != ERROR_OK)
2748         {
2749                 return retval;
2750         }
2751         if ((retval = target_read_memory(target, flash_address(bank, 0, 0x01),
2752                         bank->bus_width, 1, value_buf1)) != ERROR_OK)
2753         {
2754                 return retval;
2755         }
2756         switch (bank->chip_width) {
2757                 case 1:
2758                         cfi_info->manufacturer = *value_buf0;
2759                         cfi_info->device_id = *value_buf1;
2760                         break;
2761                 case 2:
2762                         cfi_info->manufacturer = target_buffer_get_u16(target, value_buf0);
2763                         cfi_info->device_id = target_buffer_get_u16(target, value_buf1);
2764                         break;
2765                 case 4:
2766                         cfi_info->manufacturer = target_buffer_get_u32(target, value_buf0);
2767                         cfi_info->device_id = target_buffer_get_u32(target, value_buf1);
2768                         break;
2769                 default:
2770                         LOG_ERROR("Unsupported bank chipwidth %d, can't probe memory", bank->chip_width);
2771                         return ERROR_FLASH_OPERATION_FAILED;
2772         }
2773
2774         LOG_INFO("Flash Manufacturer/Device: 0x%04x 0x%04x",
2775                         cfi_info->manufacturer, cfi_info->device_id);
2776         /* switch back to read array mode */
2777         if ((retval = cfi_reset(bank)) != ERROR_OK)
2778         {
2779                 return retval;
2780         }
2781
2782         /* check device/manufacturer ID for known non-CFI flashes. */
2783         cfi_fixup_non_cfi(bank);
2784
2785         /* query only if this is a CFI compatible flash,
2786          * otherwise the relevant info has already been filled in
2787          */
2788         if (cfi_info->not_cfi == 0)
2789         {
2790                 /* enter CFI query mode
2791                  * according to JEDEC Standard No. 68.01,
2792                  * a single bus sequence with address = 0x55, data = 0x98 should put
2793                  * the device into CFI query mode.
2794                  *
2795                  * SST flashes clearly violate this, and we will consider them incompatbile for now
2796                  */
2797
2798                 retval = cfi_query_string(bank, 0x55);
2799                 if (retval != ERROR_OK)
2800                 {
2801                         /*
2802                          * Spansion S29WS-N CFI query fix is to try 0x555 if 0x55 fails. Should
2803                          * be harmless enough:
2804                          *
2805                          * http://www.infradead.org/pipermail/linux-mtd/2005-September/013618.html
2806                          */
2807                         LOG_USER("Try workaround w/0x555 instead of 0x55 to get QRY.");
2808                         retval = cfi_query_string(bank, 0x555);
2809                 }
2810                 if (retval != ERROR_OK)
2811                         return retval;
2812
2813                 retval = cfi_query_u16(bank, 0, 0x13, &cfi_info->pri_id);
2814                 if (retval != ERROR_OK)
2815                         return retval;
2816                 retval = cfi_query_u16(bank, 0, 0x15, &cfi_info->pri_addr);
2817                 if (retval != ERROR_OK)
2818                         return retval;
2819                 retval = cfi_query_u16(bank, 0, 0x17, &cfi_info->alt_id);
2820                 if (retval != ERROR_OK)
2821                         return retval;
2822                 retval = cfi_query_u16(bank, 0, 0x19, &cfi_info->alt_addr);
2823                 if (retval != ERROR_OK)
2824                         return retval;
2825
2826                 LOG_DEBUG("qry: '%c%c%c', pri_id: 0x%4.4x, pri_addr: 0x%4.4x, alt_id: "
2827                                 "0x%4.4x, alt_addr: 0x%4.4x", cfi_info->qry[0], cfi_info->qry[1],
2828                                 cfi_info->qry[2], cfi_info->pri_id, cfi_info->pri_addr,
2829                                 cfi_info->alt_id, cfi_info->alt_addr);
2830
2831                 retval = cfi_query_u8(bank, 0, 0x1b, &cfi_info->vcc_min);
2832                 if (retval != ERROR_OK)
2833                         return retval;
2834                 retval = cfi_query_u8(bank, 0, 0x1c, &cfi_info->vcc_max);
2835                 if (retval != ERROR_OK)
2836                         return retval;
2837                 retval = cfi_query_u8(bank, 0, 0x1d, &cfi_info->vpp_min);
2838                 if (retval != ERROR_OK)
2839                         return retval;
2840                 retval = cfi_query_u8(bank, 0, 0x1e, &cfi_info->vpp_max);
2841                 if (retval != ERROR_OK)
2842                         return retval;
2843
2844                 retval = cfi_query_u8(bank, 0, 0x1f, &cfi_info->word_write_timeout_typ);
2845                 if (retval != ERROR_OK)
2846                         return retval;
2847                 retval = cfi_query_u8(bank, 0, 0x20, &cfi_info->buf_write_timeout_typ);
2848                 if (retval != ERROR_OK)
2849                         return retval;
2850                 retval = cfi_query_u8(bank, 0, 0x21, &cfi_info->block_erase_timeout_typ);
2851                 if (retval != ERROR_OK)
2852                         return retval;
2853                 retval = cfi_query_u8(bank, 0, 0x22, &cfi_info->chip_erase_timeout_typ);
2854                 if (retval != ERROR_OK)
2855                         return retval;
2856                 retval = cfi_query_u8(bank, 0, 0x23, &cfi_info->word_write_timeout_max);
2857                 if (retval != ERROR_OK)
2858                         return retval;
2859                 retval = cfi_query_u8(bank, 0, 0x24, &cfi_info->buf_write_timeout_max);
2860                 if (retval != ERROR_OK)
2861                         return retval;
2862                 retval = cfi_query_u8(bank, 0, 0x25, &cfi_info->block_erase_timeout_max);
2863                 if (retval != ERROR_OK)
2864                         return retval;
2865                 retval = cfi_query_u8(bank, 0, 0x26, &cfi_info->chip_erase_timeout_max);
2866                 if (retval != ERROR_OK)
2867                         return retval;
2868
2869                 uint8_t data;
2870                 retval = cfi_query_u8(bank, 0, 0x27, &data);
2871                 if (retval != ERROR_OK)
2872                         return retval;
2873                 cfi_info->dev_size = 1 << data;
2874
2875                 retval = cfi_query_u16(bank, 0, 0x28, &cfi_info->interface_desc);
2876                 if (retval != ERROR_OK)
2877                         return retval;
2878                 retval = cfi_query_u16(bank, 0, 0x2a, &cfi_info->max_buf_write_size);
2879                 if (retval != ERROR_OK)
2880                         return retval;
2881                 retval = cfi_query_u8(bank, 0, 0x2c, &cfi_info->num_erase_regions);
2882                 if (retval != ERROR_OK)
2883                         return retval;
2884
2885                 LOG_DEBUG("size: 0x%" PRIx32 ", interface desc: %i, max buffer write size: 0x%x",
2886                                 cfi_info->dev_size, cfi_info->interface_desc, (1 << cfi_info->max_buf_write_size));
2887
2888                 if (cfi_info->num_erase_regions)
2889                 {
2890                         cfi_info->erase_region_info = malloc(sizeof(*cfi_info->erase_region_info)
2891                                         * cfi_info->num_erase_regions);
2892                         for (i = 0; i < cfi_info->num_erase_regions; i++)
2893                         {
2894                                 retval = cfi_query_u32(bank, 0, 0x2d + (4 * i), &cfi_info->erase_region_info[i]);
2895                                 if (retval != ERROR_OK)
2896                                         return retval;
2897                                 LOG_DEBUG("erase region[%i]: %" PRIu32 " blocks of size 0x%" PRIx32 "", i,
2898                                                 (cfi_info->erase_region_info[i] & 0xffff) + 1,
2899                                                 (cfi_info->erase_region_info[i] >> 16) * 256);
2900                         }
2901                 }
2902                 else
2903                 {
2904                         cfi_info->erase_region_info = NULL;
2905                 }
2906
2907                 /* We need to read the primary algorithm extended query table before calculating
2908                  * the sector layout to be able to apply fixups
2909                  */
2910                 switch (cfi_info->pri_id)
2911                 {
2912                         /* Intel command set (standard and extended) */
2913                         case 0x0001:
2914                         case 0x0003:
2915                                 cfi_read_intel_pri_ext(bank);
2916                                 break;
2917                         /* AMD/Spansion, Atmel, ... command set */
2918                         case 0x0002:
2919                                 cfi_info->status_poll_mask = CFI_STATUS_POLL_MASK_DQ5_DQ6_DQ7; /* default for all CFI flashs */
2920                                 cfi_read_0002_pri_ext(bank);
2921                                 break;
2922                         default:
2923                                 LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2924                                 break;
2925                 }
2926
2927                 /* return to read array mode
2928                  * we use both reset commands, as some Intel flashes fail to recognize the 0xF0 command
2929                  */
2930                 if ((retval = cfi_reset(bank)) != ERROR_OK)
2931                 {
2932                         return retval;
2933                 }
2934         } /* end CFI case */
2935
2936         LOG_DEBUG("Vcc min: %x.%x, Vcc max: %x.%x, Vpp min: %u.%x, Vpp max: %u.%x",
2937                 (cfi_info->vcc_min & 0xf0) >> 4, cfi_info->vcc_min & 0x0f,
2938                 (cfi_info->vcc_max & 0xf0) >> 4, cfi_info->vcc_max & 0x0f,
2939                 (cfi_info->vpp_min & 0xf0) >> 4, cfi_info->vpp_min & 0x0f,
2940                 (cfi_info->vpp_max & 0xf0) >> 4, cfi_info->vpp_max & 0x0f);
2941
2942         LOG_DEBUG("typ. word write timeout: %u us, typ. buf write timeout: %u us, "
2943                         "typ. block erase timeout: %u ms, typ. chip erase timeout: %u ms",
2944                         1 << cfi_info->word_write_timeout_typ, 1 << cfi_info->buf_write_timeout_typ,
2945                         1 << cfi_info->block_erase_timeout_typ, 1 << cfi_info->chip_erase_timeout_typ);
2946
2947         LOG_DEBUG("max. word write timeout: %u us, max. buf write timeout: %u us, "
2948                         "max. block erase timeout: %u ms, max. chip erase timeout: %u ms",
2949                         (1 << cfi_info->word_write_timeout_max) * (1 << cfi_info->word_write_timeout_typ),
2950                         (1 << cfi_info->buf_write_timeout_max) * (1 << cfi_info->buf_write_timeout_typ),
2951                         (1 << cfi_info->block_erase_timeout_max) * (1 << cfi_info->block_erase_timeout_typ),
2952                         (1 << cfi_info->chip_erase_timeout_max) * (1 << cfi_info->chip_erase_timeout_typ));
2953
2954         /* convert timeouts to real values in ms */
2955         cfi_info->word_write_timeout = DIV_ROUND_UP((1L << cfi_info->word_write_timeout_typ) *
2956                                 (1L << cfi_info->word_write_timeout_max), 1000);
2957         cfi_info->buf_write_timeout = DIV_ROUND_UP((1L << cfi_info->buf_write_timeout_typ) *
2958                                 (1L << cfi_info->buf_write_timeout_max), 1000);
2959         cfi_info->block_erase_timeout = (1L << cfi_info->block_erase_timeout_typ) *
2960                                 (1L << cfi_info->block_erase_timeout_max);
2961         cfi_info->chip_erase_timeout = (1L << cfi_info->chip_erase_timeout_typ) *
2962                                 (1L << cfi_info->chip_erase_timeout_max);
2963
2964         LOG_DEBUG("calculated word write timeout: %u ms, buf write timeout: %u ms, "
2965                         "block erase timeout: %u ms, chip erase timeout: %u ms",
2966                         cfi_info->word_write_timeout, cfi_info->buf_write_timeout,
2967                         cfi_info->block_erase_timeout, cfi_info->chip_erase_timeout);
2968
2969         /* apply fixups depending on the primary command set */
2970         switch (cfi_info->pri_id)
2971         {
2972                 /* Intel command set (standard and extended) */
2973                 case 0x0001:
2974                 case 0x0003:
2975                         cfi_fixup(bank, cfi_0001_fixups);
2976                         break;
2977                 /* AMD/Spansion, Atmel, ... command set */
2978                 case 0x0002:
2979                         cfi_fixup(bank, cfi_0002_fixups);
2980                         break;
2981                 default:
2982                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2983                         break;
2984         }
2985
2986         if ((cfi_info->dev_size * bank->bus_width / bank->chip_width) != bank->size)
2987         {
2988                 LOG_WARNING("configuration specifies 0x%" PRIx32 " size, but a 0x%" PRIx32
2989                                 " size flash was found", bank->size, cfi_info->dev_size);
2990         }
2991
2992         if (cfi_info->num_erase_regions == 0)
2993         {
2994                 /* a device might have only one erase block, spanning the whole device */
2995                 bank->num_sectors = 1;
2996                 bank->sectors = malloc(sizeof(struct flash_sector));
2997
2998                 bank->sectors[sector].offset = 0x0;
2999                 bank->sectors[sector].size = bank->size;
3000                 bank->sectors[sector].is_erased = -1;
3001                 bank->sectors[sector].is_protected = -1;
3002         }
3003         else
3004         {
3005                 uint32_t offset = 0;
3006
3007                 for (i = 0; i < cfi_info->num_erase_regions; i++)
3008                 {
3009                         num_sectors += (cfi_info->erase_region_info[i] & 0xffff) + 1;
3010                 }
3011
3012                 bank->num_sectors = num_sectors;
3013                 bank->sectors = malloc(sizeof(struct flash_sector) * num_sectors);
3014
3015                 for (i = 0; i < cfi_info->num_erase_regions; i++)
3016                 {
3017                         uint32_t j;
3018                         for (j = 0; j < (cfi_info->erase_region_info[i] & 0xffff) + 1; j++)
3019                         {
3020                                 bank->sectors[sector].offset = offset;
3021                                 bank->sectors[sector].size = ((cfi_info->erase_region_info[i] >> 16) * 256)
3022                                                 * bank->bus_width / bank->chip_width;
3023                                 offset += bank->sectors[sector].size;
3024                                 bank->sectors[sector].is_erased = -1;
3025                                 bank->sectors[sector].is_protected = -1;
3026                                 sector++;
3027                         }
3028                 }
3029                 if (offset != (cfi_info->dev_size * bank->bus_width / bank->chip_width))
3030                 {
3031                         LOG_WARNING("CFI size is 0x%" PRIx32 ", but total sector size is 0x%" PRIx32 "", \
3032                                 (cfi_info->dev_size * bank->bus_width / bank->chip_width), offset);
3033                 }
3034         }
3035
3036         cfi_info->probed = 1;
3037
3038         return ERROR_OK;
3039 }
3040
3041 static int cfi_auto_probe(struct flash_bank *bank)
3042 {
3043         struct cfi_flash_bank *cfi_info = bank->driver_priv;
3044         if (cfi_info->probed)
3045                 return ERROR_OK;
3046         return cfi_probe(bank);
3047 }
3048
3049 static int cfi_intel_protect_check(struct flash_bank *bank)
3050 {
3051         int retval;
3052         struct cfi_flash_bank *cfi_info = bank->driver_priv;
3053         struct cfi_intel_pri_ext *pri_ext = cfi_info->pri_ext;
3054         int i;
3055
3056         /* check if block lock bits are supported on this device */
3057         if (!(pri_ext->blk_status_reg_mask & 0x1))
3058                 return ERROR_FLASH_OPERATION_FAILED;
3059
3060         if ((retval = cfi_send_command(bank, 0x90, flash_address(bank, 0, 0x55))) != ERROR_OK)
3061         {
3062                 return retval;
3063         }
3064
3065         for (i = 0; i < bank->num_sectors; i++)
3066         {
3067                 uint8_t block_status;
3068                 retval = cfi_get_u8(bank, i, 0x2, &block_status);
3069                 if (retval != ERROR_OK)
3070                         return retval;
3071
3072                 if (block_status & 1)
3073                         bank->sectors[i].is_protected = 1;
3074                 else
3075                         bank->sectors[i].is_protected = 0;
3076         }
3077
3078         return cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0));
3079 }
3080
3081 static int cfi_spansion_protect_check(struct flash_bank *bank)
3082 {
3083         int retval;
3084         struct cfi_flash_bank *cfi_info = bank->driver_priv;
3085         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
3086         int i;
3087
3088         if ((retval = cfi_send_command(bank, 0xaa,
3089                         flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
3090         {
3091                 return retval;
3092         }
3093
3094         if ((retval = cfi_send_command(bank, 0x55,
3095                         flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
3096         {
3097                 return retval;
3098         }
3099
3100         if ((retval = cfi_send_command(bank, 0x90,
3101                         flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
3102         {
3103                 return retval;
3104         }
3105
3106         for (i = 0; i < bank->num_sectors; i++)
3107         {
3108                 uint8_t block_status;
3109                 retval = cfi_get_u8(bank, i, 0x2, &block_status);
3110                 if (retval != ERROR_OK)
3111                         return retval;
3112
3113                 if (block_status & 1)
3114                         bank->sectors[i].is_protected = 1;
3115                 else
3116                         bank->sectors[i].is_protected = 0;
3117         }
3118
3119         return cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0));
3120 }
3121
3122 static int cfi_protect_check(struct flash_bank *bank)
3123 {
3124         struct cfi_flash_bank *cfi_info = bank->driver_priv;
3125
3126         if (bank->target->state != TARGET_HALTED)
3127         {
3128                 LOG_ERROR("Target not halted");
3129                 return ERROR_TARGET_NOT_HALTED;
3130         }
3131
3132         if (cfi_info->qry[0] != 'Q')
3133                 return ERROR_FLASH_BANK_NOT_PROBED;
3134
3135         switch (cfi_info->pri_id)
3136         {
3137                 case 1:
3138                 case 3:
3139                         return cfi_intel_protect_check(bank);
3140                         break;
3141                 case 2:
3142                         return cfi_spansion_protect_check(bank);
3143                         break;
3144                 default:
3145                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
3146                         break;
3147         }
3148
3149         return ERROR_OK;
3150 }
3151
3152 static int get_cfi_info(struct flash_bank *bank, char *buf, int buf_size)
3153 {
3154         int printed;
3155         struct cfi_flash_bank *cfi_info = bank->driver_priv;
3156
3157         if (cfi_info->qry[0] == 0xff)
3158         {
3159                 snprintf(buf, buf_size, "\ncfi flash bank not probed yet\n");
3160                 return ERROR_OK;
3161         }
3162
3163         if (cfi_info->not_cfi == 0)
3164                 printed = snprintf(buf, buf_size, "\nCFI flash: ");
3165         else
3166                 printed = snprintf(buf, buf_size, "\nnon-CFI flash: ");
3167         buf += printed;
3168         buf_size -= printed;
3169
3170         printed = snprintf(buf, buf_size, "mfr: 0x%4.4x, id:0x%4.4x\n\n",
3171                 cfi_info->manufacturer, cfi_info->device_id);
3172         buf += printed;
3173         buf_size -= printed;
3174
3175         printed = snprintf(buf, buf_size, "qry: '%c%c%c', pri_id: 0x%4.4x, pri_addr: "
3176                         "0x%4.4x, alt_id: 0x%4.4x, alt_addr: 0x%4.4x\n",
3177                         cfi_info->qry[0], cfi_info->qry[1], cfi_info->qry[2],
3178                         cfi_info->pri_id, cfi_info->pri_addr, cfi_info->alt_id, cfi_info->alt_addr);
3179         buf += printed;
3180         buf_size -= printed;
3181
3182         printed = snprintf(buf, buf_size, "Vcc min: %x.%x, Vcc max: %x.%x, "
3183                         "Vpp min: %u.%x, Vpp max: %u.%x\n",
3184                         (cfi_info->vcc_min & 0xf0) >> 4, cfi_info->vcc_min & 0x0f,
3185                         (cfi_info->vcc_max & 0xf0) >> 4, cfi_info->vcc_max & 0x0f,
3186                         (cfi_info->vpp_min & 0xf0) >> 4, cfi_info->vpp_min & 0x0f,
3187                         (cfi_info->vpp_max & 0xf0) >> 4, cfi_info->vpp_max & 0x0f);
3188         buf += printed;
3189         buf_size -= printed;
3190
3191         printed = snprintf(buf, buf_size, "typ. word write timeout: %u us, "
3192                         "typ. buf write timeout: %u us, "
3193                         "typ. block erase timeout: %u ms, "
3194                         "typ. chip erase timeout: %u ms\n",
3195                         1 << cfi_info->word_write_timeout_typ,
3196                         1 << cfi_info->buf_write_timeout_typ,
3197                         1 << cfi_info->block_erase_timeout_typ,
3198                         1 << cfi_info->chip_erase_timeout_typ);
3199         buf += printed;
3200         buf_size -= printed;
3201
3202         printed = snprintf(buf, buf_size, "max. word write timeout: %u us, "
3203                         "max. buf write timeout: %u us, max. "
3204                         "block erase timeout: %u ms, max. chip erase timeout: %u ms\n",
3205                         (1 << cfi_info->word_write_timeout_max) * (1 << cfi_info->word_write_timeout_typ),
3206                         (1 << cfi_info->buf_write_timeout_max) * (1 << cfi_info->buf_write_timeout_typ),
3207                         (1 << cfi_info->block_erase_timeout_max) * (1 << cfi_info->block_erase_timeout_typ),
3208                         (1 << cfi_info->chip_erase_timeout_max) * (1 << cfi_info->chip_erase_timeout_typ));
3209         buf += printed;
3210         buf_size -= printed;
3211
3212         printed = snprintf(buf, buf_size, "size: 0x%" PRIx32 ", interface desc: %i, "
3213                         "max buffer write size: 0x%x\n",
3214                         cfi_info->dev_size,
3215                         cfi_info->interface_desc,
3216                         1 << cfi_info->max_buf_write_size);
3217         buf += printed;
3218         buf_size -= printed;
3219
3220         switch (cfi_info->pri_id)
3221         {
3222                 case 1:
3223                 case 3:
3224                         cfi_intel_info(bank, buf, buf_size);
3225                         break;
3226                 case 2:
3227                         cfi_spansion_info(bank, buf, buf_size);
3228                         break;
3229                 default:
3230                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
3231                         break;
3232         }
3233
3234         return ERROR_OK;
3235 }
3236
3237 static void cfi_fixup_0002_write_buffer(struct flash_bank *bank, void *param)
3238 {
3239         struct cfi_flash_bank *cfi_info = bank->driver_priv;
3240
3241         /* disable write buffer for M29W128G */
3242         cfi_info->buf_write_timeout_typ = 0;
3243 }
3244
3245 struct flash_driver cfi_flash = {
3246         .name = "cfi",
3247         .flash_bank_command = cfi_flash_bank_command,
3248         .erase = cfi_erase,
3249         .protect = cfi_protect,
3250         .write = cfi_write,
3251         .read = cfi_read,
3252         .probe = cfi_probe,
3253         .auto_probe = cfi_auto_probe,
3254         /* FIXME: access flash at bus_width size */
3255         .erase_check = default_flash_blank_check,
3256         .protect_check = cfi_protect_check,
3257         .info = get_cfi_info,
3258 };