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