034be732a556641183ceae083e894f1b927d2d5f
[fw/openocd] / src / flash / at91sam7.c
1 /***************************************************************************
2  *   Copyright (C) 2006 by Magnus Lundin                                   *
3  *   lundin@mlu.mine.nu                                                    *
4  *                                                                         *
5  *   Copyright (C) 2008 by Gheorghe Guran (atlas)                          *
6  *                                                                         *
7  *   This program is free software; you can redistribute it and/or modify  *
8  *   it under the terms of the GNU General public License as published by  *
9  *   the Free Software Foundation; either version 2 of the License, or     *
10  *   (at your option) any later version.                                   *
11  *                                                                         *
12  *   This program is distributed in the hope that it will be useful,       *
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
14  *   MERCHANTABILITY or FITNESS for A PARTICULAR PURPOSE.  See the         *
15  *   GNU General public License for more details.                          *
16  *                                                                         *
17  *   You should have received a copy of the GNU General public License     *
18  *   along with this program; if not, write to the                         *
19  *   Free Software Foundation, Inc.,                                       *
20  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
21 ****************************************************************************/
22
23 /***************************************************************************************************************************************************************************************
24 *
25 * New flash setup command:
26 *
27 * flash bank <driver> <base_addr> <size> <chip_width> <bus_width> <target_number> [<target_name> <banks> <sectors_per_bank> <pages_per_sector> <page_size> <num_nvmbits> <ext_freq_khz>]
28 *
29 *   <ext_freq_khz> - MUST be used if clock is from external source,
30 *                    CAN be used if main oscillator frequency is known (recomended)
31 * Examples:
32 *  flash bank at91sam7 0x00100000 0 0 4 0 0 AT91SAM7XC256 1 16 64 256 3 25000                   ==== RECOMENDED ============
33 *  flash bank at91sam7 0 0 0 0 0 0 0 0 0 0 0 0 25000    (auto-detection, except for clock)      ==== RECOMENDED ============
34 *  flash bank at91sam7 0x00100000 0 0 4 0 0 AT91SAM7XC256 1 16 64 256 3 0                       ==== NOT RECOMENDED !!! ====
35 *  flash bank at91sam7 0 0 0 0 0            (old style, full auto-detection)                    ==== NOT RECOMENDED !!! ====
36 ****************************************************************************************************************************************************************************************/
37
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41
42 #include "at91sam7.h"
43 #include "binarybuffer.h"
44
45
46 static int at91sam7_register_commands(struct command_context_s *cmd_ctx);
47 static int at91sam7_flash_bank_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, struct flash_bank_s *bank);
48 static int at91sam7_erase(struct flash_bank_s *bank, int first, int last);
49 static int at91sam7_protect(struct flash_bank_s *bank, int set, int first, int last);
50 static int at91sam7_write(struct flash_bank_s *bank, uint8_t *buffer, uint32_t offset, uint32_t count);
51 static int at91sam7_probe(struct flash_bank_s *bank);
52 //static int at91sam7_auto_probe(struct flash_bank_s *bank);
53 static int at91sam7_erase_check(struct flash_bank_s *bank);
54 static int at91sam7_protect_check(struct flash_bank_s *bank);
55 static int at91sam7_info(struct flash_bank_s *bank, char *buf, int buf_size);
56
57 static uint32_t at91sam7_get_flash_status(target_t *target, int bank_number);
58 static void at91sam7_set_flash_mode(flash_bank_t *bank, int mode);
59 static uint32_t at91sam7_wait_status_busy(flash_bank_t *bank, uint32_t waitbits, int timeout);
60 static int at91sam7_flash_command(struct flash_bank_s *bank, uint8_t cmd, uint16_t pagen); 
61 static int at91sam7_handle_gpnvm_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
62
63 flash_driver_t at91sam7_flash =
64 {
65         .name = "at91sam7",
66         .register_commands = at91sam7_register_commands,
67         .flash_bank_command = at91sam7_flash_bank_command,
68         .erase = at91sam7_erase,
69         .protect = at91sam7_protect,
70         .write = at91sam7_write,
71         .probe = at91sam7_probe,
72         .auto_probe = at91sam7_probe,
73         .erase_check = at91sam7_erase_check,
74         .protect_check = at91sam7_protect_check,
75         .info = at91sam7_info
76 };
77
78 static uint32_t MC_FMR[4] = { 0xFFFFFF60, 0xFFFFFF70, 0xFFFFFF80, 0xFFFFFF90 };
79 static uint32_t MC_FCR[4] = { 0xFFFFFF64, 0xFFFFFF74, 0xFFFFFF84, 0xFFFFFF94 };
80 static uint32_t MC_FSR[4] = { 0xFFFFFF68, 0xFFFFFF78, 0xFFFFFF88, 0xFFFFFF98 };
81
82 static char * EPROC[8]= {"Unknown","ARM946-E","ARM7TDMI","Unknown","ARM920T","ARM926EJ-S","Unknown","Unknown"};
83
84 #if 0
85 static long SRAMSIZ[16] = {
86         -1,
87         0x0400,         /*  1K */
88         0x0800,         /*  2K */ 
89         -1, 
90         0x1c000,        /* 112K */
91         0x1000,         /*   4K */
92         0x14000,        /*  80K */
93         0x28000,        /* 160K */
94         0x2000,         /*   8K */
95         0x4000,         /*  16K */
96         0x8000,         /*  32K */
97         0x10000,        /*  64K */
98         0x20000,        /* 128K */
99         0x40000,        /* 256K */
100         0x18000,        /*  96K */
101         0x80000,        /* 512K */
102 };
103 #endif
104
105 static int at91sam7_register_commands(struct command_context_s *cmd_ctx)
106 {
107         command_t *at91sam7_cmd = register_command(cmd_ctx, NULL, "at91sam7", NULL, COMMAND_ANY, NULL);
108
109         register_command(cmd_ctx, at91sam7_cmd, "gpnvm", at91sam7_handle_gpnvm_command, COMMAND_EXEC,
110                                         "at91sam7 gpnvm <bit> set | clear, set or clear one gpnvm bit");
111         return ERROR_OK;
112 }
113
114 static uint32_t at91sam7_get_flash_status(target_t *target, int bank_number)
115 {
116         uint32_t fsr;
117         target_read_u32(target, MC_FSR[bank_number], &fsr);
118
119         return fsr;
120 }
121
122 /* Read clock configuration and set at91sam7_info->mck_freq */
123 static void at91sam7_read_clock_info(flash_bank_t *bank)
124 {
125         at91sam7_flash_bank_t *at91sam7_info = bank->driver_priv;
126         target_t *target = bank->target;
127         uint32_t mckr, mcfr, pllr, mor;
128         unsigned long tmp = 0, mainfreq;
129
130         /* Read Clock Generator Main Oscillator Register */
131         target_read_u32(target, CKGR_MOR, &mor);
132         /* Read Clock Generator Main Clock Frequency Register */
133         target_read_u32(target, CKGR_MCFR, &mcfr);
134         /* Read Master Clock Register*/
135         target_read_u32(target, PMC_MCKR, &mckr);
136         /* Read Clock Generator PLL Register  */
137         target_read_u32(target, CKGR_PLLR, &pllr);
138         
139         at91sam7_info->mck_valid = 0;
140         at91sam7_info->mck_freq = 0;
141         switch (mckr & PMC_MCKR_CSS) 
142         {
143                 case 0:                 /* Slow Clock */
144                         at91sam7_info->mck_valid = 1;
145                         tmp = RC_FREQ;
146                         break;
147
148                 case 1:                 /* Main Clock */
149                         if ((mcfr & CKGR_MCFR_MAINRDY) && 
150                                 (at91sam7_info->ext_freq == 0))
151                         {
152                                 at91sam7_info->mck_valid = 1;
153                                 tmp = RC_FREQ / 16ul * (mcfr & 0xffff);
154                         }
155                         else if (at91sam7_info->ext_freq != 0)
156                         {
157                                 at91sam7_info->mck_valid = 1;
158                                 tmp = at91sam7_info->ext_freq;
159                         }
160                         break;
161
162                 case 2:                 /* Reserved */
163                         break;
164
165                 case 3:                 /* PLL Clock */
166                         if ((mcfr & CKGR_MCFR_MAINRDY) && 
167                                 (at91sam7_info->ext_freq == 0)) 
168                         {
169                                 target_read_u32(target, CKGR_PLLR, &pllr);
170                                 if (!(pllr & CKGR_PLLR_DIV))
171                                         break; /* 0 Hz */
172                                 at91sam7_info->mck_valid = 1;
173                                 mainfreq = RC_FREQ / 16ul * (mcfr & 0xffff);
174                                 /* Integer arithmetic should have sufficient precision
175                                  * as long as PLL is properly configured. */
176                                 tmp = mainfreq / (pllr & CKGR_PLLR_DIV)*
177                                         (((pllr & CKGR_PLLR_MUL) >> 16) + 1);
178                         }
179                         else if ((at91sam7_info->ext_freq != 0) &&
180                                 ((pllr&CKGR_PLLR_DIV) != 0))
181                         {
182                                 at91sam7_info->mck_valid = 1;
183                                 tmp = at91sam7_info->ext_freq / (pllr&CKGR_PLLR_DIV)*
184                                         (((pllr & CKGR_PLLR_MUL) >> 16) + 1);
185                         }
186                         break;
187         }
188
189         /* Prescaler adjust */
190         if ((((mckr & PMC_MCKR_PRES) >> 2) == 7) || (tmp == 0))
191         {
192                 at91sam7_info->mck_valid = 0;
193                 at91sam7_info->mck_freq = 0;
194         }
195         else if (((mckr & PMC_MCKR_PRES) >> 2) != 0)
196                 at91sam7_info->mck_freq = tmp >> ((mckr & PMC_MCKR_PRES) >> 2);
197         else
198                 at91sam7_info->mck_freq = tmp;
199 }
200
201 /* Setup the timimg registers for nvbits or normal flash */
202 static void at91sam7_set_flash_mode(flash_bank_t *bank, int mode)
203 {
204         uint32_t fmr, fmcn = 0, fws = 0;
205         at91sam7_flash_bank_t *at91sam7_info = bank->driver_priv;
206         target_t *target = bank->target;
207
208         if (mode && (mode != at91sam7_info->flashmode))
209         {
210                 /* Always round up (ceil) */
211                 if (mode == FMR_TIMING_NVBITS)
212                 {
213                         if (at91sam7_info->cidr_arch == 0x60)
214                         {
215                                 /* AT91SAM7A3 uses master clocks in 100 ns */
216                                 fmcn = (at91sam7_info->mck_freq/10000000ul) + 1;
217                         }
218                         else
219                         {
220                                 /* master clocks in 1uS for ARCH 0x7 types */
221                                 fmcn = (at91sam7_info->mck_freq/1000000ul) + 1;
222                         }
223                 }
224                 else if (mode == FMR_TIMING_FLASH)
225                 {
226                         /* main clocks in 1.5uS */
227                         fmcn = (at91sam7_info->mck_freq/1000000ul)+
228                                 (at91sam7_info->mck_freq/2000000ul) + 1;
229                 }
230
231                 /* hard overclocking */
232                 if (fmcn > 0xFF)
233                         fmcn = 0xFF;
234
235                 /* Only allow fmcn = 0 if clock period is > 30 us = 33kHz. */
236                 if (at91sam7_info->mck_freq <= 33333ul)
237                         fmcn = 0;
238                 /* Only allow fws = 0 if clock frequency is < 30 MHz. */
239                 if (at91sam7_info->mck_freq > 30000000ul)
240                         fws = 1;
241
242                 LOG_DEBUG("fmcn[%i]: %i", bank->bank_number, (int)(fmcn));
243                 fmr = fmcn << 16 | fws << 8;
244                 target_write_u32(target, MC_FMR[bank->bank_number], fmr);
245         }
246
247         at91sam7_info->flashmode = mode;
248 }
249
250 static uint32_t at91sam7_wait_status_busy(flash_bank_t *bank, uint32_t waitbits, int timeout)
251 {
252         uint32_t status;
253
254         while ((!((status = at91sam7_get_flash_status(bank->target, bank->bank_number)) & waitbits)) && (timeout-- > 0))
255         {
256                 LOG_DEBUG("status[%i]: 0x%" PRIx32 "", (int)bank->bank_number, status);
257                 alive_sleep(1);
258         }
259
260         LOG_DEBUG("status[%i]: 0x%" PRIx32 "", bank->bank_number, status);
261
262         if (status & 0x0C)
263         {
264                 LOG_ERROR("status register: 0x%" PRIx32 "", status);
265                 if (status & 0x4)
266                         LOG_ERROR("Lock Error Bit Detected, Operation Abort");
267                 if (status & 0x8)
268                         LOG_ERROR("Invalid command and/or bad keyword, Operation Abort");
269                 if (status & 0x10)
270                         LOG_ERROR("Security Bit Set, Operation Abort");
271         }
272
273         return status;
274 }
275
276 /* Send one command to the AT91SAM flash controller */
277 static int at91sam7_flash_command(struct flash_bank_s *bank, uint8_t cmd, uint16_t pagen)
278 {
279         uint32_t fcr;
280         at91sam7_flash_bank_t *at91sam7_info = bank->driver_priv;
281         target_t *target = bank->target;
282
283         fcr = (0x5A << 24) | ((pagen&0x3FF) << 8) | cmd; 
284         target_write_u32(target, MC_FCR[bank->bank_number], fcr);
285         LOG_DEBUG("Flash command: 0x%" PRIx32 ", flash bank: %i, page number: %u", fcr, bank->bank_number + 1, pagen);
286
287         if ((at91sam7_info->cidr_arch == 0x60) && ((cmd == SLB) | (cmd == CLB)))
288         {
289                 /* Lock bit manipulation on AT91SAM7A3 waits for FC_FSR bit 1, EOL */
290                 if (at91sam7_wait_status_busy(bank, MC_FSR_EOL, 10)&0x0C)
291                 {
292                         return ERROR_FLASH_OPERATION_FAILED;
293                 }
294                 return ERROR_OK;
295         }
296
297         if (at91sam7_wait_status_busy(bank, MC_FSR_FRDY, 10)&0x0C) 
298         {
299                 return ERROR_FLASH_OPERATION_FAILED;
300         }
301
302         return ERROR_OK;
303 }
304
305 /* Read device id register, main clock frequency register and fill in driver info structure */
306 static int at91sam7_read_part_info(struct flash_bank_s *bank)
307 {
308         flash_bank_t *t_bank = bank;
309         at91sam7_flash_bank_t *at91sam7_info;
310         target_t *target = t_bank->target;
311
312         uint16_t bnk, sec;
313         uint16_t arch;
314         uint32_t cidr;
315         uint8_t banks_num = 0;
316         uint16_t num_nvmbits = 0;
317         uint16_t sectors_num = 0;
318         uint16_t pages_per_sector = 0;
319         uint16_t page_size = 0;
320         uint32_t ext_freq;
321         uint32_t bank_size;
322         uint32_t base_address = 0;
323         char *target_name = "Unknown";
324
325         at91sam7_info = t_bank->driver_priv;
326
327         if (at91sam7_info->cidr != 0)
328         {
329                 /* flash already configured, update clock and check for protected sectors */
330                 flash_bank_t *fb = bank;
331                 t_bank = fb;
332
333                 while (t_bank)
334                 {
335                         /* re-calculate master clock frequency */
336                         at91sam7_read_clock_info(t_bank);
337
338                         /* no timming */
339                         at91sam7_set_flash_mode(t_bank, FMR_TIMING_NONE);
340
341                         /* check protect state */
342                         at91sam7_protect_check(t_bank);
343
344                         t_bank = fb->next;
345                         fb = t_bank;
346                 }
347
348                 return ERROR_OK;
349         }
350
351         /* Read and parse chip identification register */
352         target_read_u32(target, DBGU_CIDR, &cidr);
353         if (cidr == 0)
354         {
355                 LOG_WARNING("Cannot identify target as an AT91SAM");
356                 return ERROR_FLASH_OPERATION_FAILED;
357         }
358
359         if (at91sam7_info->flash_autodetection == 0)
360         {
361                 /* banks and sectors are already created, based on data from input file */
362                 flash_bank_t *fb = bank;
363                 t_bank = fb;
364                 while (t_bank)
365                 {
366                         at91sam7_info = t_bank->driver_priv;
367
368                         at91sam7_info->cidr = cidr;
369                         at91sam7_info->cidr_ext = (cidr >> 31)&0x0001;
370                         at91sam7_info->cidr_nvptyp = (cidr >> 28)&0x0007;
371                         at91sam7_info->cidr_arch = (cidr >> 20)&0x00FF;
372                         at91sam7_info->cidr_sramsiz = (cidr >> 16)&0x000F;
373                         at91sam7_info->cidr_nvpsiz2 = (cidr >> 12)&0x000F;
374                         at91sam7_info->cidr_nvpsiz = (cidr >> 8)&0x000F;
375                         at91sam7_info->cidr_eproc = (cidr >> 5)&0x0007;
376                         at91sam7_info->cidr_version = cidr&0x001F;
377
378                         /* calculate master clock frequency */
379                         at91sam7_read_clock_info(t_bank);
380
381                         /* no timming */
382                         at91sam7_set_flash_mode(t_bank, FMR_TIMING_NONE);
383
384                         /* check protect state */
385                         at91sam7_protect_check(t_bank);
386
387                         t_bank = fb->next;
388                         fb = t_bank;
389                 }
390
391                 return ERROR_OK;
392         }
393
394         arch = (cidr >> 20)&0x00FF;
395
396         /* check flash size */
397         switch ((cidr >> 8)&0x000F)
398         {
399                 case FLASH_SIZE_8KB:
400                         break;
401
402                 case FLASH_SIZE_16KB:
403                         banks_num = 1;
404                         sectors_num = 8;
405                         pages_per_sector = 32;
406                         page_size  = 64;
407                         base_address = 0x00100000;
408                         if (arch == 0x70)
409                         {
410                                 num_nvmbits = 2;
411                                 target_name = "AT91SAM7S161/16";
412                         }
413                         break;
414
415                 case FLASH_SIZE_32KB:
416                         banks_num = 1;
417                         sectors_num = 8;
418                         pages_per_sector = 32;
419                         page_size  = 128;
420                         base_address = 0x00100000;
421                         if (arch == 0x70)
422                         {
423                                 num_nvmbits = 2;
424                                 target_name = "AT91SAM7S321/32";
425                         }
426                         if (arch == 0x72)
427                         {
428                                 num_nvmbits = 3;
429                                 target_name = "AT91SAM7SE32";
430                         }
431                         break;
432
433                 case FLASH_SIZE_64KB:
434                         banks_num = 1;
435                         sectors_num = 16;
436                         pages_per_sector = 32;
437                         page_size  = 128;
438                         base_address = 0x00100000;
439                         if (arch == 0x70)
440                         {
441                                 num_nvmbits = 2;
442                                 target_name = "AT91SAM7S64";
443                         }
444                         break;
445
446                 case FLASH_SIZE_128KB:
447                         banks_num = 1;
448                         sectors_num = 8;
449                         pages_per_sector = 64;
450                         page_size  = 256;
451                         base_address = 0x00100000;
452                         if (arch == 0x70)
453                         {
454                                 num_nvmbits = 2;
455                                 target_name = "AT91SAM7S128";
456                         }
457                         if (arch == 0x71)
458                         {
459                                 num_nvmbits = 3;
460                                 target_name = "AT91SAM7XC128";
461                         }
462                         if (arch == 0x72)
463                         {
464                                 num_nvmbits = 3;
465                                 target_name = "AT91SAM7SE128";
466                         }
467                         if (arch == 0x75)
468                         {
469                                 num_nvmbits = 3;
470                                 target_name = "AT91SAM7X128";
471                         }
472                         break;
473
474                 case FLASH_SIZE_256KB:
475                         banks_num = 1;
476                         sectors_num = 16;
477                         pages_per_sector = 64;
478                         page_size  = 256;
479                         base_address = 0x00100000;
480                         if (arch == 0x60)
481                         {
482                                 num_nvmbits = 3;
483                                 target_name = "AT91SAM7A3";
484                         }
485                         if (arch == 0x70)
486                         {
487                                 num_nvmbits = 2;
488                                 target_name = "AT91SAM7S256";
489                         }
490                         if (arch == 0x71)
491                         {
492                                 num_nvmbits = 3;
493                                 target_name = "AT91SAM7XC256";
494                         }
495                         if (arch == 0x72)
496                         {
497                                 num_nvmbits = 3;
498                                 target_name = "AT91SAM7SE256";
499                         }
500                         if (arch == 0x75)
501                         {
502                                 num_nvmbits = 3;
503                                 target_name = "AT91SAM7X256";
504                         }
505                         break;
506
507                 case FLASH_SIZE_512KB:
508                         banks_num = 2;
509                         sectors_num = 16;
510                         pages_per_sector = 64;
511                         page_size  = 256;
512                         base_address = 0x00100000;
513                         if (arch == 0x70)
514                         {
515                                 num_nvmbits = 2;
516                                 target_name = "AT91SAM7S512";
517                         }
518                         if (arch == 0x71)
519                         {
520                                 num_nvmbits = 3;
521                                 target_name = "AT91SAM7XC512";
522                         }
523                         if (arch == 0x72)
524                         {
525                                 num_nvmbits = 3;
526                                 target_name = "AT91SAM7SE512";
527                         }
528                         if (arch == 0x75)
529                         {
530                                 num_nvmbits = 3;
531                                 target_name = "AT91SAM7X512";
532                         }
533                         break;
534
535                 case FLASH_SIZE_1024KB:
536                         break;
537
538                 case FLASH_SIZE_2048KB:
539                         break;
540         }
541
542         if (strcmp(target_name, "Unknown") == 0)
543         {
544                 LOG_ERROR("Target autodetection failed! Please specify target parameters in configuration file");
545                 return ERROR_FLASH_OPERATION_FAILED;
546         }
547
548         ext_freq = at91sam7_info->ext_freq;
549
550         /* calculate bank size  */
551         bank_size = sectors_num * pages_per_sector * page_size;
552
553         for (bnk = 0; bnk < banks_num; bnk++)
554         {
555                 if (bnk > 0)
556                 {
557                         /* create a new flash bank element */
558                         flash_bank_t *fb = malloc(sizeof(flash_bank_t));
559                         fb->target = target;
560                         fb->driver = &at91sam7_flash;
561                         fb->driver_priv = malloc(sizeof(at91sam7_flash_bank_t));
562                         fb->next = NULL;
563
564                         /* link created bank in 'flash_banks' list and redirect t_bank */
565                         t_bank->next = fb;
566                         t_bank = fb;
567                 }
568
569                 t_bank->bank_number = bnk;
570                 t_bank->base = base_address + bnk * bank_size;
571                 t_bank->size = bank_size;
572                 t_bank->chip_width = 0;
573                 t_bank->bus_width = 4;
574                 t_bank->num_sectors = sectors_num;
575
576                 /* allocate sectors */
577                 t_bank->sectors = malloc(sectors_num * sizeof(flash_sector_t));
578                 for (sec = 0; sec < sectors_num; sec++)
579                 {
580                         t_bank->sectors[sec].offset = sec * pages_per_sector * page_size;
581                         t_bank->sectors[sec].size = pages_per_sector * page_size;
582                         t_bank->sectors[sec].is_erased = -1;
583                         t_bank->sectors[sec].is_protected = -1;
584                 }
585
586                 at91sam7_info = t_bank->driver_priv;
587
588                 at91sam7_info->cidr = cidr;
589                 at91sam7_info->cidr_ext = (cidr >> 31)&0x0001;
590                 at91sam7_info->cidr_nvptyp = (cidr >> 28)&0x0007;
591                 at91sam7_info->cidr_arch = (cidr >> 20)&0x00FF;
592                 at91sam7_info->cidr_sramsiz = (cidr >> 16)&0x000F;
593                 at91sam7_info->cidr_nvpsiz2 = (cidr >> 12)&0x000F;
594                 at91sam7_info->cidr_nvpsiz = (cidr >> 8)&0x000F;
595                 at91sam7_info->cidr_eproc = (cidr >> 5)&0x0007;
596                 at91sam7_info->cidr_version = cidr&0x001F;
597
598                 at91sam7_info->target_name  = target_name;
599                 at91sam7_info->flashmode = 0;
600                 at91sam7_info->ext_freq = ext_freq;
601                 at91sam7_info->num_nvmbits = num_nvmbits;
602                 at91sam7_info->num_nvmbits_on = 0;
603                 at91sam7_info->pagesize = page_size;
604                 at91sam7_info->pages_per_sector = pages_per_sector;
605
606                 /* calculate master clock frequency */
607                 at91sam7_read_clock_info(t_bank);
608
609                 /* no timming */
610                 at91sam7_set_flash_mode(t_bank, FMR_TIMING_NONE);
611
612                 /* check protect state */
613                 at91sam7_protect_check(t_bank);
614         }
615
616         LOG_DEBUG("nvptyp: 0x%3.3x, arch: 0x%4.4x", at91sam7_info->cidr_nvptyp, at91sam7_info->cidr_arch);
617
618         return ERROR_OK;
619 }
620
621 static int at91sam7_erase_check(struct flash_bank_s *bank)
622 {
623         target_t *target = bank->target;
624         uint16_t retval;
625         uint32_t blank;
626         uint16_t fast_check;
627         uint8_t *buffer;
628         uint16_t nSector;
629         uint16_t nByte;
630
631         if (bank->target->state != TARGET_HALTED)
632         {
633                 LOG_ERROR("Target not halted");
634                 return ERROR_TARGET_NOT_HALTED;
635         }
636
637         /* Configure the flash controller timing */
638         at91sam7_read_clock_info(bank); 
639         at91sam7_set_flash_mode(bank, FMR_TIMING_FLASH);
640
641         fast_check = 1;
642         for (nSector = 0; nSector < bank->num_sectors; nSector++)
643         {
644                 retval = target_blank_check_memory(target, bank->base + bank->sectors[nSector].offset,
645                         bank->sectors[nSector].size, &blank);
646                 if (retval != ERROR_OK)
647                 {
648                         fast_check = 0;
649                         break;
650                 }
651                 if (blank == 0xFF)
652                         bank->sectors[nSector].is_erased = 1;
653                 else
654                         bank->sectors[nSector].is_erased = 0;
655         }
656
657         if (fast_check)
658         {
659                 return ERROR_OK;
660         }
661
662         LOG_USER("Running slow fallback erase check - add working memory");
663
664         buffer = malloc(bank->sectors[0].size);
665         for (nSector = 0; nSector < bank->num_sectors; nSector++)
666         {
667                 bank->sectors[nSector].is_erased = 1;
668                 retval = target_read_memory(target, bank->base + bank->sectors[nSector].offset, 4,
669                         bank->sectors[nSector].size/4, buffer);
670                 if (retval != ERROR_OK)
671                         return retval;
672
673                 for (nByte = 0; nByte < bank->sectors[nSector].size; nByte++)
674                 {
675                         if (buffer[nByte] != 0xFF)
676                         {
677                                 bank->sectors[nSector].is_erased = 0;
678                                 break;
679                         }
680                 }
681         }
682         free(buffer);
683
684         return ERROR_OK;
685 }
686
687 static int at91sam7_protect_check(struct flash_bank_s *bank)
688 {
689         uint8_t lock_pos, gpnvm_pos;
690         uint32_t status;
691
692         at91sam7_flash_bank_t *at91sam7_info = bank->driver_priv;
693
694         if (at91sam7_info->cidr == 0)
695         {
696                 return ERROR_FLASH_BANK_NOT_PROBED;
697         }
698         if (bank->target->state != TARGET_HALTED)
699         {
700                 LOG_ERROR("Target not halted");
701                 return ERROR_TARGET_NOT_HALTED;
702         }
703
704         status = at91sam7_get_flash_status(bank->target, bank->bank_number);
705         at91sam7_info->lockbits = (status >> 16);
706
707         at91sam7_info->num_lockbits_on = 0;
708         for (lock_pos = 0; lock_pos < bank->num_sectors; lock_pos++)
709         {
710                 if (((status >> (16 + lock_pos))&(0x0001)) == 1)
711                 {
712                         at91sam7_info->num_lockbits_on++;
713                         bank->sectors[lock_pos].is_protected = 1;
714                 }
715                 else
716                         bank->sectors[lock_pos].is_protected = 0;
717         }
718
719         /* GPNVM and SECURITY bits apply only for MC_FSR of EFC0 */
720         status = at91sam7_get_flash_status(bank->target, 0);
721
722         at91sam7_info->securitybit = (status >> 4)&0x01;
723         at91sam7_info->nvmbits = (status >> 8)&0xFF;
724
725         at91sam7_info->num_nvmbits_on = 0;
726         for (gpnvm_pos = 0; gpnvm_pos < at91sam7_info->num_nvmbits; gpnvm_pos++)
727         {
728                 if (((status >> (8 + gpnvm_pos))&(0x01)) == 1)
729                 {
730                         at91sam7_info->num_nvmbits_on++;
731                 }
732         }
733
734         return ERROR_OK;
735 }
736
737 /***************************************************************************************************************************************************************************************
738 # flash bank <driver> <base_addr> <size> <chip_width> <bus_width> <target_number> [<target_name> <banks> <sectors_per_bank> <pages_per_sector> <page_size> <num_nvmbits> <ext_freq_khz>]
739 #   <ext_freq_khz> - MUST be used if clock is from external source
740 #                    CAN be used if main oscillator frequency is known
741 # Examples:
742 #  flash bank at91sam7 0x00100000 0 0 4 0 0 AT91SAM7XC256 1 16 64 256 3 25000                   ==== RECOMENDED ============
743 #  flash bank at91sam7 0 0 0 0 0 0 0 0 0 0 0 0 25000    (auto-detection, except for clock)      ==== RECOMENDED ============
744 #  flash bank at91sam7 0x00100000 0 0 4 0 0 AT91SAM7XC256 1 16 64 256 3 0                       ==== NOT RECOMENDED !!! ====
745 #  flash bank at91sam7 0 0 0 0 0                        (old style, full auto-detection)        ==== NOT RECOMENDED !!! ====
746 ****************************************************************************************************************************************************************************************/
747 static int at91sam7_flash_bank_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, struct flash_bank_s *bank)
748 {
749         flash_bank_t *t_bank = bank;
750         at91sam7_flash_bank_t *at91sam7_info;
751         target_t *target = t_bank->target;
752
753         uint32_t base_address;
754         uint32_t bank_size;
755         uint32_t ext_freq;
756
757         int chip_width;
758         int bus_width;
759         int banks_num;
760         int num_sectors;
761
762         uint16_t pages_per_sector;
763         uint16_t page_size;
764         uint16_t num_nvmbits;
765
766         char *target_name;
767
768         int bnk, sec;
769
770         at91sam7_info = malloc(sizeof(at91sam7_flash_bank_t));
771         t_bank->driver_priv = at91sam7_info;
772
773         /* part wasn't probed for info yet */
774         at91sam7_info->cidr = 0;
775         at91sam7_info->flashmode = 0;
776         at91sam7_info->ext_freq = 0;
777         at91sam7_info->flash_autodetection = 0;
778
779         if (argc == 14)
780         {
781                 ext_freq = atol(args[13]) * 1000;
782                 at91sam7_info->ext_freq = ext_freq;
783         }
784
785         if ((argc != 14)                ||
786                 (atoi(args[4]) == 0)        ||  /* bus width */
787                 (atoi(args[8]) == 0)        ||  /* banks number */
788                 (atoi(args[9]) == 0)        ||  /* sectors per bank */
789                 (atoi(args[10]) == 0)       ||  /* pages per sector */
790                 (atoi(args[11]) == 0)       ||  /* page size */
791                 (atoi(args[12]) == 0))          /* nvmbits number */
792         {
793                 at91sam7_info->flash_autodetection = 1;
794                 return ERROR_OK;
795         }
796
797         base_address = strtoul(args[1], NULL, 0);
798         chip_width = atoi(args[3]);
799         bus_width = atoi(args[4]);
800         banks_num = atoi(args[8]);
801         num_sectors = atoi(args[9]);
802         pages_per_sector = atoi(args[10]);
803         page_size = atoi(args[11]);
804         num_nvmbits = atoi(args[12]);
805
806         target_name = calloc(strlen(args[7]) + 1, sizeof(char));
807         strcpy(target_name, args[7]);
808
809         /* calculate bank size  */
810         bank_size = num_sectors * pages_per_sector * page_size;
811
812         for (bnk = 0; bnk < banks_num; bnk++)
813         {
814                 if (bnk > 0)
815                 {
816                         /* create a new bank element */
817                         flash_bank_t *fb = malloc(sizeof(flash_bank_t));
818                         fb->target = target;
819                         fb->driver = &at91sam7_flash;
820                         fb->driver_priv = malloc(sizeof(at91sam7_flash_bank_t));
821                         fb->next = NULL;
822
823                         /* link created bank in 'flash_banks' list and redirect t_bank */
824                         t_bank->next = fb;
825                         t_bank = fb;
826                 }
827
828                 t_bank->bank_number = bnk;
829                 t_bank->base = base_address + bnk * bank_size;
830                 t_bank->size = bank_size;
831                 t_bank->chip_width = chip_width;
832                 t_bank->bus_width = bus_width;
833                 t_bank->num_sectors = num_sectors;
834
835                 /* allocate sectors */
836                 t_bank->sectors = malloc(num_sectors * sizeof(flash_sector_t));
837                 for (sec = 0; sec < num_sectors; sec++)
838                 {
839                         t_bank->sectors[sec].offset = sec * pages_per_sector * page_size;
840                         t_bank->sectors[sec].size = pages_per_sector * page_size;
841                         t_bank->sectors[sec].is_erased = -1;
842                         t_bank->sectors[sec].is_protected = -1;
843                 }
844
845                 at91sam7_info = t_bank->driver_priv;
846
847                 at91sam7_info->target_name  = target_name;
848                 at91sam7_info->flashmode = 0;
849                 at91sam7_info->ext_freq  = ext_freq;
850                 at91sam7_info->num_nvmbits = num_nvmbits;
851                 at91sam7_info->num_nvmbits_on = 0;
852                 at91sam7_info->pagesize = page_size;
853                 at91sam7_info->pages_per_sector = pages_per_sector;
854         }
855
856         return ERROR_OK;
857 }
858
859 static int at91sam7_erase(struct flash_bank_s *bank, int first, int last)
860 {
861         at91sam7_flash_bank_t *at91sam7_info = bank->driver_priv;
862         int sec;
863         uint32_t nbytes, pos;
864         uint8_t *buffer;
865         uint8_t erase_all;
866
867         if (at91sam7_info->cidr == 0)
868         {
869                 return ERROR_FLASH_BANK_NOT_PROBED;
870         }
871
872         if (bank->target->state != TARGET_HALTED)
873         {
874                 LOG_ERROR("Target not halted");
875                 return ERROR_TARGET_NOT_HALTED;
876         }
877
878         if ((first < 0) || (last < first) || (last >= bank->num_sectors))
879         {
880                 return ERROR_FLASH_SECTOR_INVALID;
881         }
882
883         erase_all = 0;
884         if ((first == 0) && (last == (bank->num_sectors-1)))
885         {
886                 erase_all = 1;
887         }
888
889         /* Configure the flash controller timing */
890         at91sam7_read_clock_info(bank);
891         at91sam7_set_flash_mode(bank, FMR_TIMING_FLASH);
892
893         if (erase_all)
894         {
895                 if (at91sam7_flash_command(bank, EA, 0) != ERROR_OK) 
896                 {
897                         return ERROR_FLASH_OPERATION_FAILED;
898                 }
899         }
900         else
901         {
902                 /* allocate and clean buffer  */
903                 nbytes = (last - first + 1) * bank->sectors[first].size;
904                 buffer = malloc(nbytes * sizeof(uint8_t));
905                 for (pos = 0; pos < nbytes; pos++)
906                 {
907                         buffer[pos] = 0xFF;
908                 }
909
910                 if (at91sam7_write(bank, buffer, bank->sectors[first].offset, nbytes) != ERROR_OK)
911                 {
912                         return ERROR_FLASH_OPERATION_FAILED;
913                 }
914
915                 free(buffer);
916         }
917
918         /* mark erased sectors */
919         for (sec = first; sec <= last; sec++)
920         {
921                 bank->sectors[sec].is_erased = 1;
922         }
923
924         return ERROR_OK;
925 }
926
927 static int at91sam7_protect(struct flash_bank_s *bank, int set, int first, int last)
928 {
929         uint32_t cmd;
930         int sector;
931         uint32_t pagen;
932
933         at91sam7_flash_bank_t *at91sam7_info = bank->driver_priv;
934
935         if (at91sam7_info->cidr == 0)
936         {
937                 return ERROR_FLASH_BANK_NOT_PROBED;
938         }
939
940         if (bank->target->state != TARGET_HALTED)
941         {
942                 LOG_ERROR("Target not halted");
943                 return ERROR_TARGET_NOT_HALTED;
944         }
945
946         if ((first < 0) || (last < first) || (last >= bank->num_sectors))
947         {
948                 return ERROR_FLASH_SECTOR_INVALID;
949         }
950
951         /* Configure the flash controller timing */
952         at91sam7_read_clock_info(bank);
953         at91sam7_set_flash_mode(bank, FMR_TIMING_NVBITS);
954
955         for (sector = first; sector <= last; sector++)
956         {
957                 if (set)
958                         cmd = SLB;
959                 else
960                         cmd = CLB;
961
962                 /* if we lock a page from one sector then entire sector will be locked, also,
963                  * if we unlock a page from a locked sector, entire sector will be unlocked   */
964                 pagen = sector * at91sam7_info->pages_per_sector;
965
966                 if (at91sam7_flash_command(bank, cmd, pagen) != ERROR_OK)
967                 {
968                         return ERROR_FLASH_OPERATION_FAILED;
969                 }
970         }
971
972         at91sam7_protect_check(bank);
973
974         return ERROR_OK;
975 }
976
977 static int at91sam7_write(struct flash_bank_s *bank, uint8_t *buffer, uint32_t offset, uint32_t count)
978 {
979         int retval;
980         at91sam7_flash_bank_t *at91sam7_info = bank->driver_priv;
981         target_t *target = bank->target;
982         uint32_t dst_min_alignment, wcount, bytes_remaining = count;
983         uint32_t first_page, last_page, pagen, buffer_pos;
984
985         if (at91sam7_info->cidr == 0)
986         {
987                 return ERROR_FLASH_BANK_NOT_PROBED;
988         }
989
990         if (bank->target->state != TARGET_HALTED)
991         {
992                 LOG_ERROR("Target not halted");
993                 return ERROR_TARGET_NOT_HALTED;
994         }
995
996         if (offset + count > bank->size)
997                 return ERROR_FLASH_DST_OUT_OF_BANK;
998
999         dst_min_alignment = at91sam7_info->pagesize;
1000
1001         if (offset % dst_min_alignment)
1002         {
1003                 LOG_WARNING("offset 0x%" PRIx32 " breaks required alignment 0x%" PRIx32 "", offset, dst_min_alignment);
1004                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
1005         }
1006
1007         if (at91sam7_info->cidr_arch == 0)
1008                 return ERROR_FLASH_BANK_NOT_PROBED;
1009
1010         first_page = offset/dst_min_alignment;
1011         last_page = CEIL(offset + count, dst_min_alignment);
1012
1013         LOG_DEBUG("first_page: %i, last_page: %i, count %i", (int)first_page, (int)last_page, (int)count);
1014
1015         /* Configure the flash controller timing */
1016         at91sam7_read_clock_info(bank);
1017         at91sam7_set_flash_mode(bank, FMR_TIMING_FLASH);
1018
1019         for (pagen = first_page; pagen < last_page; pagen++)
1020         {
1021                 if (bytes_remaining < dst_min_alignment)
1022                         count = bytes_remaining;
1023                 else
1024                         count = dst_min_alignment;
1025                 bytes_remaining -= count;
1026
1027                 /* Write one block to the PageWriteBuffer */
1028                 buffer_pos = (pagen-first_page)*dst_min_alignment;
1029                 wcount = CEIL(count,4);
1030                 if ((retval = target_write_memory(target, bank->base + pagen*dst_min_alignment, 4, wcount, buffer + buffer_pos)) != ERROR_OK)
1031                 {
1032                         return retval;
1033                 }
1034
1035                 /* Send Write Page command to Flash Controller */
1036                 if (at91sam7_flash_command(bank, WP, pagen) != ERROR_OK)
1037                 {
1038                         return ERROR_FLASH_OPERATION_FAILED;
1039                 }
1040                 LOG_DEBUG("Write flash bank:%i page number:%" PRIi32 "", bank->bank_number, pagen);
1041         }
1042
1043         return ERROR_OK;
1044 }
1045
1046 static int at91sam7_probe(struct flash_bank_s *bank)
1047 {
1048         /* we can't probe on an at91sam7
1049          * if this is an at91sam7, it has the configured flash */
1050         int retval;
1051
1052         if (bank->target->state != TARGET_HALTED)
1053         {
1054                 LOG_ERROR("Target not halted");
1055                 return ERROR_TARGET_NOT_HALTED;
1056         }
1057
1058         retval = at91sam7_read_part_info(bank);
1059         if (retval != ERROR_OK)
1060                 return retval;
1061
1062         return ERROR_OK;
1063 }
1064
1065 static int at91sam7_info(struct flash_bank_s *bank, char *buf, int buf_size)
1066 {
1067         int printed;
1068         at91sam7_flash_bank_t *at91sam7_info = bank->driver_priv;
1069
1070         if (at91sam7_info->cidr == 0)
1071         {
1072                 return ERROR_FLASH_BANK_NOT_PROBED;
1073         }
1074
1075         printed = snprintf(buf, buf_size,
1076                 "\n at91sam7 driver information: Chip is %s\n",
1077                 at91sam7_info->target_name);
1078
1079         buf += printed;
1080         buf_size -= printed;
1081
1082         printed = snprintf(buf, 
1083                            buf_size,
1084                            " Cidr: 0x%8.8" PRIx32 " | Arch: 0x%4.4x | Eproc: %s | Version: 0x%3.3x | Flashsize: 0x%8.8" PRIx32 "\n",
1085                            at91sam7_info->cidr, 
1086                            at91sam7_info->cidr_arch, 
1087                            EPROC[at91sam7_info->cidr_eproc],
1088                            at91sam7_info->cidr_version, 
1089                            bank->size);
1090
1091         buf += printed;
1092         buf_size -= printed;
1093
1094         printed = snprintf(buf, buf_size,
1095                 " Master clock (estimated): %u KHz | External clock: %u KHz\n",
1096                 (unsigned)(at91sam7_info->mck_freq / 1000), (unsigned)(at91sam7_info->ext_freq / 1000));
1097
1098         buf += printed;
1099         buf_size -= printed;
1100
1101         printed = snprintf(buf, buf_size,
1102                 " Pagesize: %i bytes | Lockbits(%i): %i 0x%4.4x | Pages in lock region: %i \n",
1103                 at91sam7_info->pagesize, bank->num_sectors, at91sam7_info->num_lockbits_on,
1104                 at91sam7_info->lockbits, at91sam7_info->pages_per_sector*at91sam7_info->num_lockbits_on);
1105
1106         buf += printed;
1107         buf_size -= printed;
1108
1109         printed = snprintf(buf, buf_size,
1110                 " Securitybit: %i | Nvmbits(%i): %i 0x%1.1x\n",
1111                 at91sam7_info->securitybit, at91sam7_info->num_nvmbits,
1112                 at91sam7_info->num_nvmbits_on, at91sam7_info->nvmbits);
1113
1114         buf += printed;
1115         buf_size -= printed;
1116
1117         return ERROR_OK;
1118 }
1119
1120 /* 
1121 * On AT91SAM7S: When the gpnvm bits are set with 
1122 * > at91sam7 gpnvm bitnr set
1123 * the changes are not visible in the flash controller status register MC_FSR 
1124 * until the processor has been reset.
1125 * On the Olimex board this requires a power cycle.
1126 * Note that the AT91SAM7S has the following errata (doc6175.pdf sec 14.1.3):
1127 *   The maximum number of write/erase cycles for Non volatile Memory bits is 100. this includes
1128 *   Lock Bits (LOCKx), General Purpose NVM bits (GPNVMx) and the Security Bit.
1129 */
1130 static int at91sam7_handle_gpnvm_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1131 {
1132         flash_bank_t *bank;
1133         int bit;
1134         uint8_t  flashcmd;
1135         uint32_t status;
1136         at91sam7_flash_bank_t *at91sam7_info;
1137         int retval;
1138
1139         if (argc != 2)
1140         {
1141                 command_print(cmd_ctx, "at91sam7 gpnvm <bit> <set | clear>");
1142                 return ERROR_OK;
1143         }
1144
1145         bank = get_flash_bank_by_num_noprobe(0);
1146         if (bank ==  NULL)
1147         {
1148                 return ERROR_FLASH_BANK_INVALID;
1149         }
1150         if (bank->driver != &at91sam7_flash)
1151         {
1152                 command_print(cmd_ctx, "not an at91sam7 flash bank '%s'", args[0]);
1153                 return ERROR_FLASH_BANK_INVALID;
1154         }
1155         if (bank->target->state != TARGET_HALTED)
1156         {
1157                 LOG_ERROR("target has to be halted to perform flash operation");
1158                 return ERROR_TARGET_NOT_HALTED;
1159         }
1160
1161         if (strcmp(args[1], "set") == 0)
1162         {
1163                 flashcmd = SGPB;
1164         }
1165         else if (strcmp(args[1], "clear") == 0)
1166         {
1167                 flashcmd = CGPB;
1168         }
1169         else
1170         {
1171                 return ERROR_COMMAND_SYNTAX_ERROR;
1172         }
1173
1174         at91sam7_info = bank->driver_priv;
1175         if (at91sam7_info->cidr == 0)
1176         {
1177                 retval = at91sam7_read_part_info(bank);
1178                 if (retval != ERROR_OK)
1179                 {
1180                         return retval;
1181                 }
1182         }
1183
1184         bit = atoi(args[0]);
1185         if ((bit < 0) || (bit >= at91sam7_info->num_nvmbits))
1186         {
1187                 command_print(cmd_ctx, "gpnvm bit '#%s' is out of bounds for target %s", args[0], at91sam7_info->target_name);
1188                 return ERROR_OK;
1189         }
1190
1191         /* Configure the flash controller timing */
1192         at91sam7_read_clock_info(bank);
1193         at91sam7_set_flash_mode(bank, FMR_TIMING_NVBITS);
1194         
1195         if (at91sam7_flash_command(bank, flashcmd, bit) != ERROR_OK)
1196         {
1197                 return ERROR_FLASH_OPERATION_FAILED;
1198         }
1199
1200         /* GPNVM and SECURITY bits apply only for MC_FSR of EFC0 */
1201         status = at91sam7_get_flash_status(bank->target, 0);
1202         LOG_DEBUG("at91sam7_handle_gpnvm_command: cmd 0x%x, value %d, status 0x%" PRIx32 " \n", flashcmd, bit, status);
1203
1204         /* check protect state */
1205         at91sam7_protect_check(bank);
1206         
1207         return ERROR_OK;
1208 }