cfi: fix GDB keep alive bug
[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 <helper/binarybuffer.h>
33 #include <target/algorithm.h>
34
35
36 #define CFI_MAX_BUS_WIDTH       4
37 #define CFI_MAX_CHIP_WIDTH      4
38
39 /* defines internal maximum size for code fragment in cfi_intel_write_block() */
40 #define CFI_MAX_INTEL_CODESIZE 256
41
42 static struct cfi_unlock_addresses cfi_unlock_addresses[] =
43 {
44         [CFI_UNLOCK_555_2AA] = { .unlock1 = 0x555, .unlock2 = 0x2aa },
45         [CFI_UNLOCK_5555_2AAA] = { .unlock1 = 0x5555, .unlock2 = 0x2aaa },
46 };
47
48 /* CFI fixups foward declarations */
49 static void cfi_fixup_0002_erase_regions(struct flash_bank *flash, void *param);
50 static void cfi_fixup_0002_unlock_addresses(struct flash_bank *flash, void *param);
51 static void cfi_fixup_atmel_reversed_erase_regions(struct flash_bank *flash, void *param);
52
53 /* fixup after reading cmdset 0002 primary query table */
54 static const struct cfi_fixup cfi_0002_fixups[] = {
55         {CFI_MFR_SST, 0x00D4, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
56         {CFI_MFR_SST, 0x00D5, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
57         {CFI_MFR_SST, 0x00D6, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
58         {CFI_MFR_SST, 0x00D7, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
59         {CFI_MFR_SST, 0x2780, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
60         {CFI_MFR_ATMEL, 0x00C8, cfi_fixup_atmel_reversed_erase_regions, NULL},
61    {CFI_MFR_FUJITSU, 0x22ea, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
62         {CFI_MFR_FUJITSU, 0x226b, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_5555_2AAA]},
63         {CFI_MFR_AMIC, 0xb31a, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
64         {CFI_MFR_MX, 0x225b, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
65         {CFI_MFR_AMD, 0x225b, cfi_fixup_0002_unlock_addresses, &cfi_unlock_addresses[CFI_UNLOCK_555_2AA]},
66         {CFI_MFR_ANY, CFI_ID_ANY, cfi_fixup_0002_erase_regions, NULL},
67         {0, 0, NULL, NULL}
68 };
69
70 /* fixup after reading cmdset 0001 primary query table */
71 static const struct cfi_fixup cfi_0001_fixups[] = {
72         {0, 0, NULL, NULL}
73 };
74
75 static void cfi_fixup(struct flash_bank *bank, const struct cfi_fixup *fixups)
76 {
77         struct cfi_flash_bank *cfi_info = bank->driver_priv;
78         const struct cfi_fixup *f;
79
80         for (f = fixups; f->fixup; f++)
81         {
82                 if (((f->mfr == CFI_MFR_ANY) || (f->mfr == cfi_info->manufacturer)) &&
83                         ((f->id  == CFI_ID_ANY)  || (f->id  == cfi_info->device_id)))
84                 {
85                         f->fixup(bank, f->param);
86                 }
87         }
88 }
89
90 /* inline uint32_t flash_address(struct flash_bank *bank, int sector, uint32_t offset) */
91 static __inline__ uint32_t flash_address(struct flash_bank *bank, int sector, uint32_t offset)
92 {
93         struct cfi_flash_bank *cfi_info = bank->driver_priv;
94
95         if (cfi_info->x16_as_x8) offset *= 2;
96
97         /* while the sector list isn't built, only accesses to sector 0 work */
98         if (sector == 0)
99                 return bank->base + offset * bank->bus_width;
100         else
101         {
102                 if (!bank->sectors)
103                 {
104                         LOG_ERROR("BUG: sector list not yet built");
105                         exit(-1);
106                 }
107                 return bank->base + bank->sectors[sector].offset + offset * bank->bus_width;
108         }
109 }
110
111 static void cfi_command(struct flash_bank *bank, uint8_t cmd, uint8_t *cmd_buf)
112 {
113         int i;
114
115         /* clear whole buffer, to ensure bits that exceed the bus_width
116          * are set to zero
117          */
118         for (i = 0; i < CFI_MAX_BUS_WIDTH; i++)
119                 cmd_buf[i] = 0;
120
121         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
122         {
123                 for (i = bank->bus_width; i > 0; i--)
124                 {
125                         *cmd_buf++ = (i & (bank->chip_width - 1)) ? 0x0 : cmd;
126                 }
127         }
128         else
129         {
130                 for (i = 1; i <= bank->bus_width; i++)
131                 {
132                         *cmd_buf++ = (i & (bank->chip_width - 1)) ? 0x0 : cmd;
133                 }
134         }
135 }
136
137 static int cfi_send_command(struct flash_bank *bank, uint8_t cmd, uint32_t address)
138 {
139     uint8_t command[CFI_MAX_BUS_WIDTH];
140
141     cfi_command(bank, cmd, command);
142     return target_write_memory(bank->target, address, bank->bus_width, 1, command);
143 }
144
145 /* read unsigned 8-bit value from the bank
146  * flash banks are expected to be made of similar chips
147  * the query result should be the same for all
148  */
149 static uint8_t cfi_query_u8(struct flash_bank *bank, int sector, uint32_t offset)
150 {
151         struct target *target = bank->target;
152         uint8_t data[CFI_MAX_BUS_WIDTH];
153
154         target_read_memory(target, flash_address(bank, sector, offset), bank->bus_width, 1, data);
155
156         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
157                 return data[0];
158         else
159                 return data[bank->bus_width - 1];
160 }
161
162 /* read unsigned 8-bit value from the bank
163  * in case of a bank made of multiple chips,
164  * the individual values are ORed
165  */
166 static uint8_t cfi_get_u8(struct flash_bank *bank, int sector, uint32_t offset)
167 {
168         struct target *target = bank->target;
169         uint8_t data[CFI_MAX_BUS_WIDTH];
170         int i;
171
172         target_read_memory(target, flash_address(bank, sector, offset), bank->bus_width, 1, data);
173
174         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
175         {
176                 for (i = 0; i < bank->bus_width / bank->chip_width; i++)
177                         data[0] |= data[i];
178
179                 return data[0];
180         }
181         else
182         {
183                 uint8_t value = 0;
184                 for (i = 0; i < bank->bus_width / bank->chip_width; i++)
185                         value |= data[bank->bus_width - 1 - i];
186
187                 return value;
188         }
189 }
190
191 static uint16_t cfi_query_u16(struct flash_bank *bank, int sector, uint32_t offset)
192 {
193         struct target *target = bank->target;
194         struct cfi_flash_bank *cfi_info = bank->driver_priv;
195         uint8_t data[CFI_MAX_BUS_WIDTH * 2];
196
197         if (cfi_info->x16_as_x8)
198         {
199                 uint8_t i;
200                 for (i = 0;i < 2;i++)
201                         target_read_memory(target, flash_address(bank, sector, offset + i), bank->bus_width, 1,
202                                 &data[i*bank->bus_width]);
203         }
204         else
205                 target_read_memory(target, flash_address(bank, sector, offset), bank->bus_width, 2, data);
206
207         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
208                 return data[0] | data[bank->bus_width] << 8;
209         else
210                 return data[bank->bus_width - 1] | data[(2 * bank->bus_width) - 1] << 8;
211 }
212
213 static uint32_t cfi_query_u32(struct flash_bank *bank, int sector, uint32_t offset)
214 {
215         struct target *target = bank->target;
216         struct cfi_flash_bank *cfi_info = bank->driver_priv;
217         uint8_t data[CFI_MAX_BUS_WIDTH * 4];
218
219         if (cfi_info->x16_as_x8)
220         {
221                 uint8_t i;
222                 for (i = 0;i < 4;i++)
223                         target_read_memory(target, flash_address(bank, sector, offset + i), bank->bus_width, 1,
224                                 &data[i*bank->bus_width]);
225         }
226         else
227                 target_read_memory(target, flash_address(bank, sector, offset), bank->bus_width, 4, data);
228
229         if (bank->target->endianness == TARGET_LITTLE_ENDIAN)
230                 return data[0] | data[bank->bus_width] << 8 | data[bank->bus_width * 2] << 16 | data[bank->bus_width * 3] << 24;
231         else
232                 return data[bank->bus_width - 1] | data[(2* bank->bus_width) - 1] << 8 |
233                                 data[(3 * bank->bus_width) - 1] << 16 | data[(4 * bank->bus_width) - 1] << 24;
234 }
235
236 static int cfi_reset(struct flash_bank *bank)
237 {
238         struct cfi_flash_bank *cfi_info = bank->driver_priv;
239         int retval = ERROR_OK;
240
241         if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
242         {
243                 return retval;
244         }
245
246         if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
247         {
248                 return retval;
249         }
250
251         if (cfi_info->manufacturer == 0x20 &&
252                         (cfi_info->device_id == 0x227E || cfi_info->device_id == 0x7E))
253         {
254                 /* Numonix M29W128G is cmd 0xFF intolerant - causes internal undefined state
255                  * so we send an extra 0xF0 reset to fix the bug */
256                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x00))) != ERROR_OK)
257                 {
258                         return retval;
259                 }
260         }
261
262         return retval;
263 }
264
265 static void cfi_intel_clear_status_register(struct flash_bank *bank)
266 {
267         struct target *target = bank->target;
268
269         if (target->state != TARGET_HALTED)
270         {
271                 LOG_ERROR("BUG: attempted to clear status register while target wasn't halted");
272                 exit(-1);
273         }
274
275         cfi_send_command(bank, 0x50, flash_address(bank, 0, 0x0));
276 }
277
278 static uint8_t cfi_intel_wait_status_busy(struct flash_bank *bank, int timeout)
279 {
280         uint8_t status;
281
282         while ((!((status = cfi_get_u8(bank, 0, 0x0)) & 0x80)) && (timeout-- > 0))
283         {
284                 LOG_DEBUG("status: 0x%x", status);
285                 alive_sleep(1);
286         }
287
288         /* mask out bit 0 (reserved) */
289         status = status & 0xfe;
290
291         LOG_DEBUG("status: 0x%x", status);
292
293         if ((status & 0x80) != 0x80)
294         {
295                 LOG_ERROR("timeout while waiting for WSM to become ready");
296         }
297         else if (status != 0x80)
298         {
299                 LOG_ERROR("status register: 0x%x", status);
300                 if (status & 0x2)
301                         LOG_ERROR("Block Lock-Bit Detected, Operation Abort");
302                 if (status & 0x4)
303                         LOG_ERROR("Program suspended");
304                 if (status & 0x8)
305                         LOG_ERROR("Low Programming Voltage Detected, Operation Aborted");
306                 if (status & 0x10)
307                         LOG_ERROR("Program Error / Error in Setting Lock-Bit");
308                 if (status & 0x20)
309                         LOG_ERROR("Error in Block Erasure or Clear Lock-Bits");
310                 if (status & 0x40)
311                         LOG_ERROR("Block Erase Suspended");
312
313                 cfi_intel_clear_status_register(bank);
314         }
315
316         return status;
317 }
318
319 static int cfi_spansion_wait_status_busy(struct flash_bank *bank, int timeout)
320 {
321         uint8_t status, oldstatus;
322         struct cfi_flash_bank *cfi_info = bank->driver_priv;
323
324         oldstatus = cfi_get_u8(bank, 0, 0x0);
325
326         do {
327                 status = cfi_get_u8(bank, 0, 0x0);
328                 if ((status ^ oldstatus) & 0x40) {
329                         if (status & cfi_info->status_poll_mask & 0x20) {
330                                 oldstatus = cfi_get_u8(bank, 0, 0x0);
331                                 status = cfi_get_u8(bank, 0, 0x0);
332                                 if ((status ^ oldstatus) & 0x40) {
333                                         LOG_ERROR("dq5 timeout, status: 0x%x", status);
334                                         return(ERROR_FLASH_OPERATION_FAILED);
335                                 } else {
336                                         LOG_DEBUG("status: 0x%x", status);
337                                         return(ERROR_OK);
338                                 }
339                         }
340                 } else { /* no toggle: finished, OK */
341                         LOG_DEBUG("status: 0x%x", status);
342                         return(ERROR_OK);
343                 }
344
345                 oldstatus = status;
346                 alive_sleep(1);
347         } while (timeout-- > 0);
348
349         LOG_ERROR("timeout, status: 0x%x", status);
350
351         return(ERROR_FLASH_BUSY);
352 }
353
354 static int cfi_read_intel_pri_ext(struct flash_bank *bank)
355 {
356         int retval;
357         struct cfi_flash_bank *cfi_info = bank->driver_priv;
358         struct cfi_intel_pri_ext *pri_ext;
359
360         if (cfi_info->pri_ext)
361                 free(cfi_info->pri_ext);
362
363         pri_ext = malloc(sizeof(struct cfi_intel_pri_ext));
364         if (pri_ext == NULL)
365         {
366                 LOG_ERROR("Out of memory");
367                 return ERROR_FAIL;
368         }
369         cfi_info->pri_ext = pri_ext;
370
371         pri_ext->pri[0] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0);
372         pri_ext->pri[1] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 1);
373         pri_ext->pri[2] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 2);
374
375         if ((pri_ext->pri[0] != 'P') || (pri_ext->pri[1] != 'R') || (pri_ext->pri[2] != 'I'))
376         {
377                 if ((retval = cfi_reset(bank)) != ERROR_OK)
378                 {
379                         return retval;
380                 }
381                 LOG_ERROR("Could not read bank flash bank information");
382                 return ERROR_FLASH_BANK_INVALID;
383         }
384
385         pri_ext->major_version = cfi_query_u8(bank, 0, cfi_info->pri_addr + 3);
386         pri_ext->minor_version = cfi_query_u8(bank, 0, cfi_info->pri_addr + 4);
387
388         LOG_DEBUG("pri: '%c%c%c', version: %c.%c", pri_ext->pri[0], pri_ext->pri[1], pri_ext->pri[2], pri_ext->major_version, pri_ext->minor_version);
389
390         pri_ext->feature_support = cfi_query_u32(bank, 0, cfi_info->pri_addr + 5);
391         pri_ext->suspend_cmd_support = cfi_query_u8(bank, 0, cfi_info->pri_addr + 9);
392         pri_ext->blk_status_reg_mask = cfi_query_u16(bank, 0, cfi_info->pri_addr + 0xa);
393
394         LOG_DEBUG("feature_support: 0x%" PRIx32 ", suspend_cmd_support: 0x%x, blk_status_reg_mask: 0x%x",
395                   pri_ext->feature_support,
396                   pri_ext->suspend_cmd_support,
397                   pri_ext->blk_status_reg_mask);
398
399         pri_ext->vcc_optimal = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0xc);
400         pri_ext->vpp_optimal = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0xd);
401
402         LOG_DEBUG("Vcc opt: %x.%x, Vpp opt: %u.%x",
403                   (pri_ext->vcc_optimal & 0xf0) >> 4, pri_ext->vcc_optimal & 0x0f,
404                   (pri_ext->vpp_optimal & 0xf0) >> 4, pri_ext->vpp_optimal & 0x0f);
405
406         pri_ext->num_protection_fields = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0xe);
407         if (pri_ext->num_protection_fields != 1)
408         {
409                 LOG_WARNING("expected one protection register field, but found %i", pri_ext->num_protection_fields);
410         }
411
412         pri_ext->prot_reg_addr = cfi_query_u16(bank, 0, cfi_info->pri_addr + 0xf);
413         pri_ext->fact_prot_reg_size = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0x11);
414         pri_ext->user_prot_reg_size = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0x12);
415
416         LOG_DEBUG("protection_fields: %i, prot_reg_addr: 0x%x, factory pre-programmed: %i, user programmable: %i", pri_ext->num_protection_fields, pri_ext->prot_reg_addr, 1 << pri_ext->fact_prot_reg_size, 1 << pri_ext->user_prot_reg_size);
417
418         return ERROR_OK;
419 }
420
421 static int cfi_read_spansion_pri_ext(struct flash_bank *bank)
422 {
423         int retval;
424         struct cfi_flash_bank *cfi_info = bank->driver_priv;
425         struct cfi_spansion_pri_ext *pri_ext;
426
427         if (cfi_info->pri_ext)
428                 free(cfi_info->pri_ext);
429
430         pri_ext = malloc(sizeof(struct cfi_spansion_pri_ext));
431         if (pri_ext == NULL)
432         {
433                 LOG_ERROR("Out of memory");
434                 return ERROR_FAIL;
435         }
436         cfi_info->pri_ext = pri_ext;
437
438         pri_ext->pri[0] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0);
439         pri_ext->pri[1] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 1);
440         pri_ext->pri[2] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 2);
441
442         if ((pri_ext->pri[0] != 'P') || (pri_ext->pri[1] != 'R') || (pri_ext->pri[2] != 'I'))
443         {
444                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
445                 {
446                         return retval;
447                 }
448                 LOG_ERROR("Could not read spansion bank information");
449                 return ERROR_FLASH_BANK_INVALID;
450         }
451
452         pri_ext->major_version = cfi_query_u8(bank, 0, cfi_info->pri_addr + 3);
453         pri_ext->minor_version = cfi_query_u8(bank, 0, cfi_info->pri_addr + 4);
454
455         LOG_DEBUG("pri: '%c%c%c', version: %c.%c", pri_ext->pri[0], pri_ext->pri[1], pri_ext->pri[2], pri_ext->major_version, pri_ext->minor_version);
456
457         pri_ext->SiliconRevision = cfi_query_u8(bank, 0, cfi_info->pri_addr + 5);
458         pri_ext->EraseSuspend    = cfi_query_u8(bank, 0, cfi_info->pri_addr + 6);
459         pri_ext->BlkProt         = cfi_query_u8(bank, 0, cfi_info->pri_addr + 7);
460         pri_ext->TmpBlkUnprotect = cfi_query_u8(bank, 0, cfi_info->pri_addr + 8);
461         pri_ext->BlkProtUnprot   = cfi_query_u8(bank, 0, cfi_info->pri_addr + 9);
462         pri_ext->SimultaneousOps = cfi_query_u8(bank, 0, cfi_info->pri_addr + 10);
463         pri_ext->BurstMode       = cfi_query_u8(bank, 0, cfi_info->pri_addr + 11);
464         pri_ext->PageMode        = cfi_query_u8(bank, 0, cfi_info->pri_addr + 12);
465         pri_ext->VppMin          = cfi_query_u8(bank, 0, cfi_info->pri_addr + 13);
466         pri_ext->VppMax          = cfi_query_u8(bank, 0, cfi_info->pri_addr + 14);
467         pri_ext->TopBottom       = cfi_query_u8(bank, 0, cfi_info->pri_addr + 15);
468
469         LOG_DEBUG("Silicon Revision: 0x%x, Erase Suspend: 0x%x, Block protect: 0x%x", pri_ext->SiliconRevision,
470               pri_ext->EraseSuspend, pri_ext->BlkProt);
471
472         LOG_DEBUG("Temporary Unprotect: 0x%x, Block Protect Scheme: 0x%x, Simultaneous Ops: 0x%x", pri_ext->TmpBlkUnprotect,
473               pri_ext->BlkProtUnprot, pri_ext->SimultaneousOps);
474
475         LOG_DEBUG("Burst Mode: 0x%x, Page Mode: 0x%x, ", pri_ext->BurstMode, pri_ext->PageMode);
476
477
478         LOG_DEBUG("Vpp min: %u.%x, Vpp max: %u.%x",
479                   (pri_ext->VppMin & 0xf0) >> 4, pri_ext->VppMin & 0x0f,
480                   (pri_ext->VppMax & 0xf0) >> 4, pri_ext->VppMax & 0x0f);
481
482         LOG_DEBUG("WP# protection 0x%x", pri_ext->TopBottom);
483
484         /* default values for implementation specific workarounds */
485         pri_ext->_unlock1 = cfi_unlock_addresses[CFI_UNLOCK_555_2AA].unlock1;
486         pri_ext->_unlock2 = cfi_unlock_addresses[CFI_UNLOCK_555_2AA].unlock2;
487         pri_ext->_reversed_geometry = 0;
488
489         return ERROR_OK;
490 }
491
492 static int cfi_read_atmel_pri_ext(struct flash_bank *bank)
493 {
494         int retval;
495         struct cfi_atmel_pri_ext atmel_pri_ext;
496         struct cfi_flash_bank *cfi_info = bank->driver_priv;
497         struct cfi_spansion_pri_ext *pri_ext;
498
499         if (cfi_info->pri_ext)
500                 free(cfi_info->pri_ext);
501
502         pri_ext = malloc(sizeof(struct cfi_spansion_pri_ext));
503         if (pri_ext == NULL)
504         {
505                 LOG_ERROR("Out of memory");
506                 return ERROR_FAIL;
507         }
508
509         /* ATMEL devices use the same CFI primary command set (0x2) as AMD/Spansion,
510          * but a different primary extended query table.
511          * We read the atmel table, and prepare a valid AMD/Spansion query table.
512          */
513
514         memset(pri_ext, 0, sizeof(struct cfi_spansion_pri_ext));
515
516         cfi_info->pri_ext = pri_ext;
517
518         atmel_pri_ext.pri[0] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 0);
519         atmel_pri_ext.pri[1] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 1);
520         atmel_pri_ext.pri[2] = cfi_query_u8(bank, 0, cfi_info->pri_addr + 2);
521
522         if ((atmel_pri_ext.pri[0] != 'P') || (atmel_pri_ext.pri[1] != 'R') || (atmel_pri_ext.pri[2] != 'I'))
523         {
524                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
525                 {
526                         return retval;
527                 }
528                 LOG_ERROR("Could not read atmel bank information");
529                 return ERROR_FLASH_BANK_INVALID;
530         }
531
532         pri_ext->pri[0] = atmel_pri_ext.pri[0];
533         pri_ext->pri[1] = atmel_pri_ext.pri[1];
534         pri_ext->pri[2] = atmel_pri_ext.pri[2];
535
536         atmel_pri_ext.major_version = cfi_query_u8(bank, 0, cfi_info->pri_addr + 3);
537         atmel_pri_ext.minor_version = cfi_query_u8(bank, 0, cfi_info->pri_addr + 4);
538
539         LOG_DEBUG("pri: '%c%c%c', version: %c.%c", atmel_pri_ext.pri[0], atmel_pri_ext.pri[1], atmel_pri_ext.pri[2], atmel_pri_ext.major_version, atmel_pri_ext.minor_version);
540
541         pri_ext->major_version = atmel_pri_ext.major_version;
542         pri_ext->minor_version = atmel_pri_ext.minor_version;
543
544         atmel_pri_ext.features = cfi_query_u8(bank, 0, cfi_info->pri_addr + 5);
545         atmel_pri_ext.bottom_boot = cfi_query_u8(bank, 0, cfi_info->pri_addr + 6);
546         atmel_pri_ext.burst_mode = cfi_query_u8(bank, 0, cfi_info->pri_addr + 7);
547         atmel_pri_ext.page_mode = cfi_query_u8(bank, 0, cfi_info->pri_addr + 8);
548
549         LOG_DEBUG("features: 0x%2.2x, bottom_boot: 0x%2.2x, burst_mode: 0x%2.2x, page_mode: 0x%2.2x",
550                 atmel_pri_ext.features, atmel_pri_ext.bottom_boot, atmel_pri_ext.burst_mode, atmel_pri_ext.page_mode);
551
552         if (atmel_pri_ext.features & 0x02)
553                 pri_ext->EraseSuspend = 2;
554
555         if (atmel_pri_ext.bottom_boot)
556                 pri_ext->TopBottom = 2;
557         else
558                 pri_ext->TopBottom = 3;
559
560         pri_ext->_unlock1 = cfi_unlock_addresses[CFI_UNLOCK_555_2AA].unlock1;
561         pri_ext->_unlock2 = cfi_unlock_addresses[CFI_UNLOCK_555_2AA].unlock2;
562
563         return ERROR_OK;
564 }
565
566 static int cfi_read_0002_pri_ext(struct flash_bank *bank)
567 {
568         struct cfi_flash_bank *cfi_info = bank->driver_priv;
569
570         if (cfi_info->manufacturer == CFI_MFR_ATMEL)
571         {
572                 return cfi_read_atmel_pri_ext(bank);
573         }
574         else
575         {
576                 return cfi_read_spansion_pri_ext(bank);
577         }
578 }
579
580 static int cfi_spansion_info(struct flash_bank *bank, char *buf, int buf_size)
581 {
582         int printed;
583         struct cfi_flash_bank *cfi_info = bank->driver_priv;
584         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
585
586         printed = snprintf(buf, buf_size, "\nSpansion primary algorithm extend information:\n");
587         buf += printed;
588         buf_size -= printed;
589
590         printed = snprintf(buf, buf_size, "pri: '%c%c%c', version: %c.%c\n", pri_ext->pri[0],
591                            pri_ext->pri[1], pri_ext->pri[2],
592                            pri_ext->major_version, pri_ext->minor_version);
593         buf += printed;
594         buf_size -= printed;
595
596         printed = snprintf(buf, buf_size, "Silicon Rev.: 0x%x, Address Sensitive unlock: 0x%x\n",
597                            (pri_ext->SiliconRevision) >> 2,
598                            (pri_ext->SiliconRevision) & 0x03);
599         buf += printed;
600         buf_size -= printed;
601
602         printed = snprintf(buf, buf_size, "Erase Suspend: 0x%x, Sector Protect: 0x%x\n",
603                            pri_ext->EraseSuspend,
604                            pri_ext->BlkProt);
605         buf += printed;
606         buf_size -= printed;
607
608         printed = snprintf(buf, buf_size, "VppMin: %u.%x, VppMax: %u.%x\n",
609                 (pri_ext->VppMin & 0xf0) >> 4, pri_ext->VppMin & 0x0f,
610                 (pri_ext->VppMax & 0xf0) >> 4, pri_ext->VppMax & 0x0f);
611
612         return ERROR_OK;
613 }
614
615 static int cfi_intel_info(struct flash_bank *bank, char *buf, int buf_size)
616 {
617         int printed;
618         struct cfi_flash_bank *cfi_info = bank->driver_priv;
619         struct cfi_intel_pri_ext *pri_ext = cfi_info->pri_ext;
620
621         printed = snprintf(buf, buf_size, "\nintel primary algorithm extend information:\n");
622         buf += printed;
623         buf_size -= printed;
624
625         printed = snprintf(buf, buf_size, "pri: '%c%c%c', version: %c.%c\n", pri_ext->pri[0], pri_ext->pri[1], pri_ext->pri[2], pri_ext->major_version, pri_ext->minor_version);
626         buf += printed;
627         buf_size -= printed;
628
629         printed = snprintf(buf, buf_size, "feature_support: 0x%" PRIx32 ", suspend_cmd_support: 0x%x, blk_status_reg_mask: 0x%x\n", pri_ext->feature_support, pri_ext->suspend_cmd_support, pri_ext->blk_status_reg_mask);
630         buf += printed;
631         buf_size -= printed;
632
633         printed = snprintf(buf, buf_size, "Vcc opt: %x.%x, Vpp opt: %u.%x\n",
634                 (pri_ext->vcc_optimal & 0xf0) >> 4, pri_ext->vcc_optimal & 0x0f,
635                 (pri_ext->vpp_optimal & 0xf0) >> 4, pri_ext->vpp_optimal & 0x0f);
636         buf += printed;
637         buf_size -= printed;
638
639         printed = snprintf(buf, buf_size, "protection_fields: %i, prot_reg_addr: 0x%x, factory pre-programmed: %i, user programmable: %i\n", pri_ext->num_protection_fields, pri_ext->prot_reg_addr, 1 << pri_ext->fact_prot_reg_size, 1 << pri_ext->user_prot_reg_size);
640
641         return ERROR_OK;
642 }
643
644 /* flash_bank cfi <base> <size> <chip_width> <bus_width> <target#> [options]
645  */
646 FLASH_BANK_COMMAND_HANDLER(cfi_flash_bank_command)
647 {
648         struct cfi_flash_bank *cfi_info;
649
650         if (CMD_ARGC < 6)
651         {
652                 LOG_WARNING("incomplete flash_bank cfi configuration");
653                 return ERROR_FLASH_BANK_INVALID;
654         }
655
656         /* both widths must:
657          * - not exceed max value;
658          * - not be null;
659          * - be equal to a power of 2.
660          * bus must be wide enought to hold one chip */
661         if ((bank->chip_width > CFI_MAX_CHIP_WIDTH)
662                         || (bank->bus_width > CFI_MAX_BUS_WIDTH)
663                         || (bank->chip_width == 0)
664                         || (bank->bus_width == 0)
665                         || (bank->chip_width & (bank->chip_width - 1))
666                         || (bank->bus_width & (bank->bus_width - 1))
667                         || (bank->chip_width > bank->bus_width))
668         {
669                 LOG_ERROR("chip and bus width have to specified in bytes");
670                 return ERROR_FLASH_BANK_INVALID;
671         }
672
673         cfi_info = malloc(sizeof(struct cfi_flash_bank));
674         cfi_info->probed = 0;
675         cfi_info->erase_region_info = 0;
676         cfi_info->pri_ext = NULL;
677         bank->driver_priv = cfi_info;
678
679         cfi_info->write_algorithm = NULL;
680
681         cfi_info->x16_as_x8 = 0;
682         cfi_info->jedec_probe = 0;
683         cfi_info->not_cfi = 0;
684
685         for (unsigned i = 6; i < CMD_ARGC; i++)
686         {
687                 if (strcmp(CMD_ARGV[i], "x16_as_x8") == 0)
688                 {
689                         cfi_info->x16_as_x8 = 1;
690                 }
691                 else if (strcmp(CMD_ARGV[i], "jedec_probe") == 0)
692                 {
693                         cfi_info->jedec_probe = 1;
694                 }
695         }
696
697         cfi_info->write_algorithm = NULL;
698
699         /* bank wasn't probed yet */
700         cfi_info->qry[0] = -1;
701
702         return ERROR_OK;
703 }
704
705 static int cfi_intel_erase(struct flash_bank *bank, int first, int last)
706 {
707         int retval;
708         struct cfi_flash_bank *cfi_info = bank->driver_priv;
709         int i;
710
711         cfi_intel_clear_status_register(bank);
712
713         for (i = first; i <= last; i++)
714         {
715                 if ((retval = cfi_send_command(bank, 0x20, flash_address(bank, i, 0x0))) != ERROR_OK)
716                 {
717                         return retval;
718                 }
719
720                 if ((retval = cfi_send_command(bank, 0xd0, flash_address(bank, i, 0x0))) != ERROR_OK)
721                 {
722                         return retval;
723                 }
724
725                 if (cfi_intel_wait_status_busy(bank, 1000 * (1 << cfi_info->block_erase_timeout_typ)) == 0x80)
726                         bank->sectors[i].is_erased = 1;
727                 else
728                 {
729                         if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
730                         {
731                                 return retval;
732                         }
733
734                         LOG_ERROR("couldn't erase block %i of flash bank at base 0x%" PRIx32 , i, bank->base);
735                         return ERROR_FLASH_OPERATION_FAILED;
736                 }
737         }
738
739         return cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0));
740 }
741
742 static int cfi_spansion_erase(struct flash_bank *bank, int first, int last)
743 {
744         int retval;
745         struct cfi_flash_bank *cfi_info = bank->driver_priv;
746         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
747         int i;
748
749         for (i = first; i <= last; i++)
750         {
751                 if ((retval = cfi_send_command(bank, 0xaa, flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
752                 {
753                         return retval;
754                 }
755
756                 if ((retval = cfi_send_command(bank, 0x55, flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
757                 {
758                         return retval;
759                 }
760
761                 if ((retval = cfi_send_command(bank, 0x80, flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
762                 {
763                         return retval;
764                 }
765
766                 if ((retval = cfi_send_command(bank, 0xaa, flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
767                 {
768                         return retval;
769                 }
770
771                 if ((retval = cfi_send_command(bank, 0x55, flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
772                 {
773                         return retval;
774                 }
775
776                 if ((retval = cfi_send_command(bank, 0x30, flash_address(bank, i, 0x0))) != ERROR_OK)
777                 {
778                         return retval;
779                 }
780
781                 if (cfi_spansion_wait_status_busy(bank, 1000 * (1 << cfi_info->block_erase_timeout_typ)) == ERROR_OK)
782                         bank->sectors[i].is_erased = 1;
783                 else
784                 {
785                         if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
786                         {
787                                 return retval;
788                         }
789
790                         LOG_ERROR("couldn't erase block %i of flash bank at base 0x%" PRIx32, i, bank->base);
791                         return ERROR_FLASH_OPERATION_FAILED;
792                 }
793         }
794
795         return  cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0));
796 }
797
798 static int cfi_erase(struct flash_bank *bank, int first, int last)
799 {
800         struct cfi_flash_bank *cfi_info = bank->driver_priv;
801
802         if (bank->target->state != TARGET_HALTED)
803         {
804                 LOG_ERROR("Target not halted");
805                 return ERROR_TARGET_NOT_HALTED;
806         }
807
808         if ((first < 0) || (last < first) || (last >= bank->num_sectors))
809         {
810                 return ERROR_FLASH_SECTOR_INVALID;
811         }
812
813         if (cfi_info->qry[0] != 'Q')
814                 return ERROR_FLASH_BANK_NOT_PROBED;
815
816         switch (cfi_info->pri_id)
817         {
818                 case 1:
819                 case 3:
820                         return cfi_intel_erase(bank, first, last);
821                         break;
822                 case 2:
823                         return cfi_spansion_erase(bank, first, last);
824                         break;
825                 default:
826                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
827                         break;
828         }
829
830         return ERROR_OK;
831 }
832
833 static int cfi_intel_protect(struct flash_bank *bank, int set, int first, int last)
834 {
835         int retval;
836         struct cfi_flash_bank *cfi_info = bank->driver_priv;
837         struct cfi_intel_pri_ext *pri_ext = cfi_info->pri_ext;
838         int retry = 0;
839         int i;
840
841         /* if the device supports neither legacy lock/unlock (bit 3) nor
842          * instant individual block locking (bit 5).
843          */
844         if (!(pri_ext->feature_support & 0x28))
845                 return ERROR_FLASH_OPERATION_FAILED;
846
847         cfi_intel_clear_status_register(bank);
848
849         for (i = first; i <= last; i++)
850         {
851                 if ((retval = cfi_send_command(bank, 0x60, flash_address(bank, i, 0x0))) != ERROR_OK)
852                 {
853                         return retval;
854                 }
855                 if (set)
856                 {
857                         if ((retval = cfi_send_command(bank, 0x01, flash_address(bank, i, 0x0))) != ERROR_OK)
858                         {
859                                 return retval;
860                         }
861                         bank->sectors[i].is_protected = 1;
862                 }
863                 else
864                 {
865                         if ((retval = cfi_send_command(bank, 0xd0, flash_address(bank, i, 0x0))) != ERROR_OK)
866                         {
867                                 return retval;
868                         }
869                         bank->sectors[i].is_protected = 0;
870                 }
871
872                 /* instant individual block locking doesn't require reading of the status register */
873                 if (!(pri_ext->feature_support & 0x20))
874                 {
875                         /* Clear lock bits operation may take up to 1.4s */
876                         cfi_intel_wait_status_busy(bank, 1400);
877                 }
878                 else
879                 {
880                         uint8_t block_status;
881                         /* read block lock bit, to verify status */
882                         if ((retval = cfi_send_command(bank, 0x90, flash_address(bank, 0, 0x55))) != ERROR_OK)
883                         {
884                                 return retval;
885                         }
886                         block_status = cfi_get_u8(bank, i, 0x2);
887
888                         if ((block_status & 0x1) != set)
889                         {
890                                 LOG_ERROR("couldn't change block lock status (set = %i, block_status = 0x%2.2x)", set, block_status);
891                                 if ((retval = cfi_send_command(bank, 0x70, flash_address(bank, 0, 0x55))) != ERROR_OK)
892                                 {
893                                         return retval;
894                                 }
895                                 cfi_intel_wait_status_busy(bank, 10);
896
897                                 if (retry > 10)
898                                         return ERROR_FLASH_OPERATION_FAILED;
899                                 else
900                                 {
901                                         i--;
902                                         retry++;
903                                 }
904                         }
905                 }
906         }
907
908         /* if the device doesn't support individual block lock bits set/clear,
909          * all blocks have been unlocked in parallel, so we set those that should be protected
910          */
911         if ((!set) && (!(pri_ext->feature_support & 0x20)))
912         {
913                 /* FIX!!! this code path is broken!!!
914                  *
915                  * The correct approach is:
916                  *
917                  * 1. read out current protection status
918                  *
919                  * 2. override read out protection status w/unprotected.
920                  *
921                  * 3. re-protect what should be protected.
922                  *
923                  */
924                 for (i = 0; i < bank->num_sectors; i++)
925                 {
926                         if (bank->sectors[i].is_protected == 1)
927                         {
928                                 cfi_intel_clear_status_register(bank);
929
930                                 if ((retval = cfi_send_command(bank, 0x60, flash_address(bank, i, 0x0))) != ERROR_OK)
931                                 {
932                                         return retval;
933                                 }
934
935                                 if ((retval = cfi_send_command(bank, 0x01, flash_address(bank, i, 0x0))) != ERROR_OK)
936                                 {
937                                         return retval;
938                                 }
939
940                                 cfi_intel_wait_status_busy(bank, 100);
941                         }
942                 }
943         }
944
945         return cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0));
946 }
947
948 static int cfi_protect(struct flash_bank *bank, int set, int first, int last)
949 {
950         struct cfi_flash_bank *cfi_info = bank->driver_priv;
951
952         if (bank->target->state != TARGET_HALTED)
953         {
954                 LOG_ERROR("Target not halted");
955                 return ERROR_TARGET_NOT_HALTED;
956         }
957
958         if ((first < 0) || (last < first) || (last >= bank->num_sectors))
959         {
960                 LOG_ERROR("Invalid sector range");
961                 return ERROR_FLASH_SECTOR_INVALID;
962         }
963
964         if (cfi_info->qry[0] != 'Q')
965                 return ERROR_FLASH_BANK_NOT_PROBED;
966
967         switch (cfi_info->pri_id)
968         {
969                 case 1:
970                 case 3:
971                         return cfi_intel_protect(bank, set, first, last);
972                         break;
973                 default:
974                         LOG_ERROR("protect: cfi primary command set %i unsupported", cfi_info->pri_id);
975                         return ERROR_FAIL;
976         }
977 }
978
979 /* Convert code image to target endian */
980 /* FIXME create general block conversion fcts in target.c?) */
981 static void cfi_fix_code_endian(struct target *target, uint8_t *dest, const uint32_t *src, uint32_t count)
982 {
983         uint32_t i;
984         for (i = 0; i< count; i++)
985         {
986                 target_buffer_set_u32(target, dest, *src);
987                 dest += 4;
988                 src++;
989         }
990 }
991
992 static uint32_t cfi_command_val(struct flash_bank *bank, uint8_t cmd)
993 {
994         struct target *target = bank->target;
995
996         uint8_t buf[CFI_MAX_BUS_WIDTH];
997         cfi_command(bank, cmd, buf);
998         switch (bank->bus_width)
999         {
1000         case 1 :
1001                 return buf[0];
1002                 break;
1003         case 2 :
1004                 return target_buffer_get_u16(target, buf);
1005                 break;
1006         case 4 :
1007                 return target_buffer_get_u32(target, buf);
1008                 break;
1009         default :
1010                 LOG_ERROR("Unsupported bank buswidth %d, can't do block memory writes", bank->bus_width);
1011                 return 0;
1012         }
1013 }
1014
1015 static int cfi_intel_write_block(struct flash_bank *bank, uint8_t *buffer, uint32_t address, uint32_t count)
1016 {
1017         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1018         struct target *target = bank->target;
1019         struct reg_param reg_params[7];
1020         struct arm_algorithm armv4_5_info;
1021         struct working_area *source;
1022         uint32_t buffer_size = 32768;
1023         uint32_t write_command_val, busy_pattern_val, error_pattern_val;
1024
1025         /* algorithm register usage:
1026          * r0: source address (in RAM)
1027          * r1: target address (in Flash)
1028          * r2: count
1029          * r3: flash write command
1030          * r4: status byte (returned to host)
1031          * r5: busy test pattern
1032          * r6: error test pattern
1033          */
1034
1035         static const uint32_t word_32_code[] = {
1036                 0xe4904004,   /* loop:  ldr r4, [r0], #4 */
1037                 0xe5813000,   /*                str r3, [r1] */
1038                 0xe5814000,   /*                str r4, [r1] */
1039                 0xe5914000,   /* busy:  ldr r4, [r1] */
1040                 0xe0047005,   /*                and r7, r4, r5 */
1041                 0xe1570005,   /*                cmp r7, r5 */
1042                 0x1afffffb,   /*                bne busy */
1043                 0xe1140006,   /*                tst r4, r6 */
1044                 0x1a000003,   /*                bne done */
1045                 0xe2522001,   /*                subs r2, r2, #1 */
1046                 0x0a000001,   /*                beq done */
1047                 0xe2811004,   /*                add r1, r1 #4 */
1048                 0xeafffff2,   /*                b loop */
1049                 0xeafffffe    /* done:  b -2 */
1050         };
1051
1052         static const uint32_t word_16_code[] = {
1053                 0xe0d040b2,   /* loop:  ldrh r4, [r0], #2 */
1054                 0xe1c130b0,   /*                strh r3, [r1] */
1055                 0xe1c140b0,   /*                strh r4, [r1] */
1056                 0xe1d140b0,   /* busy   ldrh r4, [r1] */
1057                 0xe0047005,   /*                and r7, r4, r5 */
1058                 0xe1570005,   /*                cmp r7, r5 */
1059                 0x1afffffb,   /*                bne busy */
1060                 0xe1140006,   /*                tst r4, r6 */
1061                 0x1a000003,   /*                bne done */
1062                 0xe2522001,   /*                subs r2, r2, #1 */
1063                 0x0a000001,   /*                beq done */
1064                 0xe2811002,   /*                add r1, r1 #2 */
1065                 0xeafffff2,   /*                b loop */
1066                 0xeafffffe    /* done:  b -2 */
1067         };
1068
1069         static const uint32_t word_8_code[] = {
1070                 0xe4d04001,   /* loop:  ldrb r4, [r0], #1 */
1071                 0xe5c13000,   /*                strb r3, [r1] */
1072                 0xe5c14000,   /*                strb r4, [r1] */
1073                 0xe5d14000,   /* busy   ldrb r4, [r1] */
1074                 0xe0047005,   /*                and r7, r4, r5 */
1075                 0xe1570005,   /*                cmp r7, r5 */
1076                 0x1afffffb,   /*                bne busy */
1077                 0xe1140006,   /*                tst r4, r6 */
1078                 0x1a000003,   /*                bne done */
1079                 0xe2522001,   /*                subs r2, r2, #1 */
1080                 0x0a000001,   /*                beq done */
1081                 0xe2811001,   /*                add r1, r1 #1 */
1082                 0xeafffff2,   /*                b loop */
1083                 0xeafffffe    /* done:  b -2 */
1084         };
1085         uint8_t target_code[4*CFI_MAX_INTEL_CODESIZE];
1086         const uint32_t *target_code_src;
1087         uint32_t target_code_size;
1088         int retval = ERROR_OK;
1089
1090
1091         cfi_intel_clear_status_register(bank);
1092
1093         armv4_5_info.common_magic = ARM_COMMON_MAGIC;
1094         armv4_5_info.core_mode = ARM_MODE_SVC;
1095         armv4_5_info.core_state = ARM_STATE_ARM;
1096
1097         /* If we are setting up the write_algorith, we need target_code_src */
1098         /* if not we only need target_code_size. */
1099
1100         /* However, we don't want to create multiple code paths, so we */
1101         /* do the unecessary evaluation of target_code_src, which the */
1102         /* compiler will probably nicely optimize away if not needed */
1103
1104         /* prepare algorithm code for target endian */
1105         switch (bank->bus_width)
1106         {
1107         case 1 :
1108                 target_code_src = word_8_code;
1109                 target_code_size = sizeof(word_8_code);
1110                 break;
1111         case 2 :
1112                 target_code_src = word_16_code;
1113                 target_code_size = sizeof(word_16_code);
1114                 break;
1115         case 4 :
1116                 target_code_src = word_32_code;
1117                 target_code_size = sizeof(word_32_code);
1118                 break;
1119         default:
1120                 LOG_ERROR("Unsupported bank buswidth %d, can't do block memory writes", bank->bus_width);
1121                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1122         }
1123
1124         /* flash write code */
1125         if (!cfi_info->write_algorithm)
1126         {
1127                 if (target_code_size > sizeof(target_code))
1128                 {
1129                         LOG_WARNING("Internal error - target code buffer to small. Increase CFI_MAX_INTEL_CODESIZE and recompile.");
1130                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1131                 }
1132                 cfi_fix_code_endian(target, target_code, target_code_src, target_code_size / 4);
1133
1134                 /* Get memory for block write handler */
1135                 retval = target_alloc_working_area(target, target_code_size, &cfi_info->write_algorithm);
1136                 if (retval != ERROR_OK)
1137                 {
1138                         LOG_WARNING("No working area available, can't do block memory writes");
1139                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1140                 };
1141
1142                 /* write algorithm code to working area */
1143                 retval = target_write_buffer(target, cfi_info->write_algorithm->address, target_code_size, target_code);
1144                 if (retval != ERROR_OK)
1145                 {
1146                         LOG_ERROR("Unable to write block write code to target");
1147                         goto cleanup;
1148                 }
1149         }
1150
1151         /* Get a workspace buffer for the data to flash starting with 32k size.
1152            Half size until buffer would be smaller 256 Bytem then fail back */
1153         /* FIXME Why 256 bytes, why not 32 bytes (smallest flash write page */
1154         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK)
1155         {
1156                 buffer_size /= 2;
1157                 if (buffer_size <= 256)
1158                 {
1159                         LOG_WARNING("no large enough working area available, can't do block memory writes");
1160                         retval = ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1161                         goto cleanup;
1162                 }
1163         };
1164
1165         /* setup algo registers */
1166         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
1167         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
1168         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
1169         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
1170         init_reg_param(&reg_params[4], "r4", 32, PARAM_IN);
1171         init_reg_param(&reg_params[5], "r5", 32, PARAM_OUT);
1172         init_reg_param(&reg_params[6], "r6", 32, PARAM_OUT);
1173
1174         /* prepare command and status register patterns */
1175         write_command_val = cfi_command_val(bank, 0x40);
1176         busy_pattern_val  = cfi_command_val(bank, 0x80);
1177         error_pattern_val = cfi_command_val(bank, 0x7e);
1178
1179         LOG_DEBUG("Using target buffer at 0x%08" PRIx32 " and of size 0x%04" PRIx32, source->address, buffer_size);
1180
1181         /* Programming main loop */
1182         while (count > 0)
1183         {
1184                 uint32_t thisrun_count = (count > buffer_size) ? buffer_size : count;
1185                 uint32_t wsm_error;
1186
1187                 if ((retval = target_write_buffer(target, source->address, thisrun_count, buffer)) != ERROR_OK)
1188                 {
1189                         goto cleanup;
1190                 }
1191
1192                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
1193                 buf_set_u32(reg_params[1].value, 0, 32, address);
1194                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count / bank->bus_width);
1195
1196                 buf_set_u32(reg_params[3].value, 0, 32, write_command_val);
1197                 buf_set_u32(reg_params[5].value, 0, 32, busy_pattern_val);
1198                 buf_set_u32(reg_params[6].value, 0, 32, error_pattern_val);
1199
1200                 LOG_DEBUG("Write 0x%04" PRIx32 " bytes to flash at 0x%08" PRIx32 , thisrun_count, address);
1201
1202                 /* Execute algorithm, assume breakpoint for last instruction */
1203                 retval = target_run_algorithm(target, 0, NULL, 7, reg_params,
1204                         cfi_info->write_algorithm->address,
1205                         cfi_info->write_algorithm->address + target_code_size - sizeof(uint32_t),
1206                         10000, /* 10s should be enough for max. 32k of data */
1207                         &armv4_5_info);
1208
1209                 /* On failure try a fall back to direct word writes */
1210                 if (retval != ERROR_OK)
1211                 {
1212                         cfi_intel_clear_status_register(bank);
1213                         LOG_ERROR("Execution of flash algorythm failed. Can't fall back. Please report.");
1214                         retval = ERROR_FLASH_OPERATION_FAILED;
1215                         /* retval = ERROR_TARGET_RESOURCE_NOT_AVAILABLE; */
1216                         /* FIXME To allow fall back or recovery, we must save the actual status
1217                            somewhere, so that a higher level code can start recovery. */
1218                         goto cleanup;
1219                 }
1220
1221                 /* Check return value from algo code */
1222                 wsm_error = buf_get_u32(reg_params[4].value, 0, 32) & error_pattern_val;
1223                 if (wsm_error)
1224                 {
1225                         /* read status register (outputs debug inforation) */
1226                         cfi_intel_wait_status_busy(bank, 100);
1227                         cfi_intel_clear_status_register(bank);
1228                         retval = ERROR_FLASH_OPERATION_FAILED;
1229                         goto cleanup;
1230                 }
1231
1232                 buffer += thisrun_count;
1233                 address += thisrun_count;
1234                 count -= thisrun_count;
1235
1236                 keep_alive();
1237         }
1238
1239         /* free up resources */
1240 cleanup:
1241         if (source)
1242                 target_free_working_area(target, source);
1243
1244         if (cfi_info->write_algorithm)
1245         {
1246                 target_free_working_area(target, cfi_info->write_algorithm);
1247                 cfi_info->write_algorithm = NULL;
1248         }
1249
1250         destroy_reg_param(&reg_params[0]);
1251         destroy_reg_param(&reg_params[1]);
1252         destroy_reg_param(&reg_params[2]);
1253         destroy_reg_param(&reg_params[3]);
1254         destroy_reg_param(&reg_params[4]);
1255         destroy_reg_param(&reg_params[5]);
1256         destroy_reg_param(&reg_params[6]);
1257
1258         return retval;
1259 }
1260
1261 static int cfi_spansion_write_block(struct flash_bank *bank, uint8_t *buffer, uint32_t address, uint32_t count)
1262 {
1263         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1264         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
1265         struct target *target = bank->target;
1266         struct reg_param reg_params[10];
1267         struct arm_algorithm armv4_5_info;
1268         struct working_area *source;
1269         uint32_t buffer_size = 32768;
1270         uint32_t status;
1271         int retval, retvaltemp;
1272         int exit_code = ERROR_OK;
1273
1274         /* input parameters - */
1275         /*      R0 = source address */
1276         /*      R1 = destination address */
1277         /*      R2 = number of writes */
1278         /*      R3 = flash write command */
1279         /*      R4 = constant to mask DQ7 bits (also used for Dq5 with shift) */
1280         /* output parameters - */
1281         /*      R5 = 0x80 ok 0x00 bad */
1282         /* temp registers - */
1283         /*      R6 = value read from flash to test status */
1284         /*      R7 = holding register */
1285         /* unlock registers - */
1286         /*  R8 = unlock1_addr */
1287         /*  R9 = unlock1_cmd */
1288         /*  R10 = unlock2_addr */
1289         /*  R11 = unlock2_cmd */
1290
1291         static const uint32_t word_32_code[] = {
1292                                                 /* 00008100 <sp_32_code>:               */
1293                 0xe4905004,             /* ldr  r5, [r0], #4                    */
1294                 0xe5889000,     /* str  r9, [r8]                                */
1295                 0xe58ab000,     /* str  r11, [r10]                              */
1296                 0xe5883000,     /* str  r3, [r8]                                */
1297                 0xe5815000,     /* str  r5, [r1]                                */
1298                 0xe1a00000,     /* nop                                                  */
1299                                                 /*                                                              */
1300                                                 /* 00008110 <sp_32_busy>:               */
1301                 0xe5916000,     /* ldr  r6, [r1]                                */
1302                 0xe0257006,     /* eor  r7, r5, r6                              */
1303                 0xe0147007,     /* ands r7, r4, r7                              */
1304                 0x0a000007,     /* beq  8140 <sp_32_cont> ; b if DQ7 == Data7 */
1305                 0xe0166124,     /* ands r6, r6, r4, lsr #2              */
1306                 0x0afffff9,     /* beq  8110 <sp_32_busy> ;     b if DQ5 low */
1307                 0xe5916000,     /* ldr  r6, [r1]                                */
1308                 0xe0257006,     /* eor  r7, r5, r6                              */
1309                 0xe0147007,     /* ands r7, r4, r7                              */
1310                 0x0a000001,     /* beq  8140 <sp_32_cont> ; b if DQ7 == Data7 */
1311                 0xe3a05000,     /* mov  r5, #0  ; 0x0 - return 0x00, error */
1312                 0x1a000004,     /* bne  8154 <sp_32_done>               */
1313                                                 /*                                                              */
1314                                 /* 00008140 <sp_32_cont>:                               */
1315                 0xe2522001,     /* subs r2, r2, #1      ; 0x1           */
1316                 0x03a05080,     /* moveq        r5, #128        ; 0x80  */
1317                 0x0a000001,     /* beq  8154 <sp_32_done>               */
1318                 0xe2811004,     /* add  r1, r1, #4      ; 0x4           */
1319                 0xeaffffe8,     /* b    8100 <sp_32_code>               */
1320                                                 /*                                                              */
1321                                                 /* 00008154 <sp_32_done>:               */
1322                 0xeafffffe              /* b    8154 <sp_32_done>               */
1323                 };
1324
1325                 static const uint32_t word_16_code[] = {
1326                                 /* 00008158 <sp_16_code>:              */
1327                 0xe0d050b2,     /* ldrh r5, [r0], #2               */
1328                 0xe1c890b0,     /* strh r9, [r8]                                */
1329                 0xe1cab0b0,     /* strh r11, [r10]                              */
1330                 0xe1c830b0,     /* strh r3, [r8]                                */
1331                 0xe1c150b0,     /* strh r5, [r1]                       */
1332                 0xe1a00000,     /* nop                  (mov r0,r0)    */
1333                                 /*                                     */
1334                                 /* 00008168 <sp_16_busy>:              */
1335                 0xe1d160b0,     /* ldrh r6, [r1]                       */
1336                 0xe0257006,     /* eor  r7, r5, r6                     */
1337                 0xe0147007,     /* ands r7, r4, r7                     */
1338                 0x0a000007,     /* beq  8198 <sp_16_cont>              */
1339                 0xe0166124,     /* ands r6, r6, r4, lsr #2             */
1340                 0x0afffff9,     /* beq  8168 <sp_16_busy>              */
1341                 0xe1d160b0,     /* ldrh r6, [r1]                       */
1342                 0xe0257006,     /* eor  r7, r5, r6                     */
1343                 0xe0147007,     /* ands r7, r4, r7                     */
1344                 0x0a000001,     /* beq  8198 <sp_16_cont>              */
1345                 0xe3a05000,     /* mov  r5, #0  ; 0x0                  */
1346                 0x1a000004,     /* bne  81ac <sp_16_done>              */
1347                                 /*                                     */
1348                                 /* 00008198 <sp_16_cont>:              */
1349                 0xe2522001,     /* subs r2, r2, #1      ; 0x1          */
1350                 0x03a05080,     /* moveq        r5, #128        ; 0x80 */
1351                 0x0a000001,     /* beq  81ac <sp_16_done>              */
1352                 0xe2811002,     /* add  r1, r1, #2      ; 0x2          */
1353                 0xeaffffe8,     /* b    8158 <sp_16_code>              */
1354                                 /*                                     */
1355                                 /* 000081ac <sp_16_done>:              */
1356                 0xeafffffe      /* b    81ac <sp_16_done>              */
1357                 };
1358
1359                 static const uint32_t word_16_code_dq7only[] = {
1360                                 /* <sp_16_code>:                       */
1361                 0xe0d050b2,     /* ldrh r5, [r0], #2                   */
1362                 0xe1c890b0,     /* strh r9, [r8]                       */
1363                 0xe1cab0b0,     /* strh r11, [r10]                              */
1364                 0xe1c830b0,     /* strh r3, [r8]                                */
1365                 0xe1c150b0,     /* strh r5, [r1]                       */
1366                 0xe1a00000,     /* nop                  (mov r0,r0)    */
1367                                 /*                                     */
1368                                 /* <sp_16_busy>:                       */
1369                 0xe1d160b0,     /* ldrh r6, [r1]                       */
1370                 0xe0257006,     /* eor  r7, r5, r6                     */
1371                 0xe2177080,     /* ands r7, #0x80                      */
1372                 0x1afffffb,     /* bne  8168 <sp_16_busy>              */
1373                                 /*                                     */
1374                 0xe2522001,     /* subs r2, r2, #1      ; 0x1          */
1375                 0x03a05080,     /* moveq        r5, #128        ; 0x80 */
1376                 0x0a000001,     /* beq  81ac <sp_16_done>              */
1377                 0xe2811002,     /* add  r1, r1, #2      ; 0x2          */
1378                 0xeafffff0,     /* b    8158 <sp_16_code>              */
1379                                 /*                                     */
1380                                 /* 000081ac <sp_16_done>:              */
1381                 0xeafffffe      /* b    81ac <sp_16_done>              */
1382                 };
1383
1384                 static const uint32_t word_8_code[] = {
1385                                 /* 000081b0 <sp_16_code_end>:          */
1386                 0xe4d05001,     /* ldrb r5, [r0], #1                   */
1387                 0xe5c89000,     /* strb r9, [r8]                                */
1388                 0xe5cab000,     /* strb r11, [r10]                              */
1389                 0xe5c83000,     /* strb r3, [r8]                                */
1390                 0xe5c15000,     /* strb r5, [r1]                       */
1391                 0xe1a00000,     /* nop                  (mov r0,r0)    */
1392                                 /*                                     */
1393                                 /* 000081c0 <sp_8_busy>:               */
1394                 0xe5d16000,     /* ldrb r6, [r1]                       */
1395                 0xe0257006,     /* eor  r7, r5, r6                     */
1396                 0xe0147007,     /* ands r7, r4, r7                     */
1397                 0x0a000007,     /* beq  81f0 <sp_8_cont>               */
1398                 0xe0166124,     /* ands r6, r6, r4, lsr #2             */
1399                 0x0afffff9,     /* beq  81c0 <sp_8_busy>               */
1400                 0xe5d16000,     /* ldrb r6, [r1]                       */
1401                 0xe0257006,     /* eor  r7, r5, r6                     */
1402                 0xe0147007,     /* ands r7, r4, r7                     */
1403                 0x0a000001,     /* beq  81f0 <sp_8_cont>               */
1404                 0xe3a05000,     /* mov  r5, #0  ; 0x0                  */
1405                 0x1a000004,     /* bne  8204 <sp_8_done>               */
1406                                 /*                                     */
1407                                 /* 000081f0 <sp_8_cont>:               */
1408                 0xe2522001,     /* subs r2, r2, #1      ; 0x1          */
1409                 0x03a05080,     /* moveq        r5, #128        ; 0x80 */
1410                 0x0a000001,     /* beq  8204 <sp_8_done>               */
1411                 0xe2811001,     /* add  r1, r1, #1      ; 0x1          */
1412                 0xeaffffe8,     /* b    81b0 <sp_16_code_end>          */
1413                                 /*                                     */
1414                                 /* 00008204 <sp_8_done>:               */
1415                 0xeafffffe      /* b    8204 <sp_8_done>               */
1416         };
1417
1418         armv4_5_info.common_magic = ARM_COMMON_MAGIC;
1419         armv4_5_info.core_mode = ARM_MODE_SVC;
1420         armv4_5_info.core_state = ARM_STATE_ARM;
1421
1422         int target_code_size;
1423         const uint32_t *target_code_src;
1424
1425         switch (bank->bus_width)
1426         {
1427         case 1 :
1428                 target_code_src = word_8_code;
1429                 target_code_size = sizeof(word_8_code);
1430                 break;
1431         case 2 :
1432                 /* Check for DQ5 support */
1433                 if( cfi_info->status_poll_mask & (1 << 5) )
1434                 {
1435                         target_code_src = word_16_code;
1436                         target_code_size = sizeof(word_16_code);
1437                 }
1438                 else
1439                 {
1440                         /* No DQ5 support. Use DQ7 DATA# polling only. */
1441                         target_code_src = word_16_code_dq7only;
1442                         target_code_size = sizeof(word_16_code_dq7only);
1443                 }
1444                 break;
1445         case 4 :
1446                 target_code_src = word_32_code;
1447                 target_code_size = sizeof(word_32_code);
1448                 break;
1449         default:
1450                 LOG_ERROR("Unsupported bank buswidth %d, can't do block memory writes", bank->bus_width);
1451                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1452         }
1453
1454         /* flash write code */
1455         if (!cfi_info->write_algorithm)
1456         {
1457                 uint8_t *target_code;
1458
1459                 /* convert bus-width dependent algorithm code to correct endiannes */
1460                 target_code = malloc(target_code_size);
1461                 if (target_code == NULL)
1462                 {
1463                         LOG_ERROR("Out of memory");
1464                         return ERROR_FAIL;
1465                 }
1466                 cfi_fix_code_endian(target, target_code, target_code_src, target_code_size / 4);
1467
1468                 /* allocate working area */
1469                 retval = target_alloc_working_area(target, target_code_size,
1470                                 &cfi_info->write_algorithm);
1471                 if (retval != ERROR_OK)
1472                 {
1473                         free(target_code);
1474                         return retval;
1475                 }
1476
1477                 /* write algorithm code to working area */
1478                 if ((retval = target_write_buffer(target, cfi_info->write_algorithm->address,
1479                                     target_code_size, target_code)) != ERROR_OK)
1480                 {
1481                         free(target_code);
1482                         return retval;
1483                 }
1484
1485                 free(target_code);
1486         }
1487         /* the following code still assumes target code is fixed 24*4 bytes */
1488
1489         while (target_alloc_working_area_try(target, buffer_size, &source) != ERROR_OK)
1490         {
1491                 buffer_size /= 2;
1492                 if (buffer_size <= 256)
1493                 {
1494                         /* if we already allocated the writing code, but failed to get a buffer, free the algorithm */
1495                         if (cfi_info->write_algorithm)
1496                                 target_free_working_area(target, cfi_info->write_algorithm);
1497
1498                         LOG_WARNING("not enough working area available, can't do block memory writes");
1499                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1500                 }
1501         };
1502
1503         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
1504         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
1505         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
1506         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
1507         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
1508         init_reg_param(&reg_params[5], "r5", 32, PARAM_IN);
1509         init_reg_param(&reg_params[6], "r8", 32, PARAM_OUT);
1510         init_reg_param(&reg_params[7], "r9", 32, PARAM_OUT);
1511         init_reg_param(&reg_params[8], "r10", 32, PARAM_OUT);
1512         init_reg_param(&reg_params[9], "r11", 32, PARAM_OUT);
1513
1514         while (count > 0)
1515         {
1516                 uint32_t thisrun_count = (count > buffer_size) ? buffer_size : count;
1517
1518                 retvaltemp = target_write_buffer(target, source->address, thisrun_count, buffer);
1519
1520                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
1521                 buf_set_u32(reg_params[1].value, 0, 32, address);
1522                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count / bank->bus_width);
1523                 buf_set_u32(reg_params[3].value, 0, 32, cfi_command_val(bank, 0xA0));
1524                 buf_set_u32(reg_params[4].value, 0, 32, cfi_command_val(bank, 0x80));
1525                 buf_set_u32(reg_params[6].value, 0, 32, flash_address(bank, 0, pri_ext->_unlock1));
1526                 buf_set_u32(reg_params[7].value, 0, 32, 0xaaaaaaaa);
1527                 buf_set_u32(reg_params[8].value, 0, 32, flash_address(bank, 0, pri_ext->_unlock2));
1528                 buf_set_u32(reg_params[9].value, 0, 32, 0x55555555);
1529
1530                 retval = target_run_algorithm(target, 0, NULL, 10, reg_params,
1531                                                      cfi_info->write_algorithm->address,
1532                                                      cfi_info->write_algorithm->address + ((target_code_size) - 4),
1533                                                      10000, &armv4_5_info);
1534
1535                 status = buf_get_u32(reg_params[5].value, 0, 32);
1536
1537                 if ((retval != ERROR_OK) || (retvaltemp != ERROR_OK) || status != 0x80)
1538                 {
1539                         LOG_DEBUG("status: 0x%" PRIx32 , status);
1540                         exit_code = ERROR_FLASH_OPERATION_FAILED;
1541                         break;
1542                 }
1543
1544                 buffer += thisrun_count;
1545                 address += thisrun_count;
1546                 count -= thisrun_count;
1547         }
1548
1549         target_free_all_working_areas(target);
1550
1551         destroy_reg_param(&reg_params[0]);
1552         destroy_reg_param(&reg_params[1]);
1553         destroy_reg_param(&reg_params[2]);
1554         destroy_reg_param(&reg_params[3]);
1555         destroy_reg_param(&reg_params[4]);
1556         destroy_reg_param(&reg_params[5]);
1557         destroy_reg_param(&reg_params[6]);
1558         destroy_reg_param(&reg_params[7]);
1559         destroy_reg_param(&reg_params[8]);
1560         destroy_reg_param(&reg_params[9]);
1561
1562         return exit_code;
1563 }
1564
1565 static int cfi_intel_write_word(struct flash_bank *bank, uint8_t *word, uint32_t address)
1566 {
1567         int retval;
1568         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1569         struct target *target = bank->target;
1570
1571         cfi_intel_clear_status_register(bank);
1572         if ((retval = cfi_send_command(bank, 0x40, address)) != ERROR_OK)
1573         {
1574                 return retval;
1575         }
1576
1577         if ((retval = target_write_memory(target, address, bank->bus_width, 1, word)) != ERROR_OK)
1578         {
1579                 return retval;
1580         }
1581
1582         if (cfi_intel_wait_status_busy(bank, 1000 * (1 << cfi_info->word_write_timeout_max)) != 0x80)
1583         {
1584                 if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
1585                 {
1586                         return retval;
1587                 }
1588
1589                 LOG_ERROR("couldn't write word at base 0x%" PRIx32 ", address %" PRIx32 , bank->base, address);
1590                 return ERROR_FLASH_OPERATION_FAILED;
1591         }
1592
1593         return ERROR_OK;
1594 }
1595
1596 static int cfi_intel_write_words(struct flash_bank *bank, uint8_t *word, uint32_t wordcount, uint32_t address)
1597 {
1598         int retval;
1599         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1600         struct target *target = bank->target;
1601
1602         /* Calculate buffer size and boundary mask */
1603         /* buffersize is (buffer size per chip) * (number of chips) */
1604         /* bufferwsize is buffersize in words */
1605         uint32_t buffersize = (1UL << cfi_info->max_buf_write_size) * (bank->bus_width / bank->chip_width);
1606         uint32_t buffermask = buffersize-1;
1607         uint32_t bufferwsize = buffersize / bank->bus_width;
1608
1609         /* Check for valid range */
1610         if (address & buffermask)
1611         {
1612                 LOG_ERROR("Write address at base 0x%" PRIx32 ", address %" PRIx32 " not aligned to 2^%d boundary",
1613                           bank->base, address, cfi_info->max_buf_write_size);
1614                 return ERROR_FLASH_OPERATION_FAILED;
1615         }
1616
1617         /* Check for valid size */
1618         if (wordcount > bufferwsize)
1619         {
1620                 LOG_ERROR("Number of data words %" PRId32 " exceeds available buffersize %" PRId32 , wordcount, buffersize);
1621                 return ERROR_FLASH_OPERATION_FAILED;
1622         }
1623
1624         /* Write to flash buffer */
1625         cfi_intel_clear_status_register(bank);
1626
1627         /* Initiate buffer operation _*/
1628         if ((retval = cfi_send_command(bank, 0xe8, address)) != ERROR_OK)
1629         {
1630                 return retval;
1631         }
1632         if (cfi_intel_wait_status_busy(bank, 1000 * (1 << cfi_info->buf_write_timeout_max)) != 0x80)
1633         {
1634                 if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
1635                 {
1636                         return retval;
1637                 }
1638
1639                 LOG_ERROR("couldn't start buffer write operation at base 0x%" PRIx32 ", address %" PRIx32 , bank->base, address);
1640                 return ERROR_FLASH_OPERATION_FAILED;
1641         }
1642
1643         /* Write buffer wordcount-1 and data words */
1644         if ((retval = cfi_send_command(bank, bufferwsize-1, address)) != ERROR_OK)
1645         {
1646                 return retval;
1647         }
1648
1649         if ((retval = target_write_memory(target, address, bank->bus_width, bufferwsize, word)) != ERROR_OK)
1650         {
1651                 return retval;
1652         }
1653
1654         /* Commit write operation */
1655         if ((retval = cfi_send_command(bank, 0xd0, address)) != ERROR_OK)
1656         {
1657                 return retval;
1658         }
1659         if (cfi_intel_wait_status_busy(bank, 1000 * (1 << cfi_info->buf_write_timeout_max)) != 0x80)
1660         {
1661                 if ((retval = cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0))) != ERROR_OK)
1662                 {
1663                         return retval;
1664                 }
1665
1666                 LOG_ERROR("Buffer write at base 0x%" PRIx32 ", address %" PRIx32 " failed.", bank->base, address);
1667                 return ERROR_FLASH_OPERATION_FAILED;
1668         }
1669
1670         return ERROR_OK;
1671 }
1672
1673 static int cfi_spansion_write_word(struct flash_bank *bank, uint8_t *word, uint32_t address)
1674 {
1675         int retval;
1676         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1677         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
1678         struct target *target = bank->target;
1679
1680         if ((retval = cfi_send_command(bank, 0xaa, flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
1681         {
1682                 return retval;
1683         }
1684
1685         if ((retval = cfi_send_command(bank, 0x55, flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
1686         {
1687                 return retval;
1688         }
1689
1690         if ((retval = cfi_send_command(bank, 0xa0, flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
1691         {
1692                 return retval;
1693         }
1694
1695         if ((retval = target_write_memory(target, address, bank->bus_width, 1, word)) != ERROR_OK)
1696         {
1697                 return retval;
1698         }
1699
1700         if (cfi_spansion_wait_status_busy(bank, 1000 * (1 << cfi_info->word_write_timeout_max)) != ERROR_OK)
1701         {
1702                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
1703                 {
1704                         return retval;
1705                 }
1706
1707                 LOG_ERROR("couldn't write word at base 0x%" PRIx32 ", address %" PRIx32 , bank->base, address);
1708                 return ERROR_FLASH_OPERATION_FAILED;
1709         }
1710
1711         return ERROR_OK;
1712 }
1713
1714 static int cfi_spansion_write_words(struct flash_bank *bank, uint8_t *word, uint32_t wordcount, uint32_t address)
1715 {
1716         int retval;
1717         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1718         struct target *target = bank->target;
1719         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
1720
1721         /* Calculate buffer size and boundary mask */
1722         /* buffersize is (buffer size per chip) * (number of chips) */
1723         /* bufferwsize is buffersize in words */
1724         uint32_t buffersize = (1UL << cfi_info->max_buf_write_size) * (bank->bus_width / bank->chip_width);
1725         uint32_t buffermask = buffersize-1;
1726         uint32_t bufferwsize = buffersize / bank->bus_width;
1727
1728         /* Check for valid range */
1729         if (address & buffermask)
1730         {
1731                 LOG_ERROR("Write address at base 0x%" PRIx32 ", address %" PRIx32 " not aligned to 2^%d boundary", bank->base, address, cfi_info->max_buf_write_size);
1732                 return ERROR_FLASH_OPERATION_FAILED;
1733         }
1734
1735         /* Check for valid size */
1736         if (wordcount > bufferwsize)
1737         {
1738                 LOG_ERROR("Number of data words %" PRId32 " exceeds available buffersize %" PRId32, wordcount, buffersize);
1739                 return ERROR_FLASH_OPERATION_FAILED;
1740         }
1741
1742         // Unlock
1743         if ((retval = cfi_send_command(bank, 0xaa, flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
1744         {
1745                 return retval;
1746         }
1747
1748         if ((retval = cfi_send_command(bank, 0x55, flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
1749         {
1750                 return retval;
1751         }
1752
1753         // Buffer load command
1754         if ((retval = cfi_send_command(bank, 0x25, address)) != ERROR_OK)
1755         {
1756                 return retval;
1757         }
1758
1759         /* Write buffer wordcount-1 and data words */
1760         if ((retval = cfi_send_command(bank, bufferwsize-1, address)) != ERROR_OK)
1761         {
1762                 return retval;
1763         }
1764
1765         if ((retval = target_write_memory(target, address, bank->bus_width, bufferwsize, word)) != ERROR_OK)
1766         {
1767                 return retval;
1768         }
1769
1770         /* Commit write operation */
1771         if ((retval = cfi_send_command(bank, 0x29, address)) != ERROR_OK)
1772         {
1773                 return retval;
1774         }
1775
1776         if (cfi_spansion_wait_status_busy(bank, 1000 * (1 << cfi_info->word_write_timeout_max)) != ERROR_OK)
1777         {
1778                 if ((retval = cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0))) != ERROR_OK)
1779                 {
1780                         return retval;
1781                 }
1782
1783                 LOG_ERROR("couldn't write block at base 0x%" PRIx32 ", address %" PRIx32 ", size %" PRIx32 , bank->base, address, bufferwsize);
1784                 return ERROR_FLASH_OPERATION_FAILED;
1785         }
1786
1787         return ERROR_OK;
1788 }
1789
1790 static int cfi_write_word(struct flash_bank *bank, uint8_t *word, uint32_t address)
1791 {
1792         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1793
1794         switch (cfi_info->pri_id)
1795         {
1796                 case 1:
1797                 case 3:
1798                         return cfi_intel_write_word(bank, word, address);
1799                         break;
1800                 case 2:
1801                         return cfi_spansion_write_word(bank, word, address);
1802                         break;
1803                 default:
1804                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
1805                         break;
1806         }
1807
1808         return ERROR_FLASH_OPERATION_FAILED;
1809 }
1810
1811 static int cfi_write_words(struct flash_bank *bank, uint8_t *word, uint32_t wordcount, uint32_t address)
1812 {
1813         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1814
1815         switch (cfi_info->pri_id)
1816         {
1817                 case 1:
1818                 case 3:
1819                         return cfi_intel_write_words(bank, word, wordcount, address);
1820                         break;
1821                 case 2:
1822                         return cfi_spansion_write_words(bank, word, wordcount, address);
1823                         break;
1824                 default:
1825                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
1826                         break;
1827         }
1828
1829         return ERROR_FLASH_OPERATION_FAILED;
1830 }
1831
1832 static int cfi_read(struct flash_bank *bank, uint8_t *buffer, uint32_t offset, uint32_t count)
1833 {
1834         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1835         struct target *target = bank->target;
1836         uint32_t address = bank->base + offset;
1837         uint32_t read_p;
1838         int align;      /* number of unaligned bytes */
1839         uint8_t current_word[CFI_MAX_BUS_WIDTH];
1840         int i;
1841         int retval;
1842
1843         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1844                 (int)count, (unsigned)offset);
1845
1846         if (bank->target->state != TARGET_HALTED)
1847         {
1848                 LOG_ERROR("Target not halted");
1849                 return ERROR_TARGET_NOT_HALTED;
1850         }
1851
1852         if (offset + count > bank->size)
1853                 return ERROR_FLASH_DST_OUT_OF_BANK;
1854
1855         if (cfi_info->qry[0] != 'Q')
1856                 return ERROR_FLASH_BANK_NOT_PROBED;
1857
1858         /* start at the first byte of the first word (bus_width size) */
1859         read_p = address & ~(bank->bus_width - 1);
1860         if ((align = address - read_p) != 0)
1861         {
1862                 LOG_INFO("Fixup %d unaligned read head bytes", align);
1863
1864                 /* read a complete word from flash */
1865                 if ((retval = target_read_memory(target, read_p, bank->bus_width, 1, current_word)) != ERROR_OK)
1866                         return retval;
1867
1868                 /* take only bytes we need */
1869                 for (i = align; (i < bank->bus_width) && (count > 0); i++, count--)
1870                         *buffer++ = current_word[i];
1871
1872                 read_p += bank->bus_width;
1873         }
1874
1875         align = count / bank->bus_width;
1876         if (align)
1877         {
1878                 if ((retval = target_read_memory(target, read_p, bank->bus_width, align, buffer)) != ERROR_OK)
1879                         return retval;
1880
1881                 read_p += align * bank->bus_width;
1882                 buffer += align * bank->bus_width;
1883                 count -= align * bank->bus_width;
1884         }
1885
1886         if (count)
1887         {
1888                 LOG_INFO("Fixup %d unaligned read tail bytes", count);
1889
1890                 /* read a complete word from flash */
1891                 if ((retval = target_read_memory(target, read_p, bank->bus_width, 1, current_word)) != ERROR_OK)
1892                         return retval;
1893
1894                 /* take only bytes we need */
1895                 for (i = 0; (i < bank->bus_width) && (count > 0); i++, count--)
1896                         *buffer++ = current_word[i];
1897         }
1898
1899         return ERROR_OK;
1900 }
1901
1902 static int cfi_write(struct flash_bank *bank, uint8_t *buffer, uint32_t offset, uint32_t count)
1903 {
1904         struct cfi_flash_bank *cfi_info = bank->driver_priv;
1905         struct target *target = bank->target;
1906         uint32_t address = bank->base + offset; /* address of first byte to be programmed */
1907         uint32_t write_p;
1908         int align;      /* number of unaligned bytes */
1909         int blk_count; /* number of bus_width bytes for block copy */
1910         uint8_t current_word[CFI_MAX_BUS_WIDTH * 4];    /* word (bus_width size) currently being programmed */
1911         int i;
1912         int retval;
1913
1914         if (bank->target->state != TARGET_HALTED)
1915         {
1916                 LOG_ERROR("Target not halted");
1917                 return ERROR_TARGET_NOT_HALTED;
1918         }
1919
1920         if (offset + count > bank->size)
1921                 return ERROR_FLASH_DST_OUT_OF_BANK;
1922
1923         if (cfi_info->qry[0] != 'Q')
1924                 return ERROR_FLASH_BANK_NOT_PROBED;
1925
1926         /* start at the first byte of the first word (bus_width size) */
1927         write_p = address & ~(bank->bus_width - 1);
1928         if ((align = address - write_p) != 0)
1929         {
1930                 LOG_INFO("Fixup %d unaligned head bytes", align);
1931
1932                 /* read a complete word from flash */
1933                 if ((retval = target_read_memory(target, write_p, bank->bus_width, 1, current_word)) != ERROR_OK)
1934                         return retval;
1935
1936                 /* replace only bytes that must be written */
1937                 for (i = align; (i < bank->bus_width) && (count > 0); i++, count--)
1938                         current_word[i] = *buffer++;
1939
1940                 retval = cfi_write_word(bank, current_word, write_p);
1941                 if (retval != ERROR_OK)
1942                         return retval;
1943                 write_p += bank->bus_width;
1944         }
1945
1946         /* handle blocks of bus_size aligned bytes */
1947         blk_count = count & ~(bank->bus_width - 1); /* round down, leave tail bytes */
1948         switch (cfi_info->pri_id)
1949         {
1950                 /* try block writes (fails without working area) */
1951                 case 1:
1952                 case 3:
1953                         retval = cfi_intel_write_block(bank, buffer, write_p, blk_count);
1954                         break;
1955                 case 2:
1956                         retval = cfi_spansion_write_block(bank, buffer, write_p, blk_count);
1957                         break;
1958                 default:
1959                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
1960                         retval = ERROR_FLASH_OPERATION_FAILED;
1961                         break;
1962         }
1963         if (retval == ERROR_OK)
1964         {
1965                 /* Increment pointers and decrease count on succesful block write */
1966                 buffer += blk_count;
1967                 write_p += blk_count;
1968                 count -= blk_count;
1969         }
1970         else
1971         {
1972                 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1973                 {
1974                         /* Calculate buffer size and boundary mask */
1975                         /* buffersize is (buffer size per chip) * (number of chips) */
1976                         /* bufferwsize is buffersize in words */
1977                         uint32_t buffersize = (1UL << cfi_info->max_buf_write_size) * (bank->bus_width / bank->chip_width);
1978                         uint32_t buffermask = buffersize-1;
1979                         uint32_t bufferwsize = buffersize / bank->bus_width;
1980
1981                         /* fall back to memory writes */
1982                         while (count >= (uint32_t)bank->bus_width)
1983                         {
1984                                 int fallback;
1985                                 if ((write_p & 0xff) == 0)
1986                                 {
1987                                         LOG_INFO("Programming at %08" PRIx32 ", count %08" PRIx32 " bytes remaining", write_p, count);
1988                                 }
1989                                 fallback = 1;
1990                                 if ((bufferwsize > 0) && (count >= buffersize) && !(write_p & buffermask))
1991                                 {
1992                                         retval = cfi_write_words(bank, buffer, bufferwsize, write_p);
1993                                         if (retval == ERROR_OK)
1994                                         {
1995                                                 buffer += buffersize;
1996                                                 write_p += buffersize;
1997                                                 count -= buffersize;
1998                                                 fallback = 0;
1999                                         }
2000                                 }
2001                                 /* try the slow way? */
2002                                 if (fallback)
2003                                 {
2004                                         for (i = 0; i < bank->bus_width; i++)
2005                                                 current_word[i] = *buffer++;
2006
2007                                         retval = cfi_write_word(bank, current_word, write_p);
2008                                         if (retval != ERROR_OK)
2009                                                 return retval;
2010
2011                                         write_p += bank->bus_width;
2012                                         count -= bank->bus_width;
2013                                 }
2014                         }
2015                 }
2016                 else
2017                         return retval;
2018         }
2019
2020         /* return to read array mode, so we can read from flash again for padding */
2021         if ((retval = cfi_reset(bank)) != ERROR_OK)
2022         {
2023                 return retval;
2024         }
2025
2026         /* handle unaligned tail bytes */
2027         if (count > 0)
2028         {
2029                 LOG_INFO("Fixup %" PRId32 " unaligned tail bytes", count);
2030
2031                 /* read a complete word from flash */
2032                 if ((retval = target_read_memory(target, write_p, bank->bus_width, 1, current_word)) != ERROR_OK)
2033                         return retval;
2034
2035                 /* replace only bytes that must be written */
2036                 for (i = 0; (i < bank->bus_width) && (count > 0); i++, count--)
2037                         current_word[i] = *buffer++;
2038
2039                 retval = cfi_write_word(bank, current_word, write_p);
2040                 if (retval != ERROR_OK)
2041                         return retval;
2042         }
2043
2044         /* return to read array mode */
2045         return cfi_reset(bank);
2046 }
2047
2048 static void cfi_fixup_atmel_reversed_erase_regions(struct flash_bank *bank, void *param)
2049 {
2050         (void) param;
2051         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2052         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2053
2054         pri_ext->_reversed_geometry = 1;
2055 }
2056
2057 static void cfi_fixup_0002_erase_regions(struct flash_bank *bank, void *param)
2058 {
2059         int i;
2060         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2061         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2062         (void) param;
2063
2064         if ((pri_ext->_reversed_geometry) || (pri_ext->TopBottom == 3))
2065         {
2066                 LOG_DEBUG("swapping reversed erase region information on cmdset 0002 device");
2067
2068                 for (i = 0; i < cfi_info->num_erase_regions / 2; i++)
2069                 {
2070                         int j = (cfi_info->num_erase_regions - 1) - i;
2071                         uint32_t swap;
2072
2073                         swap = cfi_info->erase_region_info[i];
2074                         cfi_info->erase_region_info[i] = cfi_info->erase_region_info[j];
2075                         cfi_info->erase_region_info[j] = swap;
2076                 }
2077         }
2078 }
2079
2080 static void cfi_fixup_0002_unlock_addresses(struct flash_bank *bank, void *param)
2081 {
2082         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2083         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2084         struct cfi_unlock_addresses *unlock_addresses = param;
2085
2086         pri_ext->_unlock1 = unlock_addresses->unlock1;
2087         pri_ext->_unlock2 = unlock_addresses->unlock2;
2088 }
2089
2090
2091 static int cfi_query_string(struct flash_bank *bank, int address)
2092 {
2093         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2094         int retval;
2095
2096         if ((retval = cfi_send_command(bank, 0x98, flash_address(bank, 0, address))) != ERROR_OK)
2097         {
2098                 return retval;
2099         }
2100
2101         cfi_info->qry[0] = cfi_query_u8(bank, 0, 0x10);
2102         cfi_info->qry[1] = cfi_query_u8(bank, 0, 0x11);
2103         cfi_info->qry[2] = cfi_query_u8(bank, 0, 0x12);
2104
2105         LOG_DEBUG("CFI qry returned: 0x%2.2x 0x%2.2x 0x%2.2x", cfi_info->qry[0], cfi_info->qry[1], cfi_info->qry[2]);
2106
2107         if ((cfi_info->qry[0] != 'Q') || (cfi_info->qry[1] != 'R') || (cfi_info->qry[2] != 'Y'))
2108         {
2109                 if ((retval = cfi_reset(bank)) != ERROR_OK)
2110                 {
2111                         return retval;
2112                 }
2113                 LOG_ERROR("Could not probe bank: no QRY");
2114                 return ERROR_FLASH_BANK_INVALID;
2115         }
2116
2117         return ERROR_OK;
2118 }
2119
2120 static int cfi_probe(struct flash_bank *bank)
2121 {
2122         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2123         struct target *target = bank->target;
2124         int num_sectors = 0;
2125         int i;
2126         int sector = 0;
2127         uint32_t unlock1 = 0x555;
2128         uint32_t unlock2 = 0x2aa;
2129         int retval;
2130         uint8_t value_buf0[CFI_MAX_BUS_WIDTH], value_buf1[CFI_MAX_BUS_WIDTH];
2131
2132         if (bank->target->state != TARGET_HALTED)
2133         {
2134                 LOG_ERROR("Target not halted");
2135                 return ERROR_TARGET_NOT_HALTED;
2136         }
2137
2138         cfi_info->probed = 0;
2139         if (bank->sectors)
2140         {
2141                 free(bank->sectors);
2142                 bank->sectors = NULL;
2143         }
2144         if(cfi_info->erase_region_info)
2145         {
2146                 free(cfi_info->erase_region_info);
2147                 cfi_info->erase_region_info = NULL;
2148         }
2149
2150         /* JEDEC standard JESD21C uses 0x5555 and 0x2aaa as unlock addresses,
2151          * while CFI compatible AMD/Spansion flashes use 0x555 and 0x2aa
2152          */
2153         if (cfi_info->jedec_probe)
2154         {
2155                 unlock1 = 0x5555;
2156                 unlock2 = 0x2aaa;
2157         }
2158
2159         /* switch to read identifier codes mode ("AUTOSELECT") */
2160         if ((retval = cfi_send_command(bank, 0xaa, flash_address(bank, 0, unlock1))) != ERROR_OK)
2161         {
2162                 return retval;
2163         }
2164         if ((retval = cfi_send_command(bank, 0x55, flash_address(bank, 0, unlock2))) != ERROR_OK)
2165         {
2166                 return retval;
2167         }
2168         if ((retval = cfi_send_command(bank, 0x90, flash_address(bank, 0, unlock1))) != ERROR_OK)
2169         {
2170                 return retval;
2171         }
2172
2173         if ((retval = target_read_memory(target, flash_address(bank, 0, 0x00), bank->bus_width, 1, value_buf0)) != ERROR_OK)
2174         {
2175                 return retval;
2176         }
2177         if ((retval = target_read_memory(target, flash_address(bank, 0, 0x01), bank->bus_width, 1, value_buf1)) != ERROR_OK)
2178         {
2179                 return retval;
2180         }
2181         switch (bank->chip_width) {
2182                 case 1:
2183                         cfi_info->manufacturer = *value_buf0;
2184                         cfi_info->device_id = *value_buf1;
2185                         break;
2186                 case 2:
2187                         cfi_info->manufacturer = target_buffer_get_u16(target, value_buf0);
2188                         cfi_info->device_id = target_buffer_get_u16(target, value_buf1);
2189                         break;
2190                 case 4:
2191                         cfi_info->manufacturer = target_buffer_get_u32(target, value_buf0);
2192                         cfi_info->device_id = target_buffer_get_u32(target, value_buf1);
2193                         break;
2194                 default:
2195                         LOG_ERROR("Unsupported bank chipwidth %d, can't probe memory", bank->chip_width);
2196                         return ERROR_FLASH_OPERATION_FAILED;
2197         }
2198
2199         LOG_INFO("Flash Manufacturer/Device: 0x%04x 0x%04x", cfi_info->manufacturer, cfi_info->device_id);
2200         /* switch back to read array mode */
2201         if ((retval = cfi_reset(bank)) != ERROR_OK)
2202         {
2203                 return retval;
2204         }
2205
2206         /* check device/manufacturer ID for known non-CFI flashes. */
2207         cfi_fixup_non_cfi(bank);
2208
2209         /* query only if this is a CFI compatible flash,
2210          * otherwise the relevant info has already been filled in
2211          */
2212         if (cfi_info->not_cfi == 0)
2213         {
2214                 int retval;
2215
2216                 /* enter CFI query mode
2217                  * according to JEDEC Standard No. 68.01,
2218                  * a single bus sequence with address = 0x55, data = 0x98 should put
2219                  * the device into CFI query mode.
2220                  *
2221                  * SST flashes clearly violate this, and we will consider them incompatbile for now
2222                  */
2223
2224                 retval = cfi_query_string(bank, 0x55);
2225                 if (retval != ERROR_OK)
2226                 {
2227                         /*
2228                          * Spansion S29WS-N CFI query fix is to try 0x555 if 0x55 fails. Should
2229                          * be harmless enough:
2230                          *
2231                          * http://www.infradead.org/pipermail/linux-mtd/2005-September/013618.html
2232                          */
2233                         LOG_USER("Try workaround w/0x555 instead of 0x55 to get QRY.");
2234                         retval = cfi_query_string(bank, 0x555);
2235                 }
2236                 if (retval != ERROR_OK)
2237                         return retval;
2238
2239                 cfi_info->pri_id = cfi_query_u16(bank, 0, 0x13);
2240                 cfi_info->pri_addr = cfi_query_u16(bank, 0, 0x15);
2241                 cfi_info->alt_id = cfi_query_u16(bank, 0, 0x17);
2242                 cfi_info->alt_addr = cfi_query_u16(bank, 0, 0x19);
2243
2244                 LOG_DEBUG("qry: '%c%c%c', pri_id: 0x%4.4x, pri_addr: 0x%4.4x, alt_id: 0x%4.4x, alt_addr: 0x%4.4x", cfi_info->qry[0], cfi_info->qry[1], cfi_info->qry[2], cfi_info->pri_id, cfi_info->pri_addr, cfi_info->alt_id, cfi_info->alt_addr);
2245
2246                 cfi_info->vcc_min = cfi_query_u8(bank, 0, 0x1b);
2247                 cfi_info->vcc_max = cfi_query_u8(bank, 0, 0x1c);
2248                 cfi_info->vpp_min = cfi_query_u8(bank, 0, 0x1d);
2249                 cfi_info->vpp_max = cfi_query_u8(bank, 0, 0x1e);
2250                 cfi_info->word_write_timeout_typ = cfi_query_u8(bank, 0, 0x1f);
2251                 cfi_info->buf_write_timeout_typ = cfi_query_u8(bank, 0, 0x20);
2252                 cfi_info->block_erase_timeout_typ = cfi_query_u8(bank, 0, 0x21);
2253                 cfi_info->chip_erase_timeout_typ = cfi_query_u8(bank, 0, 0x22);
2254                 cfi_info->word_write_timeout_max = cfi_query_u8(bank, 0, 0x23);
2255                 cfi_info->buf_write_timeout_max = cfi_query_u8(bank, 0, 0x24);
2256                 cfi_info->block_erase_timeout_max = cfi_query_u8(bank, 0, 0x25);
2257                 cfi_info->chip_erase_timeout_max = cfi_query_u8(bank, 0, 0x26);
2258
2259                 LOG_DEBUG("Vcc min: %x.%x, Vcc max: %x.%x, Vpp min: %u.%x, Vpp max: %u.%x",
2260                         (cfi_info->vcc_min & 0xf0) >> 4, cfi_info->vcc_min & 0x0f,
2261                         (cfi_info->vcc_max & 0xf0) >> 4, cfi_info->vcc_max & 0x0f,
2262                         (cfi_info->vpp_min & 0xf0) >> 4, cfi_info->vpp_min & 0x0f,
2263                         (cfi_info->vpp_max & 0xf0) >> 4, cfi_info->vpp_max & 0x0f);
2264                 LOG_DEBUG("typ. word write timeout: %u, typ. buf write timeout: %u, typ. block erase timeout: %u, typ. chip erase timeout: %u", 1 << cfi_info->word_write_timeout_typ, 1 << cfi_info->buf_write_timeout_typ,
2265                         1 << cfi_info->block_erase_timeout_typ, 1 << cfi_info->chip_erase_timeout_typ);
2266                 LOG_DEBUG("max. word write timeout: %u, max. buf write timeout: %u, max. block erase timeout: %u, max. chip erase timeout: %u", (1 << cfi_info->word_write_timeout_max) * (1 << cfi_info->word_write_timeout_typ),
2267                         (1 << cfi_info->buf_write_timeout_max) * (1 << cfi_info->buf_write_timeout_typ),
2268                         (1 << cfi_info->block_erase_timeout_max) * (1 << cfi_info->block_erase_timeout_typ),
2269                         (1 << cfi_info->chip_erase_timeout_max) * (1 << cfi_info->chip_erase_timeout_typ));
2270
2271                 cfi_info->dev_size = 1 << cfi_query_u8(bank, 0, 0x27);
2272                 cfi_info->interface_desc = cfi_query_u16(bank, 0, 0x28);
2273                 cfi_info->max_buf_write_size = cfi_query_u16(bank, 0, 0x2a);
2274                 cfi_info->num_erase_regions = cfi_query_u8(bank, 0, 0x2c);
2275
2276                 LOG_DEBUG("size: 0x%" PRIx32 ", interface desc: %i, max buffer write size: %x", cfi_info->dev_size, cfi_info->interface_desc, (1 << cfi_info->max_buf_write_size));
2277
2278                 if (cfi_info->num_erase_regions)
2279                 {
2280                         cfi_info->erase_region_info = malloc(4 * cfi_info->num_erase_regions);
2281                         for (i = 0; i < cfi_info->num_erase_regions; i++)
2282                         {
2283                                 cfi_info->erase_region_info[i] = cfi_query_u32(bank, 0, 0x2d + (4 * i));
2284                                 LOG_DEBUG("erase region[%i]: %" PRIu32 " blocks of size 0x%" PRIx32 "",
2285                                           i,
2286                                           (cfi_info->erase_region_info[i] & 0xffff) + 1,
2287                                           (cfi_info->erase_region_info[i] >> 16) * 256);
2288                         }
2289                 }
2290                 else
2291                 {
2292                         cfi_info->erase_region_info = NULL;
2293                 }
2294
2295                 /* We need to read the primary algorithm extended query table before calculating
2296                  * the sector layout to be able to apply fixups
2297                  */
2298                 switch (cfi_info->pri_id)
2299                 {
2300                         /* Intel command set (standard and extended) */
2301                         case 0x0001:
2302                         case 0x0003:
2303                                 cfi_read_intel_pri_ext(bank);
2304                                 break;
2305                         /* AMD/Spansion, Atmel, ... command set */
2306                         case 0x0002:
2307                                 cfi_info->status_poll_mask = CFI_STATUS_POLL_MASK_DQ5_DQ6_DQ7; /* default for all CFI flashs */
2308                                 cfi_read_0002_pri_ext(bank);
2309                                 break;
2310                         default:
2311                                 LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2312                                 break;
2313                 }
2314
2315                 /* return to read array mode
2316                  * we use both reset commands, as some Intel flashes fail to recognize the 0xF0 command
2317                  */
2318                 if ((retval = cfi_reset(bank)) != ERROR_OK)
2319                 {
2320                         return retval;
2321                 }
2322         } /* end CFI case */
2323
2324         /* apply fixups depending on the primary command set */
2325         switch (cfi_info->pri_id)
2326         {
2327                 /* Intel command set (standard and extended) */
2328                 case 0x0001:
2329                 case 0x0003:
2330                         cfi_fixup(bank, cfi_0001_fixups);
2331                         break;
2332                 /* AMD/Spansion, Atmel, ... command set */
2333                 case 0x0002:
2334                         cfi_fixup(bank, cfi_0002_fixups);
2335                         break;
2336                 default:
2337                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2338                         break;
2339         }
2340
2341         if ((cfi_info->dev_size * bank->bus_width / bank->chip_width) != bank->size)
2342         {
2343                 LOG_WARNING("configuration specifies 0x%" PRIx32 " size, but a 0x%" PRIx32 " size flash was found", bank->size, cfi_info->dev_size);
2344         }
2345
2346         if (cfi_info->num_erase_regions == 0)
2347         {
2348                 /* a device might have only one erase block, spanning the whole device */
2349                 bank->num_sectors = 1;
2350                 bank->sectors = malloc(sizeof(struct flash_sector));
2351
2352                 bank->sectors[sector].offset = 0x0;
2353                 bank->sectors[sector].size = bank->size;
2354                 bank->sectors[sector].is_erased = -1;
2355                 bank->sectors[sector].is_protected = -1;
2356         }
2357         else
2358         {
2359                 uint32_t offset = 0;
2360
2361                 for (i = 0; i < cfi_info->num_erase_regions; i++)
2362                 {
2363                         num_sectors += (cfi_info->erase_region_info[i] & 0xffff) + 1;
2364                 }
2365
2366                 bank->num_sectors = num_sectors;
2367                 bank->sectors = malloc(sizeof(struct flash_sector) * num_sectors);
2368
2369                 for (i = 0; i < cfi_info->num_erase_regions; i++)
2370                 {
2371                         uint32_t j;
2372                         for (j = 0; j < (cfi_info->erase_region_info[i] & 0xffff) + 1; j++)
2373                         {
2374                                 bank->sectors[sector].offset = offset;
2375                                 bank->sectors[sector].size = ((cfi_info->erase_region_info[i] >> 16) * 256) * bank->bus_width / bank->chip_width;
2376                                 offset += bank->sectors[sector].size;
2377                                 bank->sectors[sector].is_erased = -1;
2378                                 bank->sectors[sector].is_protected = -1;
2379                                 sector++;
2380                         }
2381                 }
2382                 if (offset != (cfi_info->dev_size * bank->bus_width / bank->chip_width))
2383                 {
2384                         LOG_WARNING("CFI size is 0x%" PRIx32 ", but total sector size is 0x%" PRIx32 "", \
2385                                 (cfi_info->dev_size * bank->bus_width / bank->chip_width), offset);
2386                 }
2387         }
2388
2389         cfi_info->probed = 1;
2390
2391         return ERROR_OK;
2392 }
2393
2394 static int cfi_auto_probe(struct flash_bank *bank)
2395 {
2396         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2397         if (cfi_info->probed)
2398                 return ERROR_OK;
2399         return cfi_probe(bank);
2400 }
2401
2402 static int cfi_intel_protect_check(struct flash_bank *bank)
2403 {
2404         int retval;
2405         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2406         struct cfi_intel_pri_ext *pri_ext = cfi_info->pri_ext;
2407         int i;
2408
2409         /* check if block lock bits are supported on this device */
2410         if (!(pri_ext->blk_status_reg_mask & 0x1))
2411                 return ERROR_FLASH_OPERATION_FAILED;
2412
2413         if ((retval = cfi_send_command(bank, 0x90, flash_address(bank, 0, 0x55))) != ERROR_OK)
2414         {
2415                 return retval;
2416         }
2417
2418         for (i = 0; i < bank->num_sectors; i++)
2419         {
2420                 uint8_t block_status = cfi_get_u8(bank, i, 0x2);
2421
2422                 if (block_status & 1)
2423                         bank->sectors[i].is_protected = 1;
2424                 else
2425                         bank->sectors[i].is_protected = 0;
2426         }
2427
2428         return cfi_send_command(bank, 0xff, flash_address(bank, 0, 0x0));
2429 }
2430
2431 static int cfi_spansion_protect_check(struct flash_bank *bank)
2432 {
2433         int retval;
2434         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2435         struct cfi_spansion_pri_ext *pri_ext = cfi_info->pri_ext;
2436         int i;
2437
2438         if ((retval = cfi_send_command(bank, 0xaa, flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
2439         {
2440                 return retval;
2441         }
2442
2443         if ((retval = cfi_send_command(bank, 0x55, flash_address(bank, 0, pri_ext->_unlock2))) != ERROR_OK)
2444         {
2445                 return retval;
2446         }
2447
2448         if ((retval = cfi_send_command(bank, 0x90, flash_address(bank, 0, pri_ext->_unlock1))) != ERROR_OK)
2449         {
2450                 return retval;
2451         }
2452
2453         for (i = 0; i < bank->num_sectors; i++)
2454         {
2455                 uint8_t block_status = cfi_get_u8(bank, i, 0x2);
2456
2457                 if (block_status & 1)
2458                         bank->sectors[i].is_protected = 1;
2459                 else
2460                         bank->sectors[i].is_protected = 0;
2461         }
2462
2463         return cfi_send_command(bank, 0xf0, flash_address(bank, 0, 0x0));
2464 }
2465
2466 static int cfi_protect_check(struct flash_bank *bank)
2467 {
2468         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2469
2470         if (bank->target->state != TARGET_HALTED)
2471         {
2472                 LOG_ERROR("Target not halted");
2473                 return ERROR_TARGET_NOT_HALTED;
2474         }
2475
2476         if (cfi_info->qry[0] != 'Q')
2477                 return ERROR_FLASH_BANK_NOT_PROBED;
2478
2479         switch (cfi_info->pri_id)
2480         {
2481                 case 1:
2482                 case 3:
2483                         return cfi_intel_protect_check(bank);
2484                         break;
2485                 case 2:
2486                         return cfi_spansion_protect_check(bank);
2487                         break;
2488                 default:
2489                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2490                         break;
2491         }
2492
2493         return ERROR_OK;
2494 }
2495
2496 static int cfi_info(struct flash_bank *bank, char *buf, int buf_size)
2497 {
2498         int printed;
2499         struct cfi_flash_bank *cfi_info = bank->driver_priv;
2500
2501         if (cfi_info->qry[0] == (char)-1)
2502         {
2503                 printed = snprintf(buf, buf_size, "\ncfi flash bank not probed yet\n");
2504                 return ERROR_OK;
2505         }
2506
2507         if (cfi_info->not_cfi == 0)
2508                 printed = snprintf(buf, buf_size, "\ncfi information:\n");
2509         else
2510                 printed = snprintf(buf, buf_size, "\nnon-cfi flash:\n");
2511         buf += printed;
2512         buf_size -= printed;
2513
2514         printed = snprintf(buf, buf_size, "\nmfr: 0x%4.4x, id:0x%4.4x\n",
2515                 cfi_info->manufacturer, cfi_info->device_id);
2516         buf += printed;
2517         buf_size -= printed;
2518
2519         if (cfi_info->not_cfi == 0)
2520         {
2521         printed = snprintf(buf, buf_size, "qry: '%c%c%c', pri_id: 0x%4.4x, pri_addr: 0x%4.4x, alt_id: 0x%4.4x, alt_addr: 0x%4.4x\n", cfi_info->qry[0], cfi_info->qry[1], cfi_info->qry[2], cfi_info->pri_id, cfi_info->pri_addr, cfi_info->alt_id, cfi_info->alt_addr);
2522         buf += printed;
2523         buf_size -= printed;
2524
2525                 printed = snprintf(buf, buf_size, "Vcc min: %x.%x, Vcc max: %x.%x, Vpp min: %u.%x, Vpp max: %u.%x\n",
2526                                    (cfi_info->vcc_min & 0xf0) >> 4, cfi_info->vcc_min & 0x0f,
2527         (cfi_info->vcc_max & 0xf0) >> 4, cfi_info->vcc_max & 0x0f,
2528         (cfi_info->vpp_min & 0xf0) >> 4, cfi_info->vpp_min & 0x0f,
2529         (cfi_info->vpp_max & 0xf0) >> 4, cfi_info->vpp_max & 0x0f);
2530         buf += printed;
2531         buf_size -= printed;
2532
2533                 printed = snprintf(buf, buf_size, "typ. word write timeout: %u, typ. buf write timeout: %u, typ. block erase timeout: %u, typ. chip erase timeout: %u\n",
2534                                    1 << cfi_info->word_write_timeout_typ,
2535                                    1 << cfi_info->buf_write_timeout_typ,
2536                                    1 << cfi_info->block_erase_timeout_typ,
2537                                    1 << cfi_info->chip_erase_timeout_typ);
2538         buf += printed;
2539         buf_size -= printed;
2540
2541                 printed = snprintf(buf, buf_size, "max. word write timeout: %u, max. buf write timeout: %u, max. block erase timeout: %u, max. chip erase timeout: %u\n",
2542                                    (1 << cfi_info->word_write_timeout_max) * (1 << cfi_info->word_write_timeout_typ),
2543                   (1 << cfi_info->buf_write_timeout_max) * (1 << cfi_info->buf_write_timeout_typ),
2544                   (1 << cfi_info->block_erase_timeout_max) * (1 << cfi_info->block_erase_timeout_typ),
2545                   (1 << cfi_info->chip_erase_timeout_max) * (1 << cfi_info->chip_erase_timeout_typ));
2546         buf += printed;
2547         buf_size -= printed;
2548
2549                 printed = snprintf(buf, buf_size, "size: 0x%" PRIx32 ", interface desc: %i, max buffer write size: %x\n",
2550                                    cfi_info->dev_size,
2551                                    cfi_info->interface_desc,
2552                                    1 << cfi_info->max_buf_write_size);
2553         buf += printed;
2554         buf_size -= printed;
2555
2556         switch (cfi_info->pri_id)
2557         {
2558                 case 1:
2559                 case 3:
2560                         cfi_intel_info(bank, buf, buf_size);
2561                         break;
2562                 case 2:
2563                         cfi_spansion_info(bank, buf, buf_size);
2564                         break;
2565                 default:
2566                         LOG_ERROR("cfi primary command set %i unsupported", cfi_info->pri_id);
2567                         break;
2568         }
2569         }
2570
2571         return ERROR_OK;
2572 }
2573
2574 struct flash_driver cfi_flash = {
2575         .name = "cfi",
2576         .flash_bank_command = cfi_flash_bank_command,
2577         .erase = cfi_erase,
2578         .protect = cfi_protect,
2579         .write = cfi_write,
2580         .read = cfi_read,
2581         .probe = cfi_probe,
2582         .auto_probe = cfi_auto_probe,
2583         /* FIXME: access flash at bus_width size */
2584         .erase_check = default_flash_blank_check,
2585         .protect_check = cfi_protect_check,
2586         .info = cfi_info,
2587 };