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