add const keyword to some APIs
[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  * @param cmd_ctx
535  * @param cmd
536  * @param args
537  * @param argc
538  */
539 static int lpc2900_handle_signature_command( struct command_context_s *cmd_ctx,
540                                              char *cmd, char **args, int argc )
541 {
542         uint32_t status;
543         uint32_t signature[4];
544
545
546         if( argc < 1 )
547         {
548                 LOG_WARNING( "Too few arguments. Call: lpc2900 signature <bank#>" );
549                 return ERROR_FLASH_BANK_INVALID;
550         }
551
552         flash_bank_t *bank;
553         int retval = flash_command_get_bank_by_num(cmd_ctx, args[0], &bank);
554         if (ERROR_OK != retval)
555                 return retval;
556
557         if( bank->target->state != TARGET_HALTED )
558         {
559                 LOG_ERROR( "Target not halted" );
560                 return ERROR_TARGET_NOT_HALTED;
561         }
562
563         /* Run BIST over whole flash range */
564         if( (status = lpc2900_run_bist128( bank,
565                                            bank->base,
566                                            bank->base + (bank->size - 1),
567                                            &signature)
568                                          ) != ERROR_OK )
569         {
570                 return status;
571         }
572
573         command_print( cmd_ctx, "signature: 0x%8.8" PRIx32
574                                           ":0x%8.8" PRIx32
575                                           ":0x%8.8" PRIx32
576                                           ":0x%8.8" PRIx32,
577                       signature[3], signature[2], signature[1], signature[0] );
578
579         return ERROR_OK;
580 }
581
582
583
584 /**
585  * Store customer info in file.
586  *
587  * Read customer info from index sector, and store that block of data into
588  * a disk file. The format is binary.
589  *
590  * @param cmd_ctx
591  * @param cmd
592  * @param args
593  * @param argc
594  */
595 static int lpc2900_handle_read_custom_command( struct command_context_s *cmd_ctx,
596                                                char *cmd, char **args, int argc )
597 {
598         if( argc < 2 )
599         {
600                 return ERROR_COMMAND_SYNTAX_ERROR;
601         }
602
603         flash_bank_t *bank;
604         int retval = flash_command_get_bank_by_num(cmd_ctx, args[0], &bank);
605         if (ERROR_OK != retval)
606                 return retval;
607
608         lpc2900_flash_bank_t *lpc2900_info = bank->driver_priv;
609         lpc2900_info->risky = 0;
610
611         /* Get target, and check if it's halted */
612         target_t *target = bank->target;
613         if( target->state != TARGET_HALTED )
614         {
615                 LOG_ERROR( "Target not halted" );
616                 return ERROR_TARGET_NOT_HALTED;
617         }
618
619         /* Storage for customer info. Read in two parts */
620         uint32_t customer[ ISS_CUSTOMER_NWORDS1 + ISS_CUSTOMER_NWORDS2 ];
621
622         /* Enable access to index sector */
623         target_write_u32( target, FCTR, FCTR_FS_CS | FCTR_FS_WEB | FCTR_FS_ISS );
624
625         /* Read two parts */
626         target_read_memory( target, bank->base+ISS_CUSTOMER_START1, 4,
627                                     ISS_CUSTOMER_NWORDS1,
628                                     (uint8_t *)&customer[0] );
629         target_read_memory( target, bank->base+ISS_CUSTOMER_START2, 4,
630                                     ISS_CUSTOMER_NWORDS2,
631                                     (uint8_t *)&customer[ISS_CUSTOMER_NWORDS1] );
632
633         /* Deactivate access to index sector */
634         target_write_u32( target, FCTR, FCTR_FS_CS | FCTR_FS_WEB );
635
636         /* Try and open the file */
637         fileio_t fileio;
638         const char *filename = args[1];
639         int ret = fileio_open( &fileio, filename, FILEIO_WRITE, FILEIO_BINARY );
640         if( ret != ERROR_OK )
641         {
642                 LOG_WARNING( "Could not open file %s", filename );
643                 return ret;
644         }
645
646         uint32_t nwritten;
647         ret = fileio_write( &fileio, sizeof(customer),
648                         (const uint8_t *)customer, &nwritten );
649         if( ret != ERROR_OK )
650         {
651                 LOG_ERROR( "Write operation to file %s failed", filename );
652                 fileio_close( &fileio );
653                 return ret;
654         }
655
656         fileio_close( &fileio );
657
658         return ERROR_OK;
659 }
660
661
662
663
664 /**
665  * Enter password to enable potentially dangerous options.
666  *
667  * @param cmd_ctx
668  * @param cmd
669  * @param args
670  * @param argc
671  */
672 static int lpc2900_handle_password_command(struct command_context_s *cmd_ctx,
673                                            char *cmd, char **args, int argc)
674 {
675         if (argc < 2)
676         {
677                 return ERROR_COMMAND_SYNTAX_ERROR;
678         }
679
680         flash_bank_t *bank;
681         int retval = flash_command_get_bank_by_num(cmd_ctx, args[0], &bank);
682         if (ERROR_OK != retval)
683                 return retval;
684
685         lpc2900_flash_bank_t *lpc2900_info = bank->driver_priv;
686
687 #define ISS_PASSWORD "I_know_what_I_am_doing"
688
689         lpc2900_info->risky = !strcmp( args[1], ISS_PASSWORD );
690
691         if( !lpc2900_info->risky )
692         {
693                 command_print(cmd_ctx, "Wrong password (use '%s')", ISS_PASSWORD);
694                 return ERROR_COMMAND_ARGUMENT_INVALID;
695         }
696
697         command_print(cmd_ctx,
698                   "Potentially dangerous operation allowed in next command!");
699
700         return ERROR_OK;
701 }
702
703
704
705 /**
706  * Write customer info from file to the index sector.
707  *
708  * @param cmd_ctx
709  * @param cmd
710  * @param args
711  * @param argc
712  */
713 static int lpc2900_handle_write_custom_command( struct command_context_s *cmd_ctx,
714                                                 char *cmd, char **args, int argc )
715 {
716         if (argc < 2)
717         {
718                 return ERROR_COMMAND_SYNTAX_ERROR;
719         }
720
721         flash_bank_t *bank;
722         int retval = flash_command_get_bank_by_num(cmd_ctx, args[0], &bank);
723         if (ERROR_OK != retval)
724                 return retval;
725
726         lpc2900_flash_bank_t *lpc2900_info = bank->driver_priv;
727
728         /* Check if command execution is allowed. */
729         if( !lpc2900_info->risky )
730         {
731                 command_print( cmd_ctx, "Command execution not allowed!" );
732                 return ERROR_COMMAND_ARGUMENT_INVALID;
733         }
734         lpc2900_info->risky = 0;
735
736         /* Get target, and check if it's halted */
737         target_t *target = bank->target;
738         if (target->state != TARGET_HALTED)
739         {
740                 LOG_ERROR("Target not halted");
741                 return ERROR_TARGET_NOT_HALTED;
742         }
743
744         /* The image will always start at offset 0 */
745         image_t image;
746         image.base_address_set = 1;
747         image.base_address = 0;
748         image.start_address_set = 0;
749
750         const char *filename = args[1];
751         const char *type = (argc >= 3) ? args[2] : NULL;
752         retval = image_open(&image, filename, type);
753         if (retval != ERROR_OK)
754         {
755                 return retval;
756         }
757
758         /* Do a sanity check: The image must be exactly the size of the customer
759            programmable area. Any other size is rejected. */
760         if( image.num_sections != 1 )
761         {
762                 LOG_ERROR("Only one section allowed in image file.");
763                 return ERROR_COMMAND_SYNTAX_ERROR;
764         }
765         if( (image.sections[0].base_address != 0) ||
766         (image.sections[0].size != ISS_CUSTOMER_SIZE) )
767         {
768                 LOG_ERROR("Incorrect image file size. Expected %d, "
769                         "got %" PRIu32,
770                    ISS_CUSTOMER_SIZE, image.sections[0].size);
771                 return ERROR_COMMAND_SYNTAX_ERROR;
772         }
773
774         /* Well boys, I reckon this is it... */
775
776         /* Customer info is split into two blocks in pages 4 and 5. */
777         uint8_t page[FLASH_PAGE_SIZE];
778
779         /* Page 4 */
780         uint32_t offset = ISS_CUSTOMER_START1 % FLASH_PAGE_SIZE;
781         memset( page, 0xff, FLASH_PAGE_SIZE );
782         uint32_t size_read;
783         retval = image_read_section( &image, 0, 0,
784                                      ISS_CUSTOMER_SIZE1, &page[offset], &size_read);
785         if( retval != ERROR_OK )
786         {
787                 LOG_ERROR("couldn't read from file '%s'", filename);
788                 image_close(&image);
789                 return retval;
790         }
791         if( (retval = lpc2900_write_index_page( bank, 4, &page )) != ERROR_OK )
792         {
793                 image_close(&image);
794                 return retval;
795         }
796
797         /* Page 5 */
798         offset = ISS_CUSTOMER_START2 % FLASH_PAGE_SIZE;
799         memset( page, 0xff, FLASH_PAGE_SIZE );
800         retval = image_read_section( &image, 0, ISS_CUSTOMER_SIZE1,
801                                      ISS_CUSTOMER_SIZE2, &page[offset], &size_read);
802         if( retval != ERROR_OK )
803         {
804                 LOG_ERROR("couldn't read from file '%s'", filename);
805                 image_close(&image);
806                 return retval;
807         }
808         if( (retval = lpc2900_write_index_page( bank, 5, &page )) != ERROR_OK )
809         {
810                 image_close(&image);
811                 return retval;
812         }
813
814         image_close(&image);
815
816         return ERROR_OK;
817 }
818
819
820
821 /**
822  * Activate 'sector security' for a range of sectors.
823  *
824  * @param cmd_ctx
825  * @param cmd
826  * @param args
827  * @param argc
828  */
829 static int lpc2900_handle_secure_sector_command(struct command_context_s *cmd_ctx,
830                                                 char *cmd, char **args, int argc)
831 {
832         if (argc < 3)
833         {
834                 return ERROR_COMMAND_SYNTAX_ERROR;
835         }
836
837         /* Get the bank descriptor */
838         flash_bank_t *bank;
839         int retval = flash_command_get_bank_by_num(cmd_ctx, args[0], &bank);
840         if (ERROR_OK != retval)
841                 return retval;
842
843         lpc2900_flash_bank_t *lpc2900_info = bank->driver_priv;
844
845         /* Check if command execution is allowed. */
846         if( !lpc2900_info->risky )
847         {
848                 command_print( cmd_ctx, "Command execution not allowed! "
849                 "(use 'password' command first)");
850                 return ERROR_COMMAND_ARGUMENT_INVALID;
851         }
852         lpc2900_info->risky = 0;
853
854         /* Read sector range, and do a sanity check. */
855         int first, last;
856         COMMAND_PARSE_NUMBER(int, args[1], first);
857         COMMAND_PARSE_NUMBER(int, args[2], last);
858         if( (first >= bank->num_sectors) ||
859             (last >= bank->num_sectors) ||
860             (first > last) )
861         {
862                 command_print( cmd_ctx, "Illegal sector range" );
863                 return ERROR_COMMAND_ARGUMENT_INVALID;
864         }
865
866         uint8_t page[FLASH_PAGE_SIZE];
867         int sector;
868
869         /* Sectors in page 6 */
870         if( (first <= 4) || (last >= 8) )
871         {
872                 memset( &page, 0xff, FLASH_PAGE_SIZE );
873                 for( sector = first; sector <= last; sector++ )
874                 {
875                         if( sector <= 4 )
876                         {
877                                 memset( &page[0xB0 + 16*sector], 0, 16 );
878                         }
879                         else if( sector >= 8 )
880                         {
881                                 memset( &page[0x00 + 16*(sector - 8)], 0, 16 );
882                         }
883                 }
884
885                 if( (retval = lpc2900_write_index_page( bank, 6, &page )) != ERROR_OK )
886                 {
887                         LOG_ERROR("failed to update index sector page 6");
888                         return retval;
889                 }
890         }
891
892         /* Sectors in page 7 */
893         if( (first <= 7) && (last >= 5) )
894         {
895                 memset( &page, 0xff, FLASH_PAGE_SIZE );
896                 for( sector = first; sector <= last; sector++ )
897                 {
898                         if( (sector >= 5) && (sector <= 7) )
899                         {
900                                 memset( &page[0x00 + 16*(sector - 5)], 0, 16 );
901                         }
902                 }
903
904                 if( (retval = lpc2900_write_index_page( bank, 7, &page )) != ERROR_OK )
905                 {
906                         LOG_ERROR("failed to update index sector page 7");
907                         return retval;
908                 }
909         }
910
911         command_print( cmd_ctx,
912                 "Sectors security will become effective after next power cycle");
913
914         /* Update the sector security status */
915         if ( lpc2900_read_security_status(bank) != ERROR_OK )
916         {
917                 LOG_ERROR( "Cannot determine sector security status" );
918                 return ERROR_FLASH_OPERATION_FAILED;
919         }
920
921         return ERROR_OK;
922 }
923
924
925
926 /**
927  * Activate JTAG protection.
928  *
929  * @param cmd_ctx
930  * @param cmd
931  * @param args
932  * @param argc
933  */
934 static int lpc2900_handle_secure_jtag_command(struct command_context_s *cmd_ctx,
935                                               char *cmd, char **args, int argc)
936 {
937         if (argc < 1)
938         {
939                 return ERROR_COMMAND_SYNTAX_ERROR;
940         }
941
942         /* Get the bank descriptor */
943         flash_bank_t *bank;
944         int retval = flash_command_get_bank_by_num(cmd_ctx, args[0], &bank);
945         if (ERROR_OK != retval)
946                 return retval;
947
948         lpc2900_flash_bank_t *lpc2900_info = bank->driver_priv;
949
950         /* Check if command execution is allowed. */
951         if( !lpc2900_info->risky )
952         {
953                 command_print( cmd_ctx, "Command execution not allowed! "
954                                         "(use 'password' command first)");
955                 return ERROR_COMMAND_ARGUMENT_INVALID;
956         }
957         lpc2900_info->risky = 0;
958
959         /* Prepare page */
960         uint8_t page[FLASH_PAGE_SIZE];
961         memset( &page, 0xff, FLASH_PAGE_SIZE );
962
963
964         /* Insert "soft" protection word */
965         page[0x30 + 15] = 0x7F;
966         page[0x30 + 11] = 0x7F;
967         page[0x30 +  7] = 0x7F;
968         page[0x30 +  3] = 0x7F;
969
970         /* Write to page 5 */
971         if( (retval = lpc2900_write_index_page( bank, 5, &page ))
972                         != ERROR_OK )
973         {
974                 LOG_ERROR("failed to update index sector page 5");
975                 return retval;
976         }
977
978         LOG_INFO("JTAG security set. Good bye!");
979
980         return ERROR_OK;
981 }
982
983
984
985 /***********************  Flash interface functions  **************************/
986
987
988 /**
989  * Register private command handlers.
990  *
991  * @param cmd_ctx
992  */
993 static int lpc2900_register_commands(struct command_context_s *cmd_ctx)
994 {
995         command_t *lpc2900_cmd = register_command(cmd_ctx, NULL, "lpc2900",
996                                                   NULL, COMMAND_ANY, NULL);
997
998         register_command(
999             cmd_ctx,
1000             lpc2900_cmd,
1001             "signature",
1002             lpc2900_handle_signature_command,
1003             COMMAND_EXEC,
1004             "<bank> | "
1005             "print device signature of flash bank");
1006
1007         register_command(
1008             cmd_ctx,
1009             lpc2900_cmd,
1010             "read_custom",
1011             lpc2900_handle_read_custom_command,
1012             COMMAND_EXEC,
1013             "<bank> <filename> | "
1014             "read customer information from index sector to file");
1015
1016         register_command(
1017             cmd_ctx,
1018             lpc2900_cmd,
1019             "password",
1020             lpc2900_handle_password_command,
1021             COMMAND_EXEC,
1022             "<bank> <password> | "
1023             "enter password to enable 'dangerous' options");
1024
1025         register_command(
1026             cmd_ctx,
1027             lpc2900_cmd,
1028             "write_custom",
1029             lpc2900_handle_write_custom_command,
1030             COMMAND_EXEC,
1031             "<bank> <filename> [<type>] | "
1032             "write customer info from file to index sector");
1033
1034         register_command(
1035             cmd_ctx,
1036             lpc2900_cmd,
1037             "secure_sector",
1038             lpc2900_handle_secure_sector_command,
1039             COMMAND_EXEC,
1040             "<bank> <first> <last> | "
1041             "activate sector security for a range of sectors");
1042
1043         register_command(
1044             cmd_ctx,
1045             lpc2900_cmd,
1046             "secure_jtag",
1047             lpc2900_handle_secure_jtag_command,
1048             COMMAND_EXEC,
1049             "<bank> <level> | "
1050             "activate JTAG security");
1051
1052         return ERROR_OK;
1053 }
1054
1055
1056 /**
1057  * Evaluate flash bank command.
1058  *
1059  * Syntax: flash bank lpc2900 0 0 0 0 target# system_base_clock
1060  *
1061  * @param cmd_ctx
1062  * @param cmd
1063  * @param args
1064  * @param argc
1065  * @param bank Pointer to the flash bank descriptor
1066  */
1067 static int lpc2900_flash_bank_command(struct command_context_s *cmd_ctx,
1068                                       char *cmd, char **args, int argc,
1069                                       struct flash_bank_s *bank)
1070 {
1071         lpc2900_flash_bank_t *lpc2900_info;
1072
1073         if (argc < 6)
1074         {
1075                 LOG_WARNING("incomplete flash_bank LPC2900 configuration");
1076                 return ERROR_FLASH_BANK_INVALID;
1077         }
1078
1079         lpc2900_info = malloc(sizeof(lpc2900_flash_bank_t));
1080         bank->driver_priv = lpc2900_info;
1081
1082         /* Get flash clock.
1083          * Reject it if we can't meet the requirements for program time
1084          * (if clock too slow), or for erase time (clock too fast).
1085          */
1086         uint32_t clk_sys_fmc;
1087         COMMAND_PARSE_NUMBER(u32, args[6], clk_sys_fmc);
1088         lpc2900_info->clk_sys_fmc = clk_sys_fmc * 1000;
1089
1090         uint32_t clock_limit;
1091         /* Check program time limit */
1092         clock_limit = 512000000l / FLASH_PROGRAM_TIME;
1093         if (lpc2900_info->clk_sys_fmc < clock_limit)
1094         {
1095                 LOG_WARNING("flash clock must be at least %" PRIu32 " kHz",
1096                     (clock_limit / 1000));
1097                 return ERROR_FLASH_BANK_INVALID;
1098         }
1099
1100         /* Check erase time limit */
1101         clock_limit = (uint32_t)((32767.0 * 512.0 * 1e6) / FLASH_ERASE_TIME);
1102         if (lpc2900_info->clk_sys_fmc > clock_limit)
1103         {
1104                 LOG_WARNING("flash clock must be a maximum of %" PRIu32" kHz",
1105                     (clock_limit / 1000));
1106                 return ERROR_FLASH_BANK_INVALID;
1107         }
1108
1109         /* Chip ID will be obtained by probing the device later */
1110         lpc2900_info->chipid = 0;
1111
1112         return ERROR_OK;
1113 }
1114
1115
1116 /**
1117  * Erase sector(s).
1118  *
1119  * @param bank Pointer to the flash bank descriptor
1120  * @param first First sector to be erased
1121  * @param last Last sector (including) to be erased
1122  */
1123 static int lpc2900_erase(struct flash_bank_s *bank, int first, int last)
1124 {
1125         uint32_t status;
1126         int sector;
1127         int last_unsecured_sector;
1128         target_t *target = bank->target;
1129         lpc2900_flash_bank_t *lpc2900_info = bank->driver_priv;
1130
1131
1132         status = lpc2900_is_ready(bank);
1133         if (status != ERROR_OK)
1134         {
1135                 return status;
1136         }
1137
1138         /* Sanity check on sector range */
1139         if ((first < 0) || (last < first) || (last >= bank->num_sectors))
1140         {
1141                 LOG_INFO("Bad sector range");
1142                 return ERROR_FLASH_SECTOR_INVALID;
1143         }
1144
1145         /* Update the info about secured sectors */
1146         lpc2900_read_security_status( bank );
1147
1148         /* The selected sector range might include secured sectors. An attempt
1149          * to erase such a sector will cause the erase to fail also for unsecured
1150          * sectors. It is necessary to determine the last unsecured sector now,
1151          * because we have to treat the last relevant sector in the list in
1152          * a special way.
1153          */
1154         last_unsecured_sector = -1;
1155         for (sector = first; sector <= last; sector++)
1156         {
1157                 if ( !bank->sectors[sector].is_protected )
1158                 {
1159                         last_unsecured_sector = sector;
1160                 }
1161         }
1162
1163         /* Exit now, in case of the rare constellation where all sectors in range
1164          * are secured. This is regarded a success, since erasing/programming of
1165          * secured sectors shall be handled transparently.
1166          */
1167         if ( last_unsecured_sector == -1 )
1168         {
1169                 return ERROR_OK;
1170         }
1171
1172         /* Enable flash block and set the correct CRA clock of 66 kHz */
1173         lpc2900_setup(bank);
1174
1175         /* Clear END_OF_ERASE interrupt status */
1176         target_write_u32(target, INT_CLR_STATUS, INTSRC_END_OF_ERASE);
1177
1178         /* Set the program/erase timer to FLASH_ERASE_TIME */
1179         target_write_u32(target, FPTR,
1180                          FPTR_EN_T | lpc2900_calc_tr( lpc2900_info->clk_sys_fmc,
1181                                                       FLASH_ERASE_TIME ));
1182
1183         /* Sectors are marked for erasure, then erased all together */
1184         for (sector = first; sector <= last_unsecured_sector; sector++)
1185         {
1186                 /* Only mark sectors that aren't secured. Any attempt to erase a group
1187                  * of sectors will fail if any single one of them is secured!
1188                  */
1189                 if ( !bank->sectors[sector].is_protected )
1190                 {
1191                         /* Unprotect the sector */
1192                         target_write_u32(target, bank->sectors[sector].offset, 0);
1193                         target_write_u32(target, FCTR,
1194                                          FCTR_FS_LOADREQ | FCTR_FS_WPB |
1195                                          FCTR_FS_WEB | FCTR_FS_WRE | FCTR_FS_CS);
1196
1197                         /* Mark the sector for erasure. The last sector in the list
1198                            triggers the erasure. */
1199                         target_write_u32(target, bank->sectors[sector].offset, 0);
1200                         if ( sector == last_unsecured_sector )
1201                         {
1202                                 target_write_u32(target, FCTR,
1203                                                  FCTR_FS_PROGREQ | FCTR_FS_WPB | FCTR_FS_CS);
1204                         }
1205                         else
1206                         {
1207                                 target_write_u32(target, FCTR,
1208                                                  FCTR_FS_LOADREQ | FCTR_FS_WPB |
1209                                                  FCTR_FS_WEB | FCTR_FS_CS);
1210                         }
1211                 }
1212         }
1213
1214         /* Wait for the end of the erase operation. If it's not over after two seconds,
1215          * something went dreadfully wrong... :-(
1216          */
1217         if( lpc2900_wait_status(bank, INTSRC_END_OF_ERASE, 2000) != ERROR_OK )
1218         {
1219                 return ERROR_FLASH_OPERATION_FAILED;
1220         }
1221
1222         /* Normal flash operating mode */
1223         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
1224
1225         return ERROR_OK;
1226 }
1227
1228
1229
1230 static int lpc2900_protect(struct flash_bank_s *bank, int set, int first, int last)
1231 {
1232         /* This command is not supported.
1233      * "Protection" in LPC2900 terms is handled transparently. Sectors will
1234      * automatically be unprotected as needed.
1235      * Instead we use the concept of sector security. A secured sector is shown
1236      * as "protected" in OpenOCD. Sector security is a permanent feature, and
1237      * cannot be disabled once activated.
1238      */
1239
1240         return ERROR_OK;
1241 }
1242
1243
1244 /**
1245  * Write data to flash.
1246  *
1247  * @param bank Pointer to the flash bank descriptor
1248  * @param buffer Buffer with data
1249  * @param offset Start address (relative to bank start)
1250  * @param count Number of bytes to be programmed
1251  */
1252 static int lpc2900_write(struct flash_bank_s *bank, uint8_t *buffer,
1253                          uint32_t offset, uint32_t count)
1254 {
1255         uint8_t page[FLASH_PAGE_SIZE];
1256         uint32_t status;
1257         uint32_t num_bytes;
1258         target_t *target = bank->target;
1259         lpc2900_flash_bank_t *lpc2900_info = bank->driver_priv;
1260         int sector;
1261         int retval;
1262
1263         static const uint32_t write_target_code[] = {
1264                 /* Set auto latch mode: FCTR=CS|WRE|WEB */
1265                 0xe3a0a007,   /* loop       mov r10, #0x007 */
1266                 0xe583a000,   /*            str r10,[r3,#0] */
1267
1268                 /* Load complete page into latches */
1269                 0xe3a06020,   /*            mov r6,#(512/16) */
1270                 0xe8b00f00,   /* next       ldmia r0!,{r8-r11} */
1271                 0xe8a10f00,   /*            stmia r1!,{r8-r11} */
1272                 0xe2566001,   /*            subs r6,#1 */
1273                 0x1afffffb,   /*            bne next */
1274
1275                 /* Clear END_OF_BURN interrupt status */
1276                 0xe3a0a002,   /*            mov r10,#(1 << 1) */
1277                 0xe583afe8,   /*            str r10,[r3,#0xfe8] */
1278
1279                 /* Set the erase time to FLASH_PROGRAM_TIME */
1280                 0xe5834008,   /*            str r4,[r3,#8] */
1281
1282                 /* Trigger flash write
1283                         FCTR = CS | WRE | WPB | PROGREQ */
1284                 0xe3a0a083,   /*            mov r10,#0x83 */
1285                 0xe38aaa01,   /*            orr r10,#0x1000 */
1286                 0xe583a000,   /*            str r10,[r3,#0] */
1287
1288                 /* Wait for end of burn */
1289                 0xe593afe0,   /* wait       ldr r10,[r3,#0xfe0] */
1290                 0xe21aa002,   /*            ands r10,#(1 << 1) */
1291                 0x0afffffc,   /*            beq wait */
1292
1293                 /* End? */
1294                 0xe2522001,   /*            subs r2,#1 */
1295                 0x1affffed,   /*            bne loop */
1296
1297                 0xeafffffe    /* done       b done */
1298         };
1299
1300
1301         status = lpc2900_is_ready(bank);
1302         if (status != ERROR_OK)
1303         {
1304                 return status;
1305         }
1306
1307         /* Enable flash block and set the correct CRA clock of 66 kHz */
1308         lpc2900_setup(bank);
1309
1310         /* Update the info about secured sectors */
1311         lpc2900_read_security_status( bank );
1312
1313         /* Unprotect all involved sectors */
1314         for (sector = 0; sector < bank->num_sectors; sector++)
1315         {
1316                 /* Start address in or before this sector? */
1317                 /* End address in or behind this sector? */
1318                 if ( ((bank->base + offset) <
1319                           (bank->sectors[sector].offset + bank->sectors[sector].size)) &&
1320                      ((bank->base + (offset + count - 1)) >= bank->sectors[sector].offset) )
1321                 {
1322                         /* This sector is involved and needs to be unprotected.
1323                                 * Don't do it for secured sectors.
1324                                 */
1325                         if ( !bank->sectors[sector].is_protected )
1326                         {
1327                                 target_write_u32(target, bank->sectors[sector].offset, 0);
1328                                 target_write_u32(target, FCTR,
1329                                                  FCTR_FS_LOADREQ | FCTR_FS_WPB |
1330                                                  FCTR_FS_WEB | FCTR_FS_WRE | FCTR_FS_CS);
1331                         }
1332                 }
1333         }
1334
1335         /* Set the program/erase time to FLASH_PROGRAM_TIME */
1336         uint32_t prog_time = FPTR_EN_T | lpc2900_calc_tr( lpc2900_info->clk_sys_fmc,
1337                                                           FLASH_PROGRAM_TIME );
1338
1339         /* If there is a working area of reasonable size, use it to program via
1340            a target algorithm. If not, fall back to host programming. */
1341
1342         /* We need some room for target code. */
1343         uint32_t target_code_size = sizeof(write_target_code);
1344
1345         /* Try working area allocation. Start with a large buffer, and try with
1346            reduced size if that fails. */
1347         working_area_t *warea;
1348         uint32_t buffer_size = lpc2900_info->max_ram_block - 1 * KiB;
1349         while( (retval = target_alloc_working_area(target,
1350                                                    buffer_size + target_code_size,
1351                                                    &warea)) != ERROR_OK )
1352         {
1353                 /* Try a smaller buffer now, and stop if it's too small. */
1354                 buffer_size -= 1 * KiB;
1355                 if (buffer_size < 2 * KiB)
1356                 {
1357                         LOG_INFO( "no (large enough) working area"
1358                                   ", falling back to host mode" );
1359                         warea = NULL;
1360                         break;
1361                 }
1362         };
1363
1364         if( warea )
1365         {
1366                 reg_param_t reg_params[5];
1367                 armv4_5_algorithm_t armv4_5_info;
1368
1369                 /* We can use target mode. Download the algorithm. */
1370                 retval = target_write_buffer( target,
1371                                               (warea->address)+buffer_size,
1372                                               target_code_size,
1373                                               (uint8_t *)write_target_code);
1374                 if (retval != ERROR_OK)
1375                 {
1376                         LOG_ERROR("Unable to write block write code to target");
1377                         target_free_all_working_areas(target);
1378                         return ERROR_FLASH_OPERATION_FAILED;
1379                 }
1380
1381                 init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
1382                 init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
1383                 init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
1384                 init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
1385                 init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
1386
1387                 /* Write to flash in large blocks */
1388                 while ( count != 0 )
1389                 {
1390                         uint32_t this_npages;
1391                         uint8_t *this_buffer;
1392                         int start_sector = lpc2900_address2sector( bank, offset );
1393
1394                         /* First page / last page / rest */
1395                         if( offset % FLASH_PAGE_SIZE )
1396                         {
1397                                 /* Block doesn't start on page boundary.
1398                                    Burn first partial page separately. */
1399                                 memset( &page, 0xff, sizeof(page) );
1400                                 memcpy( &page[offset % FLASH_PAGE_SIZE],
1401                                         buffer,
1402                                         FLASH_PAGE_SIZE - (offset % FLASH_PAGE_SIZE) );
1403                                 this_npages = 1;
1404                                 this_buffer = &page[0];
1405                                 count = count + (offset % FLASH_PAGE_SIZE);
1406                                 offset = offset - (offset % FLASH_PAGE_SIZE);
1407                         }
1408                         else if( count < FLASH_PAGE_SIZE )
1409                         {
1410                                 /* Download last incomplete page separately. */
1411                                 memset( &page, 0xff, sizeof(page) );
1412                                 memcpy( &page, buffer, count );
1413                                 this_npages = 1;
1414                                 this_buffer = &page[0];
1415                                 count = FLASH_PAGE_SIZE;
1416                         }
1417                         else
1418                         {
1419                                 /* Download as many full pages as possible */
1420                                 this_npages = (count < buffer_size) ?
1421                                                count / FLASH_PAGE_SIZE :
1422                                                buffer_size / FLASH_PAGE_SIZE;
1423                                 this_buffer = buffer;
1424
1425                                 /* Make sure we stop at the next secured sector */
1426                                 int sector = start_sector + 1;
1427                                 while( sector < bank->num_sectors )
1428                                 {
1429                                         /* Secured? */
1430                                         if( bank->sectors[sector].is_protected )
1431                                         {
1432                                                 /* Is that next sector within the current block? */
1433                                                 if( (bank->sectors[sector].offset - bank->base) <
1434                                                         (offset + (this_npages * FLASH_PAGE_SIZE)) )
1435                                                 {
1436                                                         /* Yes! Split the block */
1437                                                         this_npages =
1438                                                           (bank->sectors[sector].offset - bank->base - offset)
1439                                                               / FLASH_PAGE_SIZE;
1440                                                         break;
1441                                                 }
1442                                         }
1443
1444                                         sector++;
1445                                 }
1446                         }
1447
1448                         /* Skip the current sector if it is secured */
1449                         if (bank->sectors[start_sector].is_protected)
1450                         {
1451                                 LOG_DEBUG("Skip secured sector %d",
1452                                                 start_sector);
1453
1454                                 /* Stop if this is the last sector */
1455                                 if (start_sector == bank->num_sectors - 1)
1456                                 {
1457                                         break;
1458                                 }
1459
1460                                 /* Skip */
1461                                 uint32_t nskip = bank->sectors[start_sector].size -
1462                                                  (offset % bank->sectors[start_sector].size);
1463                                 offset += nskip;
1464                                 buffer += nskip;
1465                                 count = (count >= nskip) ? (count - nskip) : 0;
1466                                 continue;
1467                         }
1468
1469                         /* Execute buffer download */
1470                         if ((retval = target_write_buffer(target,
1471                                                           warea->address,
1472                                                           this_npages * FLASH_PAGE_SIZE,
1473                                                           this_buffer)) != ERROR_OK)
1474                         {
1475                                 LOG_ERROR("Unable to write data to target");
1476                                 target_free_all_working_areas(target);
1477                                 return ERROR_FLASH_OPERATION_FAILED;
1478                         }
1479
1480                         /* Prepare registers */
1481                         buf_set_u32(reg_params[0].value, 0, 32, warea->address);
1482                         buf_set_u32(reg_params[1].value, 0, 32, offset);
1483                         buf_set_u32(reg_params[2].value, 0, 32, this_npages);
1484                         buf_set_u32(reg_params[3].value, 0, 32, FCTR);
1485                         buf_set_u32(reg_params[4].value, 0, 32, FPTR_EN_T | prog_time);
1486
1487                         /* Execute algorithm, assume breakpoint for last instruction */
1488                         armv4_5_info.common_magic = ARMV4_5_COMMON_MAGIC;
1489                         armv4_5_info.core_mode = ARMV4_5_MODE_SVC;
1490                         armv4_5_info.core_state = ARMV4_5_STATE_ARM;
1491
1492                         retval = target_run_algorithm(target, 0, NULL, 5, reg_params,
1493                                 (warea->address) + buffer_size,
1494                                 (warea->address) + buffer_size + target_code_size - 4,
1495                                 10000, /* 10s should be enough for max. 16 KiB of data */
1496                                 &armv4_5_info);
1497
1498                         if (retval != ERROR_OK)
1499                         {
1500                                 LOG_ERROR("Execution of flash algorithm failed.");
1501                                 target_free_all_working_areas(target);
1502                                 retval = ERROR_FLASH_OPERATION_FAILED;
1503                                 break;
1504                         }
1505
1506                         count -= this_npages * FLASH_PAGE_SIZE;
1507                         buffer += this_npages * FLASH_PAGE_SIZE;
1508                         offset += this_npages * FLASH_PAGE_SIZE;
1509                 }
1510
1511                 /* Free all resources */
1512                 destroy_reg_param(&reg_params[0]);
1513                 destroy_reg_param(&reg_params[1]);
1514                 destroy_reg_param(&reg_params[2]);
1515                 destroy_reg_param(&reg_params[3]);
1516                 destroy_reg_param(&reg_params[4]);
1517                 target_free_all_working_areas(target);
1518         }
1519         else
1520         {
1521                 /* Write to flash memory page-wise */
1522                 while ( count != 0 )
1523                 {
1524                         /* How many bytes do we copy this time? */
1525                         num_bytes = (count >= FLASH_PAGE_SIZE) ?
1526                                     FLASH_PAGE_SIZE - (offset % FLASH_PAGE_SIZE) :
1527                                     count;
1528
1529                         /* Don't do anything with it if the page is in a secured sector. */
1530                         if ( !bank->sectors[lpc2900_address2sector(bank, offset)].is_protected )
1531                         {
1532                                 /* Set latch load mode */
1533                                 target_write_u32(target, FCTR,
1534                                                  FCTR_FS_CS | FCTR_FS_WRE | FCTR_FS_WEB);
1535
1536                                 /* Always clear the buffer (a little overhead, but who cares) */
1537                                 memset(page, 0xFF, FLASH_PAGE_SIZE);
1538
1539                                 /* Copy them to the buffer */
1540                                 memcpy( &page[offset % FLASH_PAGE_SIZE],
1541                                         &buffer[offset % FLASH_PAGE_SIZE],
1542                                         num_bytes );
1543
1544                                 /* Write whole page to flash data latches */
1545                                 if (target_write_memory(
1546                                                  target,
1547                                                  bank->base + (offset - (offset % FLASH_PAGE_SIZE)),
1548                                                  4, FLASH_PAGE_SIZE / 4, page) != ERROR_OK)
1549                                 {
1550                                         LOG_ERROR("Write failed @ 0x%8.8" PRIx32, offset);
1551                                         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
1552
1553                                         return ERROR_FLASH_OPERATION_FAILED;
1554                                 }
1555
1556                                 /* Clear END_OF_BURN interrupt status */
1557                                 target_write_u32(target, INT_CLR_STATUS, INTSRC_END_OF_BURN);
1558
1559                                 /* Set the programming time */
1560                                 target_write_u32(target, FPTR, FPTR_EN_T | prog_time);
1561
1562                                 /* Trigger flash write */
1563                                 target_write_u32(target, FCTR,
1564                                     FCTR_FS_CS | FCTR_FS_WRE | FCTR_FS_WPB | FCTR_FS_PROGREQ);
1565
1566                                 /* Wait for the end of the write operation. If it's not over
1567                                  * after one second, something went dreadfully wrong... :-(
1568                                  */
1569                                 if (lpc2900_wait_status(bank, INTSRC_END_OF_BURN, 1000) != ERROR_OK)
1570                                 {
1571                                         LOG_ERROR("Write failed @ 0x%8.8" PRIx32, offset);
1572                                         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
1573
1574                                         return ERROR_FLASH_OPERATION_FAILED;
1575                                 }
1576                         }
1577
1578                         /* Update pointers and counters */
1579                         offset += num_bytes;
1580                         buffer += num_bytes;
1581                         count -= num_bytes;
1582                 }
1583
1584                 retval = ERROR_OK;
1585         }
1586
1587         /* Normal flash operating mode */
1588         target_write_u32(target, FCTR, FCTR_FS_CS | FCTR_FS_WEB);
1589
1590         return retval;
1591 }
1592
1593
1594 /**
1595  * Try and identify the device.
1596  *
1597  * Determine type number and its memory layout.
1598  *
1599  * @param bank Pointer to the flash bank descriptor
1600  */
1601 static int lpc2900_probe(struct flash_bank_s *bank)
1602 {
1603         lpc2900_flash_bank_t *lpc2900_info = bank->driver_priv;
1604         target_t *target = bank->target;
1605         int i = 0;
1606         uint32_t offset;
1607
1608
1609         if (target->state != TARGET_HALTED)
1610         {
1611                 LOG_ERROR("Target not halted");
1612                 return ERROR_TARGET_NOT_HALTED;
1613         }
1614
1615         /* We want to do this only once. Check if we already have a valid CHIPID,
1616          * because then we will have already successfully probed the device.
1617          */
1618         if (lpc2900_info->chipid == EXPECTED_CHIPID)
1619         {
1620                 return ERROR_OK;
1621         }
1622
1623         /* Probing starts with reading the CHIPID register. We will continue only
1624          * if this identifies as an LPC2900 device.
1625          */
1626         target_read_u32(target, CHIPID, &lpc2900_info->chipid);
1627
1628         if (lpc2900_info->chipid != EXPECTED_CHIPID)
1629         {
1630                 LOG_WARNING("Device is not an LPC29xx");
1631                 return ERROR_FLASH_OPERATION_FAILED;
1632         }
1633
1634         /* It's an LPC29xx device. Now read the feature register FEAT0...FEAT3. */
1635         uint32_t feat0, feat1, feat2, feat3;
1636         target_read_u32(target, FEAT0, &feat0);
1637         target_read_u32(target, FEAT1, &feat1);
1638         target_read_u32(target, FEAT2, &feat2);
1639         target_read_u32(target, FEAT3, &feat3);
1640
1641         /* Base address */
1642         bank->base = 0x20000000;
1643
1644         /* Determine flash layout from FEAT2 register */
1645         uint32_t num_64k_sectors = (feat2 >> 16) & 0xFF;
1646         uint32_t num_8k_sectors = (feat2 >> 0) & 0xFF;
1647         bank->num_sectors = num_64k_sectors + num_8k_sectors;
1648         bank->size = KiB * (64 * num_64k_sectors + 8 * num_8k_sectors);
1649
1650         /* Determine maximum contiguous RAM block */
1651         lpc2900_info->max_ram_block = 16 * KiB;
1652         if( (feat1 & 0x30) == 0x30 )
1653         {
1654                 lpc2900_info->max_ram_block = 32 * KiB;
1655                 if( (feat1 & 0x0C) == 0x0C )
1656                 {
1657                         lpc2900_info->max_ram_block = 48 * KiB;
1658                 }
1659         }
1660
1661         /* Determine package code and ITCM size */
1662         uint32_t package_code = feat0 & 0x0F;
1663         uint32_t itcm_code = (feat1 >> 16) & 0x1F;
1664
1665         /* Determine the exact type number. */
1666         uint32_t found = 1;
1667         if ( (package_code == 4) && (itcm_code == 5) )
1668         {
1669                 /* Old LPC2917 or LPC2919 (non-/01 devices) */
1670                 lpc2900_info->target_name = (bank->size == 768*KiB) ? "LPC2919" : "LPC2917";
1671         }
1672         else
1673         {
1674                 if ( package_code == 2 )
1675                 {
1676                         /* 100-pin package */
1677                         if ( bank->size == 128*KiB )
1678                         {
1679                                 lpc2900_info->target_name = "LPC2921";
1680                         }
1681                         else if ( bank->size == 256*KiB )
1682                         {
1683                                 lpc2900_info->target_name = "LPC2923";
1684                         }
1685                         else if ( bank->size == 512*KiB )
1686                         {
1687                                 lpc2900_info->target_name = "LPC2925";
1688                         }
1689                         else
1690                         {
1691                                 found = 0;
1692                         }
1693                 }
1694                 else if ( package_code == 4 )
1695                 {
1696                         /* 144-pin package */
1697                         if ( (bank->size == 512*KiB) && (feat3 == 0xFFFFFCF0) )
1698                         {
1699                                 lpc2900_info->target_name = "LPC2917/01";
1700                         }
1701                         else if ( (bank->size == 512*KiB) && (feat3 == 0xFFFFFFF1) )
1702                         {
1703                                 lpc2900_info->target_name = "LPC2927";
1704                         }
1705                         else if ( (bank->size == 768*KiB) && (feat3 == 0xFFFFFCF8) )
1706                         {
1707                                 lpc2900_info->target_name = "LPC2919/01";
1708                         }
1709                         else if ( (bank->size == 768*KiB) && (feat3 == 0xFFFFFFF9) )
1710                         {
1711                                 lpc2900_info->target_name = "LPC2929";
1712                         }
1713                         else
1714                         {
1715                                 found = 0;
1716                         }
1717                 }
1718                 else if ( package_code == 5 )
1719                 {
1720                         /* 208-pin package */
1721                         lpc2900_info->target_name = (bank->size == 0) ? "LPC2930" : "LPC2939";
1722                 }
1723                 else
1724                 {
1725                         found = 0;
1726                 }
1727         }
1728
1729         if ( !found )
1730         {
1731                 LOG_WARNING("Unknown LPC29xx derivative");
1732                 return ERROR_FLASH_OPERATION_FAILED;
1733         }
1734
1735         /* Show detected device */
1736         LOG_INFO("Flash bank %d"
1737                  ": Device %s, %" PRIu32
1738                  " KiB in %d sectors",
1739                  bank->bank_number,
1740                  lpc2900_info->target_name, bank->size / KiB,
1741                  bank->num_sectors);
1742
1743         /* Flashless devices cannot be handled */
1744         if ( bank->num_sectors == 0 )
1745         {
1746                 LOG_WARNING("Flashless device cannot be handled");
1747                 return ERROR_FLASH_OPERATION_FAILED;
1748         }
1749
1750         /* Sector layout.
1751          * These are logical sector numbers. When doing real flash operations,
1752          * the logical flash number are translated into the physical flash numbers
1753          * of the device.
1754          */
1755         bank->sectors = malloc(sizeof(flash_sector_t) * bank->num_sectors);
1756
1757         offset = 0;
1758         for (i = 0; i < bank->num_sectors; i++)
1759         {
1760                 bank->sectors[i].offset = offset;
1761                 bank->sectors[i].is_erased = -1;
1762                 bank->sectors[i].is_protected = -1;
1763
1764                 if ( i <= 7 )
1765                 {
1766                         bank->sectors[i].size = 8 * KiB;
1767                 }
1768                 else if ( i <= 18 )
1769                 {
1770                         bank->sectors[i].size = 64 * KiB;
1771                 }
1772                 else
1773                 {
1774                         /* We shouldn't come here. But there might be a new part out there
1775                          * that has more than 19 sectors. Politely ask for a fix then.
1776                          */
1777                         bank->sectors[i].size = 0;
1778                         LOG_ERROR("Never heard about sector %d", i);
1779                 }
1780
1781                 offset += bank->sectors[i].size;
1782         }
1783
1784         /* Read sector security status */
1785         if ( lpc2900_read_security_status(bank) != ERROR_OK )
1786         {
1787                 LOG_ERROR("Cannot determine sector security status");
1788                 return ERROR_FLASH_OPERATION_FAILED;
1789         }
1790
1791         return ERROR_OK;
1792 }
1793
1794
1795 /**
1796  * Run a blank check for each sector.
1797  *
1798  * For speed reasons, the device isn't read word by word.
1799  * A hash value is calculated by the hardware ("BIST") for each sector.
1800  * This value is then compared against the known hash of an empty sector.
1801  *
1802  * @param bank Pointer to the flash bank descriptor
1803  */
1804 static int lpc2900_erase_check(struct flash_bank_s *bank)
1805 {
1806         uint32_t status = lpc2900_is_ready(bank);
1807         if (status != ERROR_OK)
1808         {
1809                 LOG_INFO("Processor not halted/not probed");
1810                 return status;
1811         }
1812
1813         /* Use the BIST (Built-In Selft Test) to generate a signature of each flash
1814          * sector. Compare against the expected signature of an empty sector.
1815          */
1816         int sector;
1817         for ( sector = 0; sector < bank->num_sectors; sector++ )
1818         {
1819                 uint32_t signature[4];
1820                 if ( (status = lpc2900_run_bist128( bank,
1821                                                     bank->sectors[sector].offset,
1822                                                     bank->sectors[sector].offset +
1823                                                        (bank->sectors[sector].size - 1),
1824                                                     &signature)) != ERROR_OK )
1825                 {
1826                         return status;
1827                 }
1828
1829                 /* The expected signatures for an empty sector are different
1830                  * for 8 KiB and 64 KiB sectors.
1831                  */
1832                 if ( bank->sectors[sector].size == 8*KiB )
1833                 {
1834                         bank->sectors[sector].is_erased =
1835                             (signature[3] == 0x01ABAAAA) &&
1836                             (signature[2] == 0xAAAAAAAA) &&
1837                             (signature[1] == 0xAAAAAAAA) &&
1838                             (signature[0] == 0xAAA00AAA);
1839                 }
1840                 if ( bank->sectors[sector].size == 64*KiB )
1841                 {
1842                         bank->sectors[sector].is_erased =
1843                             (signature[3] == 0x11801222) &&
1844                             (signature[2] == 0xB88844FF) &&
1845                             (signature[1] == 0x11A22008) &&
1846                             (signature[0] == 0x2B1BFE44);
1847                 }
1848         }
1849
1850         return ERROR_OK;
1851 }
1852
1853
1854 /**
1855  * Get protection (sector security) status.
1856  *
1857  * Determine the status of "sector security" for each sector.
1858  * A secured sector is one that can never be erased/programmed again.
1859  *
1860  * @param bank Pointer to the flash bank descriptor
1861  */
1862 static int lpc2900_protect_check(struct flash_bank_s *bank)
1863 {
1864         return lpc2900_read_security_status(bank);
1865 }
1866
1867
1868 /**
1869  * Print info about the driver (not the device).
1870  *
1871  * @param bank Pointer to the flash bank descriptor
1872  * @param buf Buffer to take the string
1873  * @param buf_size Maximum number of characters that the buffer can take
1874  */
1875 static int lpc2900_info(struct flash_bank_s *bank, char *buf, int buf_size)
1876 {
1877         snprintf(buf, buf_size, "lpc2900 flash driver");
1878
1879         return ERROR_OK;
1880 }
1881
1882
1883 flash_driver_t lpc2900_flash =
1884 {
1885         .name               = "lpc2900",
1886         .register_commands  = lpc2900_register_commands,
1887         .flash_bank_command = lpc2900_flash_bank_command,
1888         .erase              = lpc2900_erase,
1889         .protect            = lpc2900_protect,
1890         .write              = lpc2900_write,
1891         .probe              = lpc2900_probe,
1892         .auto_probe         = lpc2900_probe,
1893         .erase_check        = lpc2900_erase_check,
1894         .protect_check      = lpc2900_protect_check,
1895         .info               = lpc2900_info
1896 };