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