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