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