494fd66c78126066b28cf4a02d6bc1262b8f746f
[fw/openocd] / src / flash / nor / lpc2900.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 /***************************************************************************
4  *   Copyright (C) 2009 by                                                 *
5  *   Rolf Meeser <rolfm_9dq@yahoo.de>                                      *
6  ***************************************************************************/
7
8 #ifdef HAVE_CONFIG_H
9 #include "config.h"
10 #endif
11
12 #include "imp.h"
13 #include <helper/binarybuffer.h>
14 #include <target/algorithm.h>
15 #include <target/arm.h>
16 #include <target/image.h>
17
18 /* 1024 bytes */
19 #define KiB                 1024
20
21 /* Some flash constants */
22 #define FLASH_PAGE_SIZE     512         /* bytes */
23 #define FLASH_ERASE_TIME    100000      /* microseconds */
24 #define FLASH_PROGRAM_TIME  1000        /* microseconds */
25
26 /* Chip ID / Feature Registers */
27 #define CHIPID          0xE0000000      /* Chip ID */
28 #define FEAT0           0xE0000100      /* Chip feature 0 */
29 #define FEAT1           0xE0000104      /* Chip feature 1 */
30 #define FEAT2           0xE0000108      /* Chip feature 2 (contains flash size indicator) */
31 #define FEAT3           0xE000010C      /* Chip feature 3 */
32
33 #define EXPECTED_CHIPID 0x209CE02B      /* Chip ID of all LPC2900 devices */
34
35 /* Flash/EEPROM Control Registers */
36 #define FCTR            0x20200000      /* Flash control */
37 #define FPTR            0x20200008      /* Flash program-time */
38 #define FTCTR           0x2020000C      /* Flash test control */
39 #define FBWST           0x20200010      /* Flash bridge wait-state */
40 #define FCRA            0x2020001C      /* Flash clock divider */
41 #define FMSSTART        0x20200020      /* Flash Built-In Self Test start address */
42 #define FMSSTOP         0x20200024      /* Flash Built-In Self Test stop address */
43 #define FMS16           0x20200028      /* Flash 16-bit signature */
44 #define FMSW0           0x2020002C      /* Flash 128-bit signature Word 0 */
45 #define FMSW1           0x20200030      /* Flash 128-bit signature Word 1 */
46 #define FMSW2           0x20200034      /* Flash 128-bit signature Word 2 */
47 #define FMSW3           0x20200038      /* Flash 128-bit signature Word 3 */
48
49 #define EECMD           0x20200080      /* EEPROM command */
50 #define EEADDR          0x20200084      /* EEPROM address */
51 #define EEWDATA         0x20200088      /* EEPROM write data */
52 #define EERDATA         0x2020008C      /* EEPROM read data */
53 #define EEWSTATE        0x20200090      /* EEPROM wait state */
54 #define EECLKDIV        0x20200094      /* EEPROM clock divider */
55 #define EEPWRDWN        0x20200098      /* EEPROM power-down/start */
56 #define EEMSSTART       0x2020009C      /* EEPROM BIST start address */
57 #define EEMSSTOP        0x202000A0      /* EEPROM BIST stop address */
58 #define EEMSSIG         0x202000A4      /* EEPROM 24-bit BIST signature */
59
60 #define INT_CLR_ENABLE  0x20200FD8      /* Flash/EEPROM interrupt clear enable */
61 #define INT_SET_ENABLE  0x20200FDC      /* Flash/EEPROM interrupt set enable */
62 #define INT_STATUS      0x20200FE0      /* Flash/EEPROM interrupt status */
63 #define INT_ENABLE      0x20200FE4      /* Flash/EEPROM interrupt enable */
64 #define INT_CLR_STATUS  0x20200FE8      /* Flash/EEPROM interrupt clear status */
65 #define INT_SET_STATUS  0x20200FEC      /* Flash/EEPROM interrupt set status */
66
67 /* Interrupt sources */
68 #define INTSRC_END_OF_PROG    (1 << 28)
69 #define INTSRC_END_OF_BIST    (1 << 27)
70 #define INTSRC_END_OF_RDWR    (1 << 26)
71 #define INTSRC_END_OF_MISR    (1 << 2)
72 #define INTSRC_END_OF_BURN    (1 << 1)
73 #define INTSRC_END_OF_ERASE   (1 << 0)
74
75 /* FCTR bits */
76 #define FCTR_FS_LOADREQ       (1 << 15)
77 #define FCTR_FS_CACHECLR      (1 << 14)
78 #define FCTR_FS_CACHEBYP      (1 << 13)
79 #define FCTR_FS_PROGREQ       (1 << 12)
80 #define FCTR_FS_RLS           (1 << 11)
81 #define FCTR_FS_PDL           (1 << 10)
82 #define FCTR_FS_PD            (1 << 9)
83 #define FCTR_FS_WPB           (1 << 7)
84 #define FCTR_FS_ISS           (1 << 6)
85 #define FCTR_FS_RLD           (1 << 5)
86 #define FCTR_FS_DCR           (1 << 4)
87 #define FCTR_FS_WEB           (1 << 2)
88 #define FCTR_FS_WRE           (1 << 1)
89 #define FCTR_FS_CS            (1 << 0)
90 /* FPTR bits */
91 #define FPTR_EN_T             (1 << 15)
92 /* FTCTR bits */
93 #define FTCTR_FS_BYPASS_R     (1 << 29)
94 #define FTCTR_FS_BYPASS_W     (1 << 28)
95 /* FMSSTOP bits */
96 #define FMSSTOP_MISR_START    (1 << 17)
97 /* EEMSSTOP bits */
98 #define EEMSSTOP_STRTBIST     (1 << 31)
99
100 /* Index sector */
101 #define ISS_CUSTOMER_START1   (0x830)
102 #define ISS_CUSTOMER_END1     (0xA00)
103 #define ISS_CUSTOMER_SIZE1    (ISS_CUSTOMER_END1 - ISS_CUSTOMER_START1)
104 #define ISS_CUSTOMER_NWORDS1  (ISS_CUSTOMER_SIZE1 / 4)
105 #define ISS_CUSTOMER_START2   (0xA40)
106 #define ISS_CUSTOMER_END2     (0xC00)
107 #define ISS_CUSTOMER_SIZE2    (ISS_CUSTOMER_END2 - ISS_CUSTOMER_START2)
108 #define ISS_CUSTOMER_NWORDS2  (ISS_CUSTOMER_SIZE2 / 4)
109 #define ISS_CUSTOMER_SIZE     (ISS_CUSTOMER_SIZE1 + ISS_CUSTOMER_SIZE2)
110
111 /**
112  * Private data for \c lpc2900 flash driver.
113  */
114 struct lpc2900_flash_bank {
115         /**
116          * This flag is set when the device has been successfully probed.
117          */
118         bool is_probed;
119
120         /**
121          * Holds the value read from CHIPID register.
122          * The driver will not load if the chipid doesn't match the expected
123          * value of 0x209CE02B of the LPC2900 family. A probe will only be done
124          * if the chipid does not yet contain the expected value.
125          */
126         uint32_t chipid;
127
128         /**
129          * String holding device name.
130          * This string is set by the probe function to the type number of the
131          * device. It takes the form "LPC29xx".
132          */
133         char *target_name;
134
135         /**
136          * System clock frequency.
137          * Holds the clock frequency in Hz, as passed by the configuration file
138          * to the <tt>flash bank</tt> command.
139          */
140         uint32_t clk_sys_fmc;
141
142         /**
143          * Flag to indicate that dangerous operations are possible.
144          * This flag can be set by passing the correct password to the
145          * <tt>lpc2900 password</tt> command. If set, other dangerous commands,
146          * which operate on the index sector, can be executed.
147          */
148         uint32_t risky;
149
150         /**
151          * Maximum contiguous block of internal SRAM (bytes).
152          * Autodetected by the driver. Not the total amount of SRAM, only
153          * the largest \em contiguous block!
154          */
155         uint32_t max_ram_block;
156
157 };
158
159 static uint32_t lpc2900_wait_status(struct flash_bank *bank, uint32_t mask, int timeout);
160 static void lpc2900_setup(struct flash_bank *bank);
161 static uint32_t lpc2900_is_ready(struct flash_bank *bank);
162 static uint32_t lpc2900_read_security_status(struct flash_bank *bank);
163 static uint32_t lpc2900_run_bist128(struct flash_bank *bank,
164                 uint32_t addr_from, uint32_t addr_to,
165                 uint32_t signature[4]);
166 static unsigned int lpc2900_address2sector(struct flash_bank *bank, uint32_t offset);
167 static uint32_t lpc2900_calc_tr(uint32_t clock_var, uint32_t time_var);
168
169 /***********************  Helper functions  **************************/
170
171 /**
172  * Wait for an event in mask to occur in INT_STATUS.
173  *
174  * Return when an event occurs, or after a timeout.
175  *
176  * @param[in] bank Pointer to the flash bank descriptor
177  * @param[in] mask Mask to be used for INT_STATUS
178  * @param[in] timeout Timeout in ms
179  */
180 static uint32_t lpc2900_wait_status(struct flash_bank *bank,
181         uint32_t mask,
182         int timeout)
183 {
184         uint32_t int_status;
185         struct target *target = bank->target;
186
187         do {
188                 alive_sleep(1);
189                 timeout--;
190                 target_read_u32(target, INT_STATUS, &int_status);
191         } while (((int_status & mask) == 0) && (timeout != 0));
192
193         if (timeout == 0) {
194                 LOG_DEBUG("Timeout!");
195                 return ERROR_FLASH_OPERATION_FAILED;
196         }
197
198         return ERROR_OK;
199 }
200
201 /**
202  * Set up the flash for erase/program operations.
203  *
204  * Enable the flash, and set the correct CRA clock of 66 kHz.
205  *
206  * @param bank Pointer to the flash bank descriptor
207  */
208 static void lpc2900_setup(struct flash_bank *bank)
209 {
210         uint32_t fcra;
211         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
212
213         /* Power up the flash block */
214         target_write_u32(bank->target, FCTR, FCTR_FS_WEB | FCTR_FS_CS);
215
216         fcra = (lpc2900_info->clk_sys_fmc / (3 * 66000)) - 1;
217         target_write_u32(bank->target, FCRA, fcra);
218 }
219
220 /**
221  * Check if device is ready.
222  *
223  * Check if device is ready for flash operation:
224  * Must have been successfully probed.
225  * Must be halted.
226  */
227 static uint32_t lpc2900_is_ready(struct flash_bank *bank)
228 {
229         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
230
231         if (!lpc2900_info->is_probed)
232                 return ERROR_FLASH_BANK_NOT_PROBED;
233
234         if (bank->target->state != TARGET_HALTED) {
235                 LOG_ERROR("Target not halted");
236                 return ERROR_TARGET_NOT_HALTED;
237         }
238
239         return ERROR_OK;
240 }
241
242 /**
243  * Read the status of sector security from the index sector.
244  *
245  * @param bank Pointer to the flash bank descriptor
246  */
247 static uint32_t lpc2900_read_security_status(struct flash_bank *bank)
248 {
249         uint32_t status = lpc2900_is_ready(bank);
250         if (status != ERROR_OK)
251                 return status;
252
253         struct target *target = bank->target;
254
255         /* Enable ISS access */
256         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB | FCTR_FS_ISS);
257
258         /* Read the relevant block of memory from the ISS sector */
259         uint32_t iss_secured_field[0x230/16][4];
260         target_read_memory(target, bank->base + 0xC00, 4, 0x230/4,
261                 (uint8_t *)iss_secured_field);
262
263         /* Disable ISS access */
264         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
265
266         /* Check status of each sector. Note that the sector numbering in the LPC2900
267          * is different from the logical sector numbers used in OpenOCD!
268          * Refer to the user manual for details.
269          *
270          * All zeros (16x 0x00) are treated as a secured sector (is_protected = 1)
271          * All ones (16x 0xFF) are treated as a non-secured sector (is_protected = 0)
272          * Anything else is undefined (is_protected = -1). This is treated as
273          * a protected sector!
274          */
275         for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
276                 unsigned int index_t;
277
278                 /* Convert logical sector number to physical sector number */
279                 if (sector <= 4)
280                         index_t = sector + 11;
281                 else if (sector <= 7)
282                         index_t = sector + 27;
283                 else
284                         index_t = sector - 8;
285
286                 bank->sectors[sector].is_protected = -1;
287
288                 if ((iss_secured_field[index_t][0] == 0x00000000) &&
289                         (iss_secured_field[index_t][1] == 0x00000000) &&
290                         (iss_secured_field[index_t][2] == 0x00000000) &&
291                         (iss_secured_field[index_t][3] == 0x00000000))
292                         bank->sectors[sector].is_protected = 1;
293
294                 if ((iss_secured_field[index_t][0] == 0xFFFFFFFF) &&
295                         (iss_secured_field[index_t][1] == 0xFFFFFFFF) &&
296                         (iss_secured_field[index_t][2] == 0xFFFFFFFF) &&
297                         (iss_secured_field[index_t][3] == 0xFFFFFFFF))
298                         bank->sectors[sector].is_protected = 0;
299         }
300
301         return ERROR_OK;
302 }
303
304 /**
305  * Use BIST to calculate a 128-bit hash value over a range of flash.
306  *
307  * @param bank Pointer to the flash bank descriptor
308  * @param addr_from
309  * @param addr_to
310  * @param signature
311  */
312 static uint32_t lpc2900_run_bist128(struct flash_bank *bank,
313         uint32_t addr_from,
314         uint32_t addr_to,
315         uint32_t signature[4])
316 {
317         struct target *target = bank->target;
318
319         /* Clear END_OF_MISR interrupt status */
320         target_write_u32(target, INT_CLR_STATUS, INTSRC_END_OF_MISR);
321
322         /* Start address */
323         target_write_u32(target, FMSSTART, addr_from >> 4);
324         /* End address, and issue start command */
325         target_write_u32(target, FMSSTOP, (addr_to >> 4) | FMSSTOP_MISR_START);
326
327         /* Poll for end of operation. Calculate a reasonable timeout. */
328         if (lpc2900_wait_status(bank, INTSRC_END_OF_MISR, 1000) != ERROR_OK)
329                 return ERROR_FLASH_OPERATION_FAILED;
330
331         /* Return the signature */
332         uint8_t sig_buf[4 * 4];
333         target_read_memory(target, FMSW0, 4, 4, sig_buf);
334         target_buffer_get_u32_array(target, sig_buf, 4, signature);
335
336         return ERROR_OK;
337 }
338
339 /**
340  * Return sector number for given address.
341  *
342  * Return the (logical) sector number for a given relative address.
343  * No sanity check is done. It assumed that the address is valid.
344  *
345  * @param bank Pointer to the flash bank descriptor
346  * @param offset Offset address relative to bank start
347  */
348 static unsigned int lpc2900_address2sector(struct flash_bank *bank,
349         uint32_t offset)
350 {
351         uint32_t address = bank->base + offset;
352
353         /* Run through all sectors of this bank */
354         for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
355                 /* Return immediately if address is within the current sector */
356                 if (address < (bank->sectors[sector].offset + bank->sectors[sector].size))
357                         return sector;
358         }
359
360         /* We should never come here. If we do, return an arbitrary sector number. */
361         return 0;
362 }
363
364 /**
365  * Write one page to the index sector.
366  *
367  * @param bank Pointer to the flash bank descriptor
368  * @param pagenum Page number (0...7)
369  * @param page Page array (FLASH_PAGE_SIZE bytes)
370  */
371 static int lpc2900_write_index_page(struct flash_bank *bank,
372         int pagenum,
373         uint8_t page[FLASH_PAGE_SIZE])
374 {
375         /* Only pages 4...7 are user writable */
376         if ((pagenum < 4) || (pagenum > 7)) {
377                 LOG_ERROR("Refuse to burn index sector page %d", pagenum);
378                 return ERROR_COMMAND_ARGUMENT_INVALID;
379         }
380
381         /* Get target, and check if it's halted */
382         struct target *target = bank->target;
383         if (target->state != TARGET_HALTED) {
384                 LOG_ERROR("Target not halted");
385                 return ERROR_TARGET_NOT_HALTED;
386         }
387
388         /* Private info */
389         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
390
391         /* Enable flash block and set the correct CRA clock of 66 kHz */
392         lpc2900_setup(bank);
393
394         /* Un-protect the index sector */
395         target_write_u32(target, bank->base, 0);
396         target_write_u32(target, FCTR,
397                 FCTR_FS_LOADREQ | FCTR_FS_WPB | FCTR_FS_ISS |
398                 FCTR_FS_WEB | FCTR_FS_WRE | FCTR_FS_CS);
399
400         /* Set latch load mode */
401         target_write_u32(target, FCTR,
402                 FCTR_FS_ISS | FCTR_FS_WEB | FCTR_FS_WRE | FCTR_FS_CS);
403
404         /* Write whole page to flash data latches */
405         if (target_write_memory(target,
406                         bank->base + pagenum * FLASH_PAGE_SIZE,
407                         4, FLASH_PAGE_SIZE / 4, page) != ERROR_OK) {
408                 LOG_ERROR("Index sector write failed @ page %d", pagenum);
409                 target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
410
411                 return ERROR_FLASH_OPERATION_FAILED;
412         }
413
414         /* Clear END_OF_BURN interrupt status */
415         target_write_u32(target, INT_CLR_STATUS, INTSRC_END_OF_BURN);
416
417         /* Set the program/erase time to FLASH_PROGRAM_TIME */
418         target_write_u32(target, FPTR,
419                 FPTR_EN_T | lpc2900_calc_tr(lpc2900_info->clk_sys_fmc,
420                         FLASH_PROGRAM_TIME));
421
422         /* Trigger flash write */
423         target_write_u32(target, FCTR,
424                 FCTR_FS_PROGREQ | FCTR_FS_ISS |
425                 FCTR_FS_WPB | FCTR_FS_WRE | FCTR_FS_CS);
426
427         /* Wait for the end of the write operation. If it's not over after one
428          * second, something went dreadfully wrong... :-(
429          */
430         if (lpc2900_wait_status(bank, INTSRC_END_OF_BURN, 1000) != ERROR_OK) {
431                 LOG_ERROR("Index sector write failed @ page %d", pagenum);
432                 target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
433
434                 return ERROR_FLASH_OPERATION_FAILED;
435         }
436
437         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
438
439         return ERROR_OK;
440 }
441
442 /**
443  * Calculate FPTR.TR register value for desired program/erase time.
444  *
445  * @param clock_var System clock in Hz
446  * @param time_var Program/erase time in Âµs
447  */
448 static uint32_t lpc2900_calc_tr(uint32_t clock_var, uint32_t time_var)
449 {
450         /*           ((time[µs]/1e6) * f[Hz]) + 511
451          * FPTR.TR = -------------------------------
452          *                         512
453          */
454
455         uint32_t tr_val = (uint32_t)((((time_var / 1e6) * clock_var) + 511.0) / 512.0);
456
457         return tr_val;
458 }
459
460 /***********************  Private flash commands  **************************/
461
462
463 /**
464  * Command to determine the signature of the whole flash.
465  *
466  * Uses the Built-In-Self-Test (BIST) to generate a 128-bit hash value
467  * of the flash content.
468  */
469 COMMAND_HANDLER(lpc2900_handle_signature_command)
470 {
471         uint32_t status;
472         uint32_t signature[4];
473
474         if (CMD_ARGC < 1)
475                 return ERROR_COMMAND_SYNTAX_ERROR;
476
477         struct flash_bank *bank;
478         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
479         if (retval != ERROR_OK)
480                 return retval;
481
482         if (bank->target->state != TARGET_HALTED) {
483                 LOG_ERROR("Target not halted");
484                 return ERROR_TARGET_NOT_HALTED;
485         }
486
487         /* Run BIST over whole flash range */
488         status = lpc2900_run_bist128(bank, bank->base, bank->base + (bank->size - 1), signature);
489         if (status != ERROR_OK)
490                 return status;
491
492         command_print(CMD, "signature: 0x%8.8" PRIx32
493                 ":0x%8.8" PRIx32
494                 ":0x%8.8" PRIx32
495                 ":0x%8.8" PRIx32,
496                 signature[3], signature[2], signature[1], signature[0]);
497
498         return ERROR_OK;
499 }
500
501 /**
502  * Store customer info in file.
503  *
504  * Read customer info from index sector, and store that block of data into
505  * a disk file. The format is binary.
506  */
507 COMMAND_HANDLER(lpc2900_handle_read_custom_command)
508 {
509         if (CMD_ARGC < 2)
510                 return ERROR_COMMAND_SYNTAX_ERROR;
511
512         struct flash_bank *bank;
513         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
514         if (retval != ERROR_OK)
515                 return retval;
516
517         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
518         lpc2900_info->risky = 0;
519
520         /* Get target, and check if it's halted */
521         struct target *target = bank->target;
522         if (target->state != TARGET_HALTED) {
523                 LOG_ERROR("Target not halted");
524                 return ERROR_TARGET_NOT_HALTED;
525         }
526
527         /* Storage for customer info. Read in two parts */
528         uint8_t customer[4 * (ISS_CUSTOMER_NWORDS1 + ISS_CUSTOMER_NWORDS2)];
529
530         /* Enable access to index sector */
531         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB | FCTR_FS_ISS);
532
533         /* Read two parts */
534         target_read_memory(target, bank->base+ISS_CUSTOMER_START1, 4,
535                 ISS_CUSTOMER_NWORDS1,
536                 &customer[0]);
537         target_read_memory(target, bank->base+ISS_CUSTOMER_START2, 4,
538                 ISS_CUSTOMER_NWORDS2,
539                 &customer[4 * ISS_CUSTOMER_NWORDS1]);
540
541         /* Deactivate access to index sector */
542         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
543
544         /* Try and open the file */
545         struct fileio *fileio;
546         const char *filename = CMD_ARGV[1];
547         int ret = fileio_open(&fileio, filename, FILEIO_WRITE, FILEIO_BINARY);
548         if (ret != ERROR_OK) {
549                 LOG_WARNING("Could not open file %s", filename);
550                 return ret;
551         }
552
553         size_t nwritten;
554         ret = fileio_write(fileio, sizeof(customer), customer, &nwritten);
555         if (ret != ERROR_OK) {
556                 LOG_ERROR("Write operation to file %s failed", filename);
557                 fileio_close(fileio);
558                 return ret;
559         }
560
561         fileio_close(fileio);
562
563         return ERROR_OK;
564 }
565
566 /**
567  * Enter password to enable potentially dangerous options.
568  */
569 COMMAND_HANDLER(lpc2900_handle_password_command)
570 {
571         if (CMD_ARGC < 2)
572                 return ERROR_COMMAND_SYNTAX_ERROR;
573
574         struct flash_bank *bank;
575         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
576         if (retval != ERROR_OK)
577                 return retval;
578
579         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
580
581 #define ISS_PASSWORD "I_know_what_I_am_doing"
582
583         lpc2900_info->risky = !strcmp(CMD_ARGV[1], ISS_PASSWORD);
584
585         if (!lpc2900_info->risky) {
586                 command_print(CMD, "Wrong password (use '%s')", ISS_PASSWORD);
587                 return ERROR_COMMAND_ARGUMENT_INVALID;
588         }
589
590         command_print(CMD,
591                 "Potentially dangerous operation allowed in next command!");
592
593         return ERROR_OK;
594 }
595
596 /**
597  * Write customer info from file to the index sector.
598  */
599 COMMAND_HANDLER(lpc2900_handle_write_custom_command)
600 {
601         if (CMD_ARGC < 2)
602                 return ERROR_COMMAND_SYNTAX_ERROR;
603
604         struct flash_bank *bank;
605         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
606         if (retval != ERROR_OK)
607                 return retval;
608
609         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
610
611         /* Check if command execution is allowed. */
612         if (!lpc2900_info->risky) {
613                 command_print(CMD, "Command execution not allowed!");
614                 return ERROR_COMMAND_ARGUMENT_INVALID;
615         }
616         lpc2900_info->risky = 0;
617
618         /* Get target, and check if it's halted */
619         struct target *target = bank->target;
620         if (target->state != TARGET_HALTED) {
621                 LOG_ERROR("Target not halted");
622                 return ERROR_TARGET_NOT_HALTED;
623         }
624
625         /* The image will always start at offset 0 */
626         struct image image;
627         image.base_address_set = true;
628         image.base_address = 0;
629         image.start_address_set = false;
630
631         const char *filename = CMD_ARGV[1];
632         const char *type = (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL;
633         retval = image_open(&image, filename, type);
634         if (retval != ERROR_OK)
635                 return retval;
636
637         /* Do a sanity check: The image must be exactly the size of the customer
638            programmable area. Any other size is rejected. */
639         if (image.num_sections != 1) {
640                 LOG_ERROR("Only one section allowed in image file.");
641                 return ERROR_COMMAND_SYNTAX_ERROR;
642         }
643         if ((image.sections[0].base_address != 0) ||
644                         (image.sections[0].size != ISS_CUSTOMER_SIZE)) {
645                 LOG_ERROR("Incorrect image file size. Expected %d, "
646                         "got %" PRIu32,
647                         ISS_CUSTOMER_SIZE, image.sections[0].size);
648                 return ERROR_COMMAND_SYNTAX_ERROR;
649         }
650
651         /* Well boys, I reckon this is it... */
652
653         /* Customer info is split into two blocks in pages 4 and 5. */
654         uint8_t page[FLASH_PAGE_SIZE];
655
656         /* Page 4 */
657         uint32_t offset = ISS_CUSTOMER_START1 % FLASH_PAGE_SIZE;
658         memset(page, 0xff, FLASH_PAGE_SIZE);
659         size_t size_read;
660         retval = image_read_section(&image, 0, 0,
661                         ISS_CUSTOMER_SIZE1, &page[offset], &size_read);
662         if (retval != ERROR_OK) {
663                 LOG_ERROR("couldn't read from file '%s'", filename);
664                 image_close(&image);
665                 return retval;
666         }
667         retval = lpc2900_write_index_page(bank, 4, page);
668         if (retval != ERROR_OK) {
669                 image_close(&image);
670                 return retval;
671         }
672
673         /* Page 5 */
674         offset = ISS_CUSTOMER_START2 % FLASH_PAGE_SIZE;
675         memset(page, 0xff, FLASH_PAGE_SIZE);
676         retval = image_read_section(&image, 0, ISS_CUSTOMER_SIZE1,
677                         ISS_CUSTOMER_SIZE2, &page[offset], &size_read);
678         if (retval != ERROR_OK) {
679                 LOG_ERROR("couldn't read from file '%s'", filename);
680                 image_close(&image);
681                 return retval;
682         }
683         retval = lpc2900_write_index_page(bank, 5, page);
684         if (retval != ERROR_OK) {
685                 image_close(&image);
686                 return retval;
687         }
688
689         image_close(&image);
690
691         return ERROR_OK;
692 }
693
694 /**
695  * Activate 'sector security' for a range of sectors.
696  */
697 COMMAND_HANDLER(lpc2900_handle_secure_sector_command)
698 {
699         if (CMD_ARGC < 3)
700                 return ERROR_COMMAND_SYNTAX_ERROR;
701
702         /* Get the bank descriptor */
703         struct flash_bank *bank;
704         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
705         if (retval != ERROR_OK)
706                 return retval;
707
708         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
709
710         /* Check if command execution is allowed. */
711         if (!lpc2900_info->risky) {
712                 command_print(CMD, "Command execution not allowed! "
713                         "(use 'password' command first)");
714                 return ERROR_COMMAND_ARGUMENT_INVALID;
715         }
716         lpc2900_info->risky = 0;
717
718         /* Read sector range, and do a sanity check. */
719         unsigned int first, last;
720         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], first);
721         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], last);
722         if ((first >= bank->num_sectors) ||
723                         (last >= bank->num_sectors) ||
724                         (first > last)) {
725                 command_print(CMD, "Illegal sector range");
726                 return ERROR_COMMAND_ARGUMENT_INVALID;
727         }
728
729         uint8_t page[FLASH_PAGE_SIZE];
730
731         /* Sectors in page 6 */
732         if ((first <= 4) || (last >= 8)) {
733                 memset(&page, 0xff, FLASH_PAGE_SIZE);
734                 for (unsigned int sector = first; sector <= last; sector++) {
735                         if (sector <= 4)
736                                 memset(&page[0xB0 + 16*sector], 0, 16);
737                         else if (sector >= 8)
738                                 memset(&page[0x00 + 16*(sector - 8)], 0, 16);
739                 }
740
741                 retval = lpc2900_write_index_page(bank, 6, page);
742                 if (retval != ERROR_OK) {
743                         LOG_ERROR("failed to update index sector page 6");
744                         return retval;
745                 }
746         }
747
748         /* Sectors in page 7 */
749         if ((first <= 7) && (last >= 5)) {
750                 memset(&page, 0xff, FLASH_PAGE_SIZE);
751                 for (unsigned int sector = first; sector <= last; sector++) {
752                         if ((sector >= 5) && (sector <= 7))
753                                 memset(&page[0x00 + 16*(sector - 5)], 0, 16);
754                 }
755
756                 retval = lpc2900_write_index_page(bank, 7, page);
757                 if (retval != ERROR_OK) {
758                         LOG_ERROR("failed to update index sector page 7");
759                         return retval;
760                 }
761         }
762
763         command_print(CMD,
764                 "Sectors security will become effective after next power cycle");
765
766         /* Update the sector security status */
767         if (lpc2900_read_security_status(bank) != ERROR_OK) {
768                 LOG_ERROR("Cannot determine sector security status");
769                 return ERROR_FLASH_OPERATION_FAILED;
770         }
771
772         return ERROR_OK;
773 }
774
775 /**
776  * Activate JTAG protection.
777  */
778 COMMAND_HANDLER(lpc2900_handle_secure_jtag_command)
779 {
780         if (CMD_ARGC < 1)
781                 return ERROR_COMMAND_SYNTAX_ERROR;
782
783         /* Get the bank descriptor */
784         struct flash_bank *bank;
785         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
786         if (retval != ERROR_OK)
787                 return retval;
788
789         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
790
791         /* Check if command execution is allowed. */
792         if (!lpc2900_info->risky) {
793                 command_print(CMD, "Command execution not allowed! "
794                         "(use 'password' command first)");
795                 return ERROR_COMMAND_ARGUMENT_INVALID;
796         }
797         lpc2900_info->risky = 0;
798
799         /* Prepare page */
800         uint8_t page[FLASH_PAGE_SIZE];
801         memset(&page, 0xff, FLASH_PAGE_SIZE);
802
803
804         /* Insert "soft" protection word */
805         page[0x30 + 15] = 0x7F;
806         page[0x30 + 11] = 0x7F;
807         page[0x30 +  7] = 0x7F;
808         page[0x30 +  3] = 0x7F;
809
810         /* Write to page 5 */
811         retval = lpc2900_write_index_page(bank, 5, page);
812         if (retval != ERROR_OK) {
813                 LOG_ERROR("failed to update index sector page 5");
814                 return retval;
815         }
816
817         LOG_INFO("JTAG security set. Good bye!");
818
819         return ERROR_OK;
820 }
821
822 /***********************  Flash interface functions  **************************/
823
824 static const struct command_registration lpc2900_exec_command_handlers[] = {
825         {
826                 .name = "signature",
827                 .usage = "<bank>",
828                 .handler = lpc2900_handle_signature_command,
829                 .mode = COMMAND_EXEC,
830                 .help = "Calculate and display signature of flash bank.",
831         },
832         {
833                 .name = "read_custom",
834                 .handler = lpc2900_handle_read_custom_command,
835                 .mode = COMMAND_EXEC,
836                 .usage = "bank_id filename",
837                 .help = "Copies 912 bytes of customer information "
838                         "from index sector into file.",
839         },
840         {
841                 .name = "password",
842                 .handler = lpc2900_handle_password_command,
843                 .mode = COMMAND_EXEC,
844                 .usage = "bank_id password",
845                 .help = "Enter fixed password to enable 'dangerous' options.",
846         },
847         {
848                 .name = "write_custom",
849                 .handler = lpc2900_handle_write_custom_command,
850                 .mode = COMMAND_EXEC,
851                 .usage = "bank_id filename ('bin'|'ihex'|'elf'|'s19')",
852                 .help = "Copies 912 bytes of customer info from file "
853                         "to index sector.",
854         },
855         {
856                 .name = "secure_sector",
857                 .handler = lpc2900_handle_secure_sector_command,
858                 .mode = COMMAND_EXEC,
859                 .usage = "bank_id first_sector last_sector",
860                 .help = "Activate sector security for a range of sectors.  "
861                         "It will be effective after a power cycle.",
862         },
863         {
864                 .name = "secure_jtag",
865                 .handler = lpc2900_handle_secure_jtag_command,
866                 .mode = COMMAND_EXEC,
867                 .usage = "bank_id",
868                 .help = "Disable the JTAG port.  "
869                         "It will be effective after a power cycle.",
870         },
871         COMMAND_REGISTRATION_DONE
872 };
873
874 static const struct command_registration lpc2900_command_handlers[] = {
875         {
876                 .name = "lpc2900",
877                 .mode = COMMAND_ANY,
878                 .help = "LPC2900 flash command group",
879                 .usage = "",
880                 .chain = lpc2900_exec_command_handlers,
881         },
882         COMMAND_REGISTRATION_DONE
883 };
884
885 /** Evaluate flash bank command. */
886 FLASH_BANK_COMMAND_HANDLER(lpc2900_flash_bank_command)
887 {
888         struct lpc2900_flash_bank *lpc2900_info;
889
890         if (CMD_ARGC < 6)
891                 return ERROR_COMMAND_SYNTAX_ERROR;
892
893         lpc2900_info = malloc(sizeof(struct lpc2900_flash_bank));
894         bank->driver_priv = lpc2900_info;
895
896         /* Get flash clock.
897          * Reject it if we can't meet the requirements for program time
898          * (if clock too slow), or for erase time (clock too fast).
899          */
900         uint32_t clk_sys_fmc;
901         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[6], clk_sys_fmc);
902         lpc2900_info->clk_sys_fmc = clk_sys_fmc * 1000;
903
904         uint32_t clock_limit;
905         /* Check program time limit */
906         clock_limit = 512000000l / FLASH_PROGRAM_TIME;
907         if (lpc2900_info->clk_sys_fmc < clock_limit) {
908                 LOG_WARNING("flash clock must be at least %" PRIu32 " kHz",
909                         (clock_limit / 1000));
910                 return ERROR_FLASH_BANK_INVALID;
911         }
912
913         /* Check erase time limit */
914         clock_limit = (uint32_t)((32767.0 * 512.0 * 1e6) / FLASH_ERASE_TIME);
915         if (lpc2900_info->clk_sys_fmc > clock_limit) {
916                 LOG_WARNING("flash clock must be a maximum of %" PRIu32 " kHz",
917                         (clock_limit / 1000));
918                 return ERROR_FLASH_BANK_INVALID;
919         }
920
921         /* Chip ID will be obtained by probing the device later */
922         lpc2900_info->chipid = 0;
923         lpc2900_info->is_probed = false;
924
925         return ERROR_OK;
926 }
927
928 /**
929  * Erase sector(s).
930  *
931  * @param bank Pointer to the flash bank descriptor
932  * @param first First sector to be erased
933  * @param last Last sector (including) to be erased
934  */
935 static int lpc2900_erase(struct flash_bank *bank, unsigned int first,
936                 unsigned int last)
937 {
938         uint32_t status;
939         unsigned int last_unsecured_sector;
940         bool has_unsecured_sector;
941         struct target *target = bank->target;
942         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
943
944
945         status = lpc2900_is_ready(bank);
946         if (status != ERROR_OK)
947                 return status;
948
949         /* Sanity check on sector range */
950         if ((last < first) || (last >= bank->num_sectors)) {
951                 LOG_INFO("Bad sector range");
952                 return ERROR_FLASH_SECTOR_INVALID;
953         }
954
955         /* Update the info about secured sectors */
956         lpc2900_read_security_status(bank);
957
958         /* The selected sector range might include secured sectors. An attempt
959          * to erase such a sector will cause the erase to fail also for unsecured
960          * sectors. It is necessary to determine the last unsecured sector now,
961          * because we have to treat the last relevant sector in the list in
962          * a special way.
963          */
964         last_unsecured_sector = -1;
965         has_unsecured_sector = false;
966         for (unsigned int sector = first; sector <= last; sector++) {
967                 if (!bank->sectors[sector].is_protected) {
968                         last_unsecured_sector = sector;
969                         has_unsecured_sector = true;
970                 }
971         }
972
973         /* Exit now, in case of the rare constellation where all sectors in range
974          * are secured. This is regarded a success, since erasing/programming of
975          * secured sectors shall be handled transparently.
976          */
977         if (!has_unsecured_sector)
978                 return ERROR_OK;
979
980         /* Enable flash block and set the correct CRA clock of 66 kHz */
981         lpc2900_setup(bank);
982
983         /* Clear END_OF_ERASE interrupt status */
984         target_write_u32(target, INT_CLR_STATUS, INTSRC_END_OF_ERASE);
985
986         /* Set the program/erase timer to FLASH_ERASE_TIME */
987         target_write_u32(target, FPTR,
988                 FPTR_EN_T | lpc2900_calc_tr(lpc2900_info->clk_sys_fmc,
989                         FLASH_ERASE_TIME));
990
991         /* Sectors are marked for erasure, then erased all together */
992         for (unsigned int sector = first; sector <= last_unsecured_sector; sector++) {
993                 /* Only mark sectors that aren't secured. Any attempt to erase a group
994                  * of sectors will fail if any single one of them is secured!
995                  */
996                 if (!bank->sectors[sector].is_protected) {
997                         /* Unprotect the sector */
998                         target_write_u32(target, bank->sectors[sector].offset, 0);
999                         target_write_u32(target, FCTR,
1000                                 FCTR_FS_LOADREQ | FCTR_FS_WPB |
1001                                 FCTR_FS_WEB | FCTR_FS_WRE | FCTR_FS_CS);
1002
1003                         /* Mark the sector for erasure. The last sector in the list
1004                            triggers the erasure. */
1005                         target_write_u32(target, bank->sectors[sector].offset, 0);
1006                         if (sector == last_unsecured_sector) {
1007                                 target_write_u32(target, FCTR,
1008                                         FCTR_FS_PROGREQ | FCTR_FS_WPB | FCTR_FS_CS);
1009                         } else {
1010                                 target_write_u32(target, FCTR,
1011                                         FCTR_FS_LOADREQ | FCTR_FS_WPB |
1012                                         FCTR_FS_WEB | FCTR_FS_CS);
1013                         }
1014                 }
1015         }
1016
1017         /* Wait for the end of the erase operation. If it's not over after two seconds,
1018          * something went dreadfully wrong... :-(
1019          */
1020         if (lpc2900_wait_status(bank, INTSRC_END_OF_ERASE, 2000) != ERROR_OK)
1021                 return ERROR_FLASH_OPERATION_FAILED;
1022
1023         /* Normal flash operating mode */
1024         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
1025
1026         return ERROR_OK;
1027 }
1028
1029 /* lpc2900_protect command is not supported.
1030 * "Protection" in LPC2900 terms is handled transparently. Sectors will
1031 * automatically be unprotected as needed.
1032 * Instead we use the concept of sector security. A secured sector is shown
1033 * as "protected" in OpenOCD. Sector security is a permanent feature, and
1034 * cannot be disabled once activated.
1035 */
1036
1037 /**
1038  * Write data to flash.
1039  *
1040  * @param bank Pointer to the flash bank descriptor
1041  * @param buffer Buffer with data
1042  * @param offset Start address (relative to bank start)
1043  * @param count Number of bytes to be programmed
1044  */
1045 static int lpc2900_write(struct flash_bank *bank, const uint8_t *buffer,
1046         uint32_t offset, uint32_t count)
1047 {
1048         uint8_t page[FLASH_PAGE_SIZE];
1049         uint32_t status;
1050         uint32_t num_bytes;
1051         struct target *target = bank->target;
1052         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
1053         int retval;
1054
1055         static const uint32_t write_target_code[] = {
1056                 /* Set auto latch mode: FCTR=CS|WRE|WEB */
1057                 0xe3a0a007,     /* loop       mov r10, #0x007 */
1058                 0xe583a000,     /*            str r10,[r3,#0] */
1059
1060                 /* Load complete page into latches */
1061                 0xe3a06020,     /*            mov r6,#(512/16) */
1062                 0xe8b00f00,     /* next       ldmia r0!,{r8-r11} */
1063                 0xe8a10f00,     /*            stmia r1!,{r8-r11} */
1064                 0xe2566001,     /*            subs r6,#1 */
1065                 0x1afffffb,     /*            bne next */
1066
1067                 /* Clear END_OF_BURN interrupt status */
1068                 0xe3a0a002,     /*            mov r10,#(1 << 1) */
1069                 0xe583afe8,     /*            str r10,[r3,#0xfe8] */
1070
1071                 /* Set the erase time to FLASH_PROGRAM_TIME */
1072                 0xe5834008,     /*            str r4,[r3,#8] */
1073
1074                 /* Trigger flash write
1075                  * FCTR = CS | WRE | WPB | PROGREQ */
1076                 0xe3a0a083,     /*            mov r10,#0x83 */
1077                 0xe38aaa01,     /*            orr r10,#0x1000 */
1078                 0xe583a000,     /*            str r10,[r3,#0] */
1079
1080                 /* Wait for end of burn */
1081                 0xe593afe0,     /* wait       ldr r10,[r3,#0xfe0] */
1082                 0xe21aa002,     /*            ands r10,#(1 << 1) */
1083                 0x0afffffc,     /*            beq wait */
1084
1085                 /* End? */
1086                 0xe2522001,     /*            subs r2,#1 */
1087                 0x1affffed,     /*            bne loop */
1088
1089                 0xeafffffe      /* done       b done */
1090         };
1091
1092
1093         status = lpc2900_is_ready(bank);
1094         if (status != ERROR_OK)
1095                 return status;
1096
1097         /* Enable flash block and set the correct CRA clock of 66 kHz */
1098         lpc2900_setup(bank);
1099
1100         /* Update the info about secured sectors */
1101         lpc2900_read_security_status(bank);
1102
1103         /* Unprotect all involved sectors */
1104         for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
1105                 /* Start address in or before this sector?
1106                  * End address in or behind this sector? */
1107                 if (((bank->base + offset) <
1108                                 (bank->sectors[sector].offset + bank->sectors[sector].size)) &&
1109                                 ((bank->base + (offset + count - 1)) >= bank->sectors[sector].offset)) {
1110                         /* This sector is involved and needs to be unprotected.
1111                          * Don't do it for secured sectors.
1112                          */
1113                         if (!bank->sectors[sector].is_protected) {
1114                                 target_write_u32(target, bank->sectors[sector].offset, 0);
1115                                 target_write_u32(target, FCTR,
1116                                         FCTR_FS_LOADREQ | FCTR_FS_WPB |
1117                                         FCTR_FS_WEB | FCTR_FS_WRE | FCTR_FS_CS);
1118                         }
1119                 }
1120         }
1121
1122         /* Set the program/erase time to FLASH_PROGRAM_TIME */
1123         uint32_t prog_time = FPTR_EN_T | lpc2900_calc_tr(lpc2900_info->clk_sys_fmc, FLASH_PROGRAM_TIME);
1124
1125         /* If there is a working area of reasonable size, use it to program via
1126          * a target algorithm. If not, fall back to host programming. */
1127
1128         /* We need some room for target code. */
1129         const uint32_t target_code_size = sizeof(write_target_code);
1130
1131         /* Try working area allocation. Start with a large buffer, and try with
1132          * reduced size if that fails. */
1133         struct working_area *warea;
1134         uint32_t buffer_size = lpc2900_info->max_ram_block - 1 * KiB;
1135         while ((retval = target_alloc_working_area_try(target,
1136                                  buffer_size + target_code_size,
1137                                  &warea)) != ERROR_OK) {
1138                 /* Try a smaller buffer now, and stop if it's too small. */
1139                 buffer_size -= 1 * KiB;
1140                 if (buffer_size < 2 * KiB) {
1141                         LOG_INFO("no (large enough) working area, falling back to host mode");
1142                         warea = NULL;
1143                         break;
1144                 }
1145         }
1146
1147         if (warea) {
1148                 struct reg_param reg_params[5];
1149                 struct arm_algorithm arm_algo;
1150
1151                 /* We can use target mode. Download the algorithm. */
1152                 uint8_t code[sizeof(write_target_code)];
1153                 target_buffer_set_u32_array(target, code, ARRAY_SIZE(write_target_code),
1154                                 write_target_code);
1155                 retval = target_write_buffer(target, (warea->address) + buffer_size, sizeof(code), code);
1156                 if (retval != ERROR_OK) {
1157                         LOG_ERROR("Unable to write block write code to target");
1158                         target_free_all_working_areas(target);
1159                         return ERROR_FLASH_OPERATION_FAILED;
1160                 }
1161
1162                 init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
1163                 init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
1164                 init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
1165                 init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
1166                 init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
1167
1168                 /* Write to flash in large blocks */
1169                 while (count != 0) {
1170                         uint32_t this_npages;
1171                         const uint8_t *this_buffer;
1172                         unsigned int start_sector = lpc2900_address2sector(bank, offset);
1173
1174                         /* First page / last page / rest */
1175                         if (offset % FLASH_PAGE_SIZE) {
1176                                 /* Block doesn't start on page boundary.
1177                                  * Burn first partial page separately. */
1178                                 memset(&page, 0xff, sizeof(page));
1179                                 memcpy(&page[offset % FLASH_PAGE_SIZE],
1180                                         buffer,
1181                                         FLASH_PAGE_SIZE - (offset % FLASH_PAGE_SIZE));
1182                                 this_npages = 1;
1183                                 this_buffer = &page[0];
1184                                 count = count + (offset % FLASH_PAGE_SIZE);
1185                                 offset = offset - (offset % FLASH_PAGE_SIZE);
1186                         } else if (count < FLASH_PAGE_SIZE) {
1187                                 /* Download last incomplete page separately. */
1188                                 memset(&page, 0xff, sizeof(page));
1189                                 memcpy(&page, buffer, count);
1190                                 this_npages = 1;
1191                                 this_buffer = &page[0];
1192                                 count = FLASH_PAGE_SIZE;
1193                         } else {
1194                                 /* Download as many full pages as possible */
1195                                 this_npages = (count < buffer_size) ?
1196                                         count / FLASH_PAGE_SIZE :
1197                                         buffer_size / FLASH_PAGE_SIZE;
1198                                 this_buffer = buffer;
1199
1200                                 /* Make sure we stop at the next secured sector */
1201                                 unsigned int sector = start_sector + 1;
1202                                 while (sector < bank->num_sectors) {
1203                                         /* Secured? */
1204                                         if (bank->sectors[sector].is_protected) {
1205                                                 /* Is that next sector within the current block? */
1206                                                 if ((bank->sectors[sector].offset - bank->base) <
1207                                                                 (offset + (this_npages * FLASH_PAGE_SIZE))) {
1208                                                         /* Yes! Split the block */
1209                                                         this_npages =
1210                                                                 (bank->sectors[sector].offset -
1211                                                                  bank->base - offset)
1212                                                                 / FLASH_PAGE_SIZE;
1213                                                         break;
1214                                                 }
1215                                         }
1216
1217                                         sector++;
1218                                 }
1219                         }
1220
1221                         /* Skip the current sector if it is secured */
1222                         if (bank->sectors[start_sector].is_protected) {
1223                                 LOG_DEBUG("Skip secured sector %u",
1224                                         start_sector);
1225
1226                                 /* Stop if this is the last sector */
1227                                 if (start_sector == bank->num_sectors - 1)
1228                                         break;
1229
1230                                 /* Skip */
1231                                 uint32_t nskip = bank->sectors[start_sector].size -
1232                                         (offset % bank->sectors[start_sector].size);
1233                                 offset += nskip;
1234                                 buffer += nskip;
1235                                 count = (count >= nskip) ? (count - nskip) : 0;
1236                                 continue;
1237                         }
1238
1239                         /* Execute buffer download */
1240                         retval = target_write_buffer(target, warea->address,
1241                                         this_npages * FLASH_PAGE_SIZE, this_buffer);
1242                         if (retval != ERROR_OK) {
1243                                 LOG_ERROR("Unable to write data to target");
1244                                 target_free_all_working_areas(target);
1245                                 return ERROR_FLASH_OPERATION_FAILED;
1246                         }
1247
1248                         /* Prepare registers */
1249                         buf_set_u32(reg_params[0].value, 0, 32, warea->address);
1250                         buf_set_u32(reg_params[1].value, 0, 32, offset);
1251                         buf_set_u32(reg_params[2].value, 0, 32, this_npages);
1252                         buf_set_u32(reg_params[3].value, 0, 32, FCTR);
1253                         buf_set_u32(reg_params[4].value, 0, 32, FPTR_EN_T | prog_time);
1254
1255                         /* Execute algorithm, assume breakpoint for last instruction */
1256                         arm_algo.common_magic = ARM_COMMON_MAGIC;
1257                         arm_algo.core_mode = ARM_MODE_SVC;
1258                         arm_algo.core_state = ARM_STATE_ARM;
1259
1260                         retval = target_run_algorithm(target, 0, NULL, 5, reg_params,
1261                                         (warea->address) + buffer_size,
1262                                         (warea->address) + buffer_size + target_code_size - 4,
1263                                         10000,  /* 10s should be enough for max. 16 KiB of data */
1264                                         &arm_algo);
1265
1266                         if (retval != ERROR_OK) {
1267                                 LOG_ERROR("Execution of flash algorithm failed.");
1268                                 target_free_all_working_areas(target);
1269                                 retval = ERROR_FLASH_OPERATION_FAILED;
1270                                 break;
1271                         }
1272
1273                         count -= this_npages * FLASH_PAGE_SIZE;
1274                         buffer += this_npages * FLASH_PAGE_SIZE;
1275                         offset += this_npages * FLASH_PAGE_SIZE;
1276                 }
1277
1278                 /* Free all resources */
1279                 destroy_reg_param(&reg_params[0]);
1280                 destroy_reg_param(&reg_params[1]);
1281                 destroy_reg_param(&reg_params[2]);
1282                 destroy_reg_param(&reg_params[3]);
1283                 destroy_reg_param(&reg_params[4]);
1284                 target_free_all_working_areas(target);
1285         } else {
1286                 /* Write to flash memory page-wise */
1287                 while (count != 0) {
1288                         /* How many bytes do we copy this time? */
1289                         num_bytes = (count >= FLASH_PAGE_SIZE) ?
1290                                 FLASH_PAGE_SIZE - (offset % FLASH_PAGE_SIZE) :
1291                                 count;
1292
1293                         /* Don't do anything with it if the page is in a secured sector. */
1294                         if (!bank->sectors[lpc2900_address2sector(bank, offset)].is_protected) {
1295                                 /* Set latch load mode */
1296                                 target_write_u32(target, FCTR,
1297                                         FCTR_FS_CS | FCTR_FS_WRE | FCTR_FS_WEB);
1298
1299                                 /* Always clear the buffer (a little overhead, but who cares) */
1300                                 memset(page, 0xFF, FLASH_PAGE_SIZE);
1301
1302                                 /* Copy them to the buffer */
1303                                 memcpy(&page[offset % FLASH_PAGE_SIZE],
1304                                         &buffer[offset % FLASH_PAGE_SIZE],
1305                                         num_bytes);
1306
1307                                 /* Write whole page to flash data latches */
1308                                 if (target_write_memory(target,
1309                                                 bank->base + (offset - (offset % FLASH_PAGE_SIZE)),
1310                                                 4, FLASH_PAGE_SIZE / 4, page) != ERROR_OK) {
1311                                         LOG_ERROR("Write failed @ 0x%8.8" PRIx32, offset);
1312                                         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
1313
1314                                         return ERROR_FLASH_OPERATION_FAILED;
1315                                 }
1316
1317                                 /* Clear END_OF_BURN interrupt status */
1318                                 target_write_u32(target, INT_CLR_STATUS, INTSRC_END_OF_BURN);
1319
1320                                 /* Set the programming time */
1321                                 target_write_u32(target, FPTR, FPTR_EN_T | prog_time);
1322
1323                                 /* Trigger flash write */
1324                                 target_write_u32(target, FCTR,
1325                                         FCTR_FS_CS | FCTR_FS_WRE | FCTR_FS_WPB | FCTR_FS_PROGREQ);
1326
1327                                 /* Wait for the end of the write operation. If it's not over
1328                                  * after one second, something went dreadfully wrong... :-(
1329                                  */
1330                                 if (lpc2900_wait_status(bank, INTSRC_END_OF_BURN, 1000) != ERROR_OK) {
1331                                         LOG_ERROR("Write failed @ 0x%8.8" PRIx32, offset);
1332                                         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
1333
1334                                         return ERROR_FLASH_OPERATION_FAILED;
1335                                 }
1336                         }
1337
1338                         /* Update pointers and counters */
1339                         offset += num_bytes;
1340                         buffer += num_bytes;
1341                         count -= num_bytes;
1342                 }
1343
1344                 retval = ERROR_OK;
1345         }
1346
1347         /* Normal flash operating mode */
1348         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
1349
1350         return retval;
1351 }
1352
1353 /**
1354  * Try and identify the device.
1355  *
1356  * Determine type number and its memory layout.
1357  *
1358  * @param bank Pointer to the flash bank descriptor
1359  */
1360 static int lpc2900_probe(struct flash_bank *bank)
1361 {
1362         struct lpc2900_flash_bank *lpc2900_info = bank->driver_priv;
1363         struct target *target = bank->target;
1364         uint32_t offset;
1365
1366
1367         if (target->state != TARGET_HALTED) {
1368                 LOG_ERROR("Target not halted");
1369                 return ERROR_TARGET_NOT_HALTED;
1370         }
1371
1372         /* We want to do this only once. */
1373         if (lpc2900_info->is_probed)
1374                 return ERROR_OK;
1375
1376         /* Probing starts with reading the CHIPID register. We will continue only
1377          * if this identifies as an LPC2900 device.
1378          */
1379         target_read_u32(target, CHIPID, &lpc2900_info->chipid);
1380
1381         if (lpc2900_info->chipid != EXPECTED_CHIPID) {
1382                 LOG_WARNING("Device is not an LPC29xx");
1383                 return ERROR_FLASH_OPERATION_FAILED;
1384         }
1385
1386         /* It's an LPC29xx device. Now read the feature register FEAT0...FEAT3. */
1387         uint32_t feat0, feat1, feat2, feat3;
1388         target_read_u32(target, FEAT0, &feat0);
1389         target_read_u32(target, FEAT1, &feat1);
1390         target_read_u32(target, FEAT2, &feat2);
1391         target_read_u32(target, FEAT3, &feat3);
1392
1393         /* Base address */
1394         bank->base = 0x20000000;
1395
1396         /* Determine flash layout from FEAT2 register */
1397         uint32_t num_64k_sectors = (feat2 >> 16) & 0xFF;
1398         uint32_t num_8k_sectors = (feat2 >> 0) & 0xFF;
1399         bank->num_sectors = num_64k_sectors + num_8k_sectors;
1400         bank->size = KiB * (64 * num_64k_sectors + 8 * num_8k_sectors);
1401
1402         /* Determine maximum contiguous RAM block */
1403         lpc2900_info->max_ram_block = 16 * KiB;
1404         if ((feat1 & 0x30) == 0x30) {
1405                 lpc2900_info->max_ram_block = 32 * KiB;
1406                 if ((feat1 & 0x0C) == 0x0C)
1407                         lpc2900_info->max_ram_block = 48 * KiB;
1408         }
1409
1410         /* Determine package code and ITCM size */
1411         uint32_t package_code = feat0 & 0x0F;
1412         uint32_t itcm_code = (feat1 >> 16) & 0x1F;
1413
1414         /* Determine the exact type number. */
1415         uint32_t found = 1;
1416         if ((package_code == 4) && (itcm_code == 5)) {
1417                 /* Old LPC2917 or LPC2919 (non-/01 devices) */
1418                 lpc2900_info->target_name = (bank->size == 768*KiB) ? "LPC2919" : "LPC2917";
1419         } else {
1420                 if (package_code == 2) {
1421                         /* 100-pin package */
1422                         if (bank->size == 128*KiB)
1423                                 lpc2900_info->target_name = "LPC2921";
1424                         else if (bank->size == 256*KiB)
1425                                 lpc2900_info->target_name = "LPC2923";
1426                         else if (bank->size == 512*KiB)
1427                                 lpc2900_info->target_name = "LPC2925";
1428                         else
1429                                 found = 0;
1430                 } else if (package_code == 4) {
1431                         /* 144-pin package */
1432                         if ((bank->size == 256*KiB) && (feat3 == 0xFFFFFFE9))
1433                                 lpc2900_info->target_name = "LPC2926";
1434                         else if ((bank->size == 512*KiB) && (feat3 == 0xFFFFFCF0))
1435                                 lpc2900_info->target_name = "LPC2917/01";
1436                         else if ((bank->size == 512*KiB) && (feat3 == 0xFFFFFFF1))
1437                                 lpc2900_info->target_name = "LPC2927";
1438                         else if ((bank->size == 768*KiB) && (feat3 == 0xFFFFFCF8))
1439                                 lpc2900_info->target_name = "LPC2919/01";
1440                         else if ((bank->size == 768*KiB) && (feat3 == 0xFFFFFFF9))
1441                                 lpc2900_info->target_name = "LPC2929";
1442                         else
1443                                 found = 0;
1444                 } else if (package_code == 5) {
1445                         /* 208-pin package */
1446                         lpc2900_info->target_name = (bank->size == 0) ? "LPC2930" : "LPC2939";
1447                 } else
1448                         found = 0;
1449         }
1450
1451         if (!found) {
1452                 LOG_WARNING("Unknown LPC29xx derivative (FEATx="
1453                         "%08" PRIx32 ":%08" PRIx32 ":%08" PRIx32 ":%08" PRIx32 ")",
1454                         feat0, feat1, feat2, feat3);
1455                 return ERROR_FLASH_OPERATION_FAILED;
1456         }
1457
1458         /* Show detected device */
1459         LOG_INFO("Flash bank %u: Device %s, %" PRIu32
1460                 " KiB in %u sectors",
1461                 bank->bank_number,
1462                 lpc2900_info->target_name, bank->size / KiB,
1463                 bank->num_sectors);
1464
1465         /* Flashless devices cannot be handled */
1466         if (bank->num_sectors == 0) {
1467                 LOG_WARNING("Flashless device cannot be handled");
1468                 return ERROR_FLASH_OPERATION_FAILED;
1469         }
1470
1471         /* Sector layout.
1472          * These are logical sector numbers. When doing real flash operations,
1473          * the logical flash number are translated into the physical flash numbers
1474          * of the device.
1475          */
1476         bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
1477
1478         offset = 0;
1479         for (unsigned int i = 0; i < bank->num_sectors; i++) {
1480                 bank->sectors[i].offset = offset;
1481                 bank->sectors[i].is_erased = -1;
1482                 bank->sectors[i].is_protected = -1;
1483
1484                 if (i <= 7)
1485                         bank->sectors[i].size = 8 * KiB;
1486                 else if (i <= 18)
1487                         bank->sectors[i].size = 64 * KiB;
1488                 else {
1489                         /* We shouldn't come here. But there might be a new part out there
1490                          * that has more than 19 sectors. Politely ask for a fix then.
1491                          */
1492                         bank->sectors[i].size = 0;
1493                         LOG_ERROR("Never heard about sector %u", i);
1494                 }
1495
1496                 offset += bank->sectors[i].size;
1497         }
1498
1499         lpc2900_info->is_probed = true;
1500
1501         /* Read sector security status */
1502         if (lpc2900_read_security_status(bank) != ERROR_OK) {
1503                 LOG_ERROR("Cannot determine sector security status");
1504                 return ERROR_FLASH_OPERATION_FAILED;
1505         }
1506
1507         return ERROR_OK;
1508 }
1509
1510 /**
1511  * Run a blank check for each sector.
1512  *
1513  * For speed reasons, the device isn't read word by word.
1514  * A hash value is calculated by the hardware ("BIST") for each sector.
1515  * This value is then compared against the known hash of an empty sector.
1516  *
1517  * @param bank Pointer to the flash bank descriptor
1518  */
1519 static int lpc2900_erase_check(struct flash_bank *bank)
1520 {
1521         uint32_t status = lpc2900_is_ready(bank);
1522         if (status != ERROR_OK) {
1523                 LOG_INFO("Processor not halted/not probed");
1524                 return status;
1525         }
1526
1527         /* Use the BIST (Built-In Self Test) to generate a signature of each flash
1528          * sector. Compare against the expected signature of an empty sector.
1529          */
1530         for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
1531                 uint32_t signature[4];
1532                 status = lpc2900_run_bist128(bank, bank->sectors[sector].offset,
1533                                 bank->sectors[sector].offset + (bank->sectors[sector].size - 1), signature);
1534                 if (status != ERROR_OK)
1535                         return status;
1536
1537                 /* The expected signatures for an empty sector are different
1538                  * for 8 KiB and 64 KiB sectors.
1539                  */
1540                 if (bank->sectors[sector].size == 8*KiB) {
1541                         bank->sectors[sector].is_erased =
1542                                 (signature[3] == 0x01ABAAAA) &&
1543                                 (signature[2] == 0xAAAAAAAA) &&
1544                                 (signature[1] == 0xAAAAAAAA) &&
1545                                 (signature[0] == 0xAAA00AAA);
1546                 }
1547                 if (bank->sectors[sector].size == 64*KiB) {
1548                         bank->sectors[sector].is_erased =
1549                                 (signature[3] == 0x11801222) &&
1550                                 (signature[2] == 0xB88844FF) &&
1551                                 (signature[1] == 0x11A22008) &&
1552                                 (signature[0] == 0x2B1BFE44);
1553                 }
1554         }
1555
1556         return ERROR_OK;
1557 }
1558
1559 /**
1560  * Get protection (sector security) status.
1561  *
1562  * Determine the status of "sector security" for each sector.
1563  * A secured sector is one that can never be erased/programmed again.
1564  *
1565  * @param bank Pointer to the flash bank descriptor
1566  */
1567 static int lpc2900_protect_check(struct flash_bank *bank)
1568 {
1569         return lpc2900_read_security_status(bank);
1570 }
1571
1572 const struct flash_driver lpc2900_flash = {
1573         .name = "lpc2900",
1574         .commands = lpc2900_command_handlers,
1575         .flash_bank_command = lpc2900_flash_bank_command,
1576         .erase = lpc2900_erase,
1577         .write = lpc2900_write,
1578         .read = default_flash_read,
1579         .probe = lpc2900_probe,
1580         .auto_probe = lpc2900_probe,
1581         .erase_check = lpc2900_erase_check,
1582         .protect_check = lpc2900_protect_check,
1583         .free_driver_priv = default_flash_free_driver_priv,
1584 };