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