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