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