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