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