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