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