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