Fix assert to check flash programming offset
[fw/openocd] / src / flash / nor / at91sam3.c
1 /***************************************************************************
2  *   Copyright (C) 2009 by Duane Ellis                                     *
3  *   openocd@duaneellis.com                                                *
4  *                                                                         *
5  *   Copyright (C) 2010 by Olaf Lüke (at91sam3s* support)                  *
6  *   olaf@uni-paderborn.de                                                 *
7  *                                                                         *
8  *                                                                         *
9  *   This program is free software; you can redistribute it and/or modify  *
10  *   it under the terms of the GNU General public License as published by  *
11  *   the Free Software Foundation; either version 2 of the License, or     *
12  *   (at your option) any later version.                                   *
13  *                                                                         *
14  *   This program is distributed in the hope that it will be useful,       *
15  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
16  *   MERCHANTABILITY or FITNESS for A PARTICULAR PURPOSE.  See the         *
17  *   GNU General public License for more details.                          *
18  *                                                                         *
19  *   You should have received a copy of the GNU General public License     *
20  *   along with this program; if not, write to the                         *
21  *   Free Software Foundation, Inc.,                                       *
22  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
23 ****************************************************************************/
24
25 /* Some of the the lower level code was based on code supplied by
26  * ATMEL under this copyright. */
27
28 /* BEGIN ATMEL COPYRIGHT */
29 /* ----------------------------------------------------------------------------
30  *         ATMEL Microcontroller Software Support
31  * ----------------------------------------------------------------------------
32  * Copyright (c) 2009, Atmel Corporation
33  *
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions are met:
38  *
39  * - Redistributions of source code must retain the above copyright notice,
40  * this list of conditions and the disclaimer below.
41  *
42  * Atmel's name may not be used to endorse or promote products derived from
43  * this software without specific prior written permission.
44  *
45  * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
46  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
47  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
48  * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
49  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
50  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
51  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
52  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
53  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
54  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
55  * ----------------------------------------------------------------------------
56  */
57 /* END ATMEL COPYRIGHT */
58
59 #ifdef HAVE_CONFIG_H
60 #include "config.h"
61 #endif
62
63 #include "imp.h"
64 #include <helper/time_support.h>
65
66 #define REG_NAME_WIDTH  (12)
67
68 /* at91sam3u series (has one or two flash banks) */
69 #define FLASH_BANK0_BASE_U   0x00080000
70 #define FLASH_BANK1_BASE_U   0x00100000
71
72 /* at91sam3s series (has always one flash bank) */
73 #define FLASH_BANK_BASE_S   0x00400000
74
75 /* at91sam3n series (has always one flash bank) */
76 #define FLASH_BANK_BASE_N   0x00400000
77
78 #define         AT91C_EFC_FCMD_GETD                 (0x0)       /* (EFC) Get Flash Descriptor */
79 #define         AT91C_EFC_FCMD_WP                   (0x1)       /* (EFC) Write Page */
80 #define         AT91C_EFC_FCMD_WPL                  (0x2)       /* (EFC) Write Page and Lock */
81 #define         AT91C_EFC_FCMD_EWP                  (0x3)       /* (EFC) Erase Page and Write Page */
82 #define         AT91C_EFC_FCMD_EWPL                 (0x4)       /* (EFC) Erase Page and Write Page
83                                                                  * then Lock */
84 #define         AT91C_EFC_FCMD_EA                   (0x5)       /* (EFC) Erase All */
85 /* cmd6 is not present int he at91sam3u4/2/1 data sheet table 17-2 */
86 /* #define      AT91C_EFC_FCMD_EPL                  (0x6) // (EFC) Erase plane? */
87 /* cmd7 is not present int he at91sam3u4/2/1 data sheet table 17-2 */
88 /* #define      AT91C_EFC_FCMD_EPA                  (0x7) // (EFC) Erase pages? */
89 #define         AT91C_EFC_FCMD_SLB                  (0x8)       /* (EFC) Set Lock Bit */
90 #define         AT91C_EFC_FCMD_CLB                  (0x9)       /* (EFC) Clear Lock Bit */
91 #define         AT91C_EFC_FCMD_GLB                  (0xA)       /* (EFC) Get Lock Bit */
92 #define         AT91C_EFC_FCMD_SFB                  (0xB)       /* (EFC) Set Fuse Bit */
93 #define         AT91C_EFC_FCMD_CFB                  (0xC)       /* (EFC) Clear Fuse Bit */
94 #define         AT91C_EFC_FCMD_GFB                  (0xD)       /* (EFC) Get Fuse Bit */
95 #define         AT91C_EFC_FCMD_STUI                 (0xE)       /* (EFC) Start Read Unique ID */
96 #define         AT91C_EFC_FCMD_SPUI                 (0xF)       /* (EFC) Stop Read Unique ID */
97
98 #define  offset_EFC_FMR   0
99 #define  offset_EFC_FCR   4
100 #define  offset_EFC_FSR   8
101 #define  offset_EFC_FRR   12
102
103 extern struct flash_driver at91sam3_flash;
104
105 static float _tomhz(uint32_t freq_hz)
106 {
107         float f;
108
109         f = ((float)(freq_hz)) / 1000000.0;
110         return f;
111 }
112
113 /* How the chip is configured. */
114 struct sam3_cfg {
115         uint32_t unique_id[4];
116
117         uint32_t slow_freq;
118         uint32_t rc_freq;
119         uint32_t mainosc_freq;
120         uint32_t plla_freq;
121         uint32_t mclk_freq;
122         uint32_t cpu_freq;
123         uint32_t fclk_freq;
124         uint32_t pclk0_freq;
125         uint32_t pclk1_freq;
126         uint32_t pclk2_freq;
127
128
129 #define SAM3_CHIPID_CIDR          (0x400E0740)
130         uint32_t CHIPID_CIDR;
131 #define SAM3_CHIPID_EXID          (0x400E0744)
132         uint32_t CHIPID_EXID;
133
134 #define SAM3_SUPC_CR              (0x400E1210)
135         uint32_t SUPC_CR;
136
137 #define SAM3_PMC_BASE             (0x400E0400)
138 #define SAM3_PMC_SCSR             (SAM3_PMC_BASE + 0x0008)
139         uint32_t PMC_SCSR;
140 #define SAM3_PMC_PCSR             (SAM3_PMC_BASE + 0x0018)
141         uint32_t PMC_PCSR;
142 #define SAM3_CKGR_UCKR            (SAM3_PMC_BASE + 0x001c)
143         uint32_t CKGR_UCKR;
144 #define SAM3_CKGR_MOR             (SAM3_PMC_BASE + 0x0020)
145         uint32_t CKGR_MOR;
146 #define SAM3_CKGR_MCFR            (SAM3_PMC_BASE + 0x0024)
147         uint32_t CKGR_MCFR;
148 #define SAM3_CKGR_PLLAR           (SAM3_PMC_BASE + 0x0028)
149         uint32_t CKGR_PLLAR;
150 #define SAM3_PMC_MCKR             (SAM3_PMC_BASE + 0x0030)
151         uint32_t PMC_MCKR;
152 #define SAM3_PMC_PCK0             (SAM3_PMC_BASE + 0x0040)
153         uint32_t PMC_PCK0;
154 #define SAM3_PMC_PCK1             (SAM3_PMC_BASE + 0x0044)
155         uint32_t PMC_PCK1;
156 #define SAM3_PMC_PCK2             (SAM3_PMC_BASE + 0x0048)
157         uint32_t PMC_PCK2;
158 #define SAM3_PMC_SR               (SAM3_PMC_BASE + 0x0068)
159         uint32_t PMC_SR;
160 #define SAM3_PMC_IMR              (SAM3_PMC_BASE + 0x006c)
161         uint32_t PMC_IMR;
162 #define SAM3_PMC_FSMR             (SAM3_PMC_BASE + 0x0070)
163         uint32_t PMC_FSMR;
164 #define SAM3_PMC_FSPR             (SAM3_PMC_BASE + 0x0074)
165         uint32_t PMC_FSPR;
166 };
167
168 /*
169  * The AT91SAM3N data sheet 04-Oct-2010, AT91SAM3U data sheet 22-Aug-2011
170  * and AT91SAM3S data sheet 09-Feb-2011 state that for flash writes
171  * the flash wait state (FWS) should be set to 6. It seems like that the
172  * cause of the problem is not the flash itself, but the flash write
173  * buffer. Ie the wait states have to be set before writing into the
174  * buffer.
175  * Tested and confirmed with SAM3N and SAM3U
176  */
177
178 struct sam3_bank_private {
179         int probed;
180         /* DANGER: THERE ARE DRAGONS HERE.. */
181         /* NOTE: If you add more 'ghost' pointers */
182         /* be aware that you must *manually* update */
183         /* these pointers in the function sam3_GetDetails() */
184         /* See the comment "Here there be dragons" */
185
186         /* so we can find the chip we belong to */
187         struct sam3_chip *pChip;
188         /* so we can find the orginal bank pointer */
189         struct flash_bank *pBank;
190         unsigned bank_number;
191         uint32_t controller_address;
192         uint32_t base_address;
193         uint32_t flash_wait_states;
194         bool present;
195         unsigned size_bytes;
196         unsigned nsectors;
197         unsigned sector_size;
198         unsigned page_size;
199 };
200
201 struct sam3_chip_details {
202         /* THERE ARE DRAGONS HERE.. */
203         /* note: If you add pointers here */
204         /* becareful about them as they */
205         /* may need to be updated inside */
206         /* the function: "sam3_GetDetails() */
207         /* which copy/overwrites the */
208         /* 'runtime' copy of this structure */
209         uint32_t chipid_cidr;
210         const char *name;
211
212         unsigned n_gpnvms;
213 #define SAM3_N_NVM_BITS 3
214         unsigned gpnvm[SAM3_N_NVM_BITS];
215         unsigned total_flash_size;
216         unsigned total_sram_size;
217         unsigned n_banks;
218 #define SAM3_MAX_FLASH_BANKS 2
219         /* these are "initialized" from the global const data */
220         struct sam3_bank_private bank[SAM3_MAX_FLASH_BANKS];
221 };
222
223 struct sam3_chip {
224         struct sam3_chip *next;
225         int probed;
226
227         /* this is "initialized" from the global const structure */
228         struct sam3_chip_details details;
229         struct target *target;
230         struct sam3_cfg cfg;
231 };
232
233
234 struct sam3_reg_list {
235         uint32_t address;  size_t struct_offset; const char *name;
236         void (*explain_func)(struct sam3_chip *pInfo);
237 };
238
239 static struct sam3_chip *all_sam3_chips;
240
241 static struct sam3_chip *get_current_sam3(struct command_context *cmd_ctx)
242 {
243         struct target *t;
244         static struct sam3_chip *p;
245
246         t = get_current_target(cmd_ctx);
247         if (!t) {
248                 command_print(cmd_ctx, "No current target?");
249                 return NULL;
250         }
251
252         p = all_sam3_chips;
253         if (!p) {
254                 /* this should not happen */
255                 /* the command is not registered until the chip is created? */
256                 command_print(cmd_ctx, "No SAM3 chips exist?");
257                 return NULL;
258         }
259
260         while (p) {
261                 if (p->target == t)
262                         return p;
263                 p = p->next;
264         }
265         command_print(cmd_ctx, "Cannot find SAM3 chip?");
266         return NULL;
267 }
268
269 /* these are used to *initialize* the "pChip->details" structure. */
270 static const struct sam3_chip_details all_sam3_details[] = {
271         /* Start at91sam3u* series */
272         {
273                 .chipid_cidr    = 0x28100960,
274                 .name           = "at91sam3u4e",
275                 .total_flash_size     = 256 * 1024,
276                 .total_sram_size      = 52 * 1024,
277                 .n_gpnvms       = 3,
278                 .n_banks        = 2,
279
280                 /* System boots at address 0x0 */
281                 /* gpnvm[1] = selects boot code */
282                 /*     if gpnvm[1] == 0 */
283                 /*         boot is via "SAMBA" (rom) */
284                 /*     else */
285                 /*         boot is via FLASH */
286                 /*         Selection is via gpnvm[2] */
287                 /*     endif */
288                 /*  */
289                 /* NOTE: banks 0 & 1 switch places */
290                 /*     if gpnvm[2] == 0 */
291                 /*         Bank0 is the boot rom */
292                 /*      else */
293                 /*         Bank1 is the boot rom */
294                 /*      endif */
295 /*              .bank[0] = { */
296                 {
297                         {
298                                 .probed = 0,
299                                 .pChip  = NULL,
300                                 .pBank  = NULL,
301                                 .bank_number = 0,
302                                 .base_address = FLASH_BANK0_BASE_U,
303                                 .controller_address = 0x400e0800,
304                                 .flash_wait_states = 6, /* workaround silicon bug */
305                                 .present = 1,
306                                 .size_bytes = 128 * 1024,
307                                 .nsectors   = 16,
308                                 .sector_size = 8192,
309                                 .page_size   = 256,
310                         },
311
312 /*              .bank[1] = { */
313                         {
314                                 .probed = 0,
315                                 .pChip  = NULL,
316                                 .pBank  = NULL,
317                                 .bank_number = 1,
318                                 .base_address = FLASH_BANK1_BASE_U,
319                                 .controller_address = 0x400e0a00,
320                                 .flash_wait_states = 6, /* workaround silicon bug */
321                                 .present = 1,
322                                 .size_bytes = 128 * 1024,
323                                 .nsectors   = 16,
324                                 .sector_size = 8192,
325                                 .page_size   = 256,
326                         },
327                 },
328         },
329
330         {
331                 .chipid_cidr    = 0x281a0760,
332                 .name           = "at91sam3u2e",
333                 .total_flash_size     = 128 * 1024,
334                 .total_sram_size      = 36 * 1024,
335                 .n_gpnvms       = 2,
336                 .n_banks        = 1,
337
338                 /* System boots at address 0x0 */
339                 /* gpnvm[1] = selects boot code */
340                 /*     if gpnvm[1] == 0 */
341                 /*         boot is via "SAMBA" (rom) */
342                 /*     else */
343                 /*         boot is via FLASH */
344                 /*         Selection is via gpnvm[2] */
345                 /*     endif */
346 /*              .bank[0] = { */
347                 {
348                         {
349                                 .probed = 0,
350                                 .pChip  = NULL,
351                                 .pBank  = NULL,
352                                 .bank_number = 0,
353                                 .base_address = FLASH_BANK0_BASE_U,
354                                 .controller_address = 0x400e0800,
355                                 .flash_wait_states = 6, /* workaround silicon bug */
356                                 .present = 1,
357                                 .size_bytes = 128 * 1024,
358                                 .nsectors   = 16,
359                                 .sector_size = 8192,
360                                 .page_size   = 256,
361                         },
362 /*                .bank[1] = { */
363                         {
364                                 .present = 0,
365                                 .probed = 0,
366                                 .bank_number = 1,
367                         },
368                 },
369         },
370         {
371                 .chipid_cidr    = 0x28190560,
372                 .name           = "at91sam3u1e",
373                 .total_flash_size     = 64 * 1024,
374                 .total_sram_size      = 20 * 1024,
375                 .n_gpnvms       = 2,
376                 .n_banks        = 1,
377
378                 /* System boots at address 0x0 */
379                 /* gpnvm[1] = selects boot code */
380                 /*     if gpnvm[1] == 0 */
381                 /*         boot is via "SAMBA" (rom) */
382                 /*     else */
383                 /*         boot is via FLASH */
384                 /*         Selection is via gpnvm[2] */
385                 /*     endif */
386                 /*  */
387
388 /*              .bank[0] = { */
389                 {
390                         {
391                                 .probed = 0,
392                                 .pChip  = NULL,
393                                 .pBank  = NULL,
394                                 .bank_number = 0,
395                                 .base_address = FLASH_BANK0_BASE_U,
396                                 .controller_address = 0x400e0800,
397                                 .flash_wait_states = 6, /* workaround silicon bug */
398                                 .present = 1,
399                                 .size_bytes = 64 * 1024,
400                                 .nsectors   = 8,
401                                 .sector_size = 8192,
402                                 .page_size   = 256,
403                         },
404
405 /*              .bank[1] = { */
406                         {
407                                 .present = 0,
408                                 .probed = 0,
409                                 .bank_number = 1,
410                         },
411                 },
412         },
413
414         {
415                 .chipid_cidr    = 0x28000960,
416                 .name           = "at91sam3u4c",
417                 .total_flash_size     = 256 * 1024,
418                 .total_sram_size      = 52 * 1024,
419                 .n_gpnvms       = 3,
420                 .n_banks        = 2,
421
422                 /* System boots at address 0x0 */
423                 /* gpnvm[1] = selects boot code */
424                 /*     if gpnvm[1] == 0 */
425                 /*         boot is via "SAMBA" (rom) */
426                 /*     else */
427                 /*         boot is via FLASH */
428                 /*         Selection is via gpnvm[2] */
429                 /*     endif */
430                 /*  */
431                 /* NOTE: banks 0 & 1 switch places */
432                 /*     if gpnvm[2] == 0 */
433                 /*         Bank0 is the boot rom */
434                 /*      else */
435                 /*         Bank1 is the boot rom */
436                 /*      endif */
437                 {
438                         {
439 /*              .bank[0] = { */
440                                 .probed = 0,
441                                 .pChip  = NULL,
442                                 .pBank  = NULL,
443                                 .bank_number = 0,
444                                 .base_address = FLASH_BANK0_BASE_U,
445                                 .controller_address = 0x400e0800,
446                                 .flash_wait_states = 6, /* workaround silicon bug */
447                                 .present = 1,
448                                 .size_bytes = 128 * 1024,
449                                 .nsectors   = 16,
450                                 .sector_size = 8192,
451                                 .page_size   = 256,
452                         },
453 /*              .bank[1] = { */
454                         {
455                                 .probed = 0,
456                                 .pChip  = NULL,
457                                 .pBank  = NULL,
458                                 .bank_number = 1,
459                                 .base_address = FLASH_BANK1_BASE_U,
460                                 .controller_address = 0x400e0a00,
461                                 .flash_wait_states = 6, /* workaround silicon bug */
462                                 .present = 1,
463                                 .size_bytes = 128 * 1024,
464                                 .nsectors   = 16,
465                                 .sector_size = 8192,
466                                 .page_size   = 256,
467                         },
468                 },
469         },
470
471         {
472                 .chipid_cidr    = 0x280a0760,
473                 .name           = "at91sam3u2c",
474                 .total_flash_size     = 128 * 1024,
475                 .total_sram_size      = 36 * 1024,
476                 .n_gpnvms       = 2,
477                 .n_banks        = 1,
478
479                 /* System boots at address 0x0 */
480                 /* gpnvm[1] = selects boot code */
481                 /*     if gpnvm[1] == 0 */
482                 /*         boot is via "SAMBA" (rom) */
483                 /*     else */
484                 /*         boot is via FLASH */
485                 /*         Selection is via gpnvm[2] */
486                 /*     endif */
487                 {
488 /*              .bank[0] = { */
489                         {
490                                 .probed = 0,
491                                 .pChip  = NULL,
492                                 .pBank  = NULL,
493                                 .bank_number = 0,
494                                 .base_address = FLASH_BANK0_BASE_U,
495                                 .controller_address = 0x400e0800,
496                                 .flash_wait_states = 6, /* workaround silicon bug */
497                                 .present = 1,
498                                 .size_bytes = 128 * 1024,
499                                 .nsectors   = 16,
500                                 .sector_size = 8192,
501                                 .page_size   = 256,
502                         },
503 /*              .bank[1] = { */
504                         {
505                                 .present = 0,
506                                 .probed = 0,
507                                 .bank_number = 1,
508                         },
509                 },
510         },
511         {
512                 .chipid_cidr    = 0x28090560,
513                 .name           = "at91sam3u1c",
514                 .total_flash_size     = 64 * 1024,
515                 .total_sram_size      = 20 * 1024,
516                 .n_gpnvms       = 2,
517                 .n_banks        = 1,
518
519                 /* System boots at address 0x0 */
520                 /* gpnvm[1] = selects boot code */
521                 /*     if gpnvm[1] == 0 */
522                 /*         boot is via "SAMBA" (rom) */
523                 /*     else */
524                 /*         boot is via FLASH */
525                 /*         Selection is via gpnvm[2] */
526                 /*     endif */
527                 /*  */
528
529                 {
530 /*              .bank[0] = { */
531                         {
532                                 .probed = 0,
533                                 .pChip  = NULL,
534                                 .pBank  = NULL,
535                                 .bank_number = 0,
536                                 .base_address = FLASH_BANK0_BASE_U,
537                                 .controller_address = 0x400e0800,
538                                 .flash_wait_states = 6, /* workaround silicon bug */
539                                 .present = 1,
540                                 .size_bytes = 64 * 1024,
541                                 .nsectors   = 8,
542                                 .sector_size = 8192,
543                                 .page_size   = 256,
544                         },
545 /*              .bank[1] = { */
546                         {
547                                 .present = 0,
548                                 .probed = 0,
549                                 .bank_number = 1,
550
551                         },
552                 },
553         },
554
555         /* Start at91sam3s* series */
556
557         /* Note: The preliminary at91sam3s datasheet says on page 302 */
558         /* that the flash controller is at address 0x400E0800. */
559         /* This is _not_ the case, the controller resides at address 0x400e0a0. */
560         {
561                 .chipid_cidr    = 0x28A00960,
562                 .name           = "at91sam3s4c",
563                 .total_flash_size     = 256 * 1024,
564                 .total_sram_size      = 48 * 1024,
565                 .n_gpnvms       = 2,
566                 .n_banks        = 1,
567                 {
568 /*              .bank[0] = { */
569                         {
570                                 .probed = 0,
571                                 .pChip  = NULL,
572                                 .pBank  = NULL,
573                                 .bank_number = 0,
574                                 .base_address = FLASH_BANK_BASE_S,
575                                 .controller_address = 0x400e0a00,
576                                 .flash_wait_states = 6, /* workaround silicon bug */
577                                 .present = 1,
578                                 .size_bytes = 256 * 1024,
579                                 .nsectors   = 32,
580                                 .sector_size = 8192,
581                                 .page_size   = 256,
582                         },
583 /*              .bank[1] = { */
584                         {
585                                 .present = 0,
586                                 .probed = 0,
587                                 .bank_number = 1,
588
589                         },
590                 },
591         },
592
593         {
594                 .chipid_cidr    = 0x28900960,
595                 .name           = "at91sam3s4b",
596                 .total_flash_size     = 256 * 1024,
597                 .total_sram_size      = 48 * 1024,
598                 .n_gpnvms       = 2,
599                 .n_banks        = 1,
600                 {
601 /*              .bank[0] = { */
602                         {
603                                 .probed = 0,
604                                 .pChip  = NULL,
605                                 .pBank  = NULL,
606                                 .bank_number = 0,
607                                 .base_address = FLASH_BANK_BASE_S,
608                                 .controller_address = 0x400e0a00,
609                                 .flash_wait_states = 6, /* workaround silicon bug */
610                                 .present = 1,
611                                 .size_bytes = 256 * 1024,
612                                 .nsectors   = 32,
613                                 .sector_size = 8192,
614                                 .page_size   = 256,
615                         },
616 /*              .bank[1] = { */
617                         {
618                                 .present = 0,
619                                 .probed = 0,
620                                 .bank_number = 1,
621
622                         },
623                 },
624         },
625         {
626                 .chipid_cidr    = 0x28800960,
627                 .name           = "at91sam3s4a",
628                 .total_flash_size     = 256 * 1024,
629                 .total_sram_size      = 48 * 1024,
630                 .n_gpnvms       = 2,
631                 .n_banks        = 1,
632                 {
633 /*              .bank[0] = { */
634                         {
635                                 .probed = 0,
636                                 .pChip  = NULL,
637                                 .pBank  = NULL,
638                                 .bank_number = 0,
639                                 .base_address = FLASH_BANK_BASE_S,
640                                 .controller_address = 0x400e0a00,
641                                 .flash_wait_states = 6, /* workaround silicon bug */
642                                 .present = 1,
643                                 .size_bytes = 256 * 1024,
644                                 .nsectors   = 32,
645                                 .sector_size = 8192,
646                                 .page_size   = 256,
647                         },
648 /*              .bank[1] = { */
649                         {
650                                 .present = 0,
651                                 .probed = 0,
652                                 .bank_number = 1,
653
654                         },
655                 },
656         },
657         {
658                 .chipid_cidr    = 0x28AA0760,
659                 .name           = "at91sam3s2c",
660                 .total_flash_size     = 128 * 1024,
661                 .total_sram_size      = 32 * 1024,
662                 .n_gpnvms       = 2,
663                 .n_banks        = 1,
664                 {
665 /*              .bank[0] = { */
666                         {
667                                 .probed = 0,
668                                 .pChip  = NULL,
669                                 .pBank  = NULL,
670                                 .bank_number = 0,
671                                 .base_address = FLASH_BANK_BASE_S,
672                                 .controller_address = 0x400e0a00,
673                                 .flash_wait_states = 6, /* workaround silicon bug */
674                                 .present = 1,
675                                 .size_bytes = 128 * 1024,
676                                 .nsectors   = 16,
677                                 .sector_size = 8192,
678                                 .page_size   = 256,
679                         },
680 /*              .bank[1] = { */
681                         {
682                                 .present = 0,
683                                 .probed = 0,
684                                 .bank_number = 1,
685
686                         },
687                 },
688         },
689         {
690                 .chipid_cidr    = 0x289A0760,
691                 .name           = "at91sam3s2b",
692                 .total_flash_size     = 128 * 1024,
693                 .total_sram_size      = 32 * 1024,
694                 .n_gpnvms       = 2,
695                 .n_banks        = 1,
696                 {
697 /*              .bank[0] = { */
698                         {
699                                 .probed = 0,
700                                 .pChip  = NULL,
701                                 .pBank  = NULL,
702                                 .bank_number = 0,
703                                 .base_address = FLASH_BANK_BASE_S,
704                                 .controller_address = 0x400e0a00,
705                                 .flash_wait_states = 6, /* workaround silicon bug */
706                                 .present = 1,
707                                 .size_bytes = 128 * 1024,
708                                 .nsectors   = 16,
709                                 .sector_size = 8192,
710                                 .page_size   = 256,
711                         },
712 /*              .bank[1] = { */
713                         {
714                                 .present = 0,
715                                 .probed = 0,
716                                 .bank_number = 1,
717
718                         },
719                 },
720         },
721         {
722                 .chipid_cidr    = 0x288A0760,
723                 .name           = "at91sam3s2a",
724                 .total_flash_size     = 128 * 1024,
725                 .total_sram_size      = 32 * 1024,
726                 .n_gpnvms       = 2,
727                 .n_banks        = 1,
728                 {
729 /*              .bank[0] = { */
730                         {
731                                 .probed = 0,
732                                 .pChip  = NULL,
733                                 .pBank  = NULL,
734                                 .bank_number = 0,
735                                 .base_address = FLASH_BANK_BASE_S,
736                                 .controller_address = 0x400e0a00,
737                                 .flash_wait_states = 6, /* workaround silicon bug */
738                                 .present = 1,
739                                 .size_bytes = 128 * 1024,
740                                 .nsectors   = 16,
741                                 .sector_size = 8192,
742                                 .page_size   = 256,
743                         },
744 /*              .bank[1] = { */
745                         {
746                                 .present = 0,
747                                 .probed = 0,
748                                 .bank_number = 1,
749
750                         },
751                 },
752         },
753         {
754                 .chipid_cidr    = 0x28A90560,
755                 .name           = "at91sam3s1c",
756                 .total_flash_size     = 64 * 1024,
757                 .total_sram_size      = 16 * 1024,
758                 .n_gpnvms       = 2,
759                 .n_banks        = 1,
760                 {
761 /*              .bank[0] = { */
762                         {
763                                 .probed = 0,
764                                 .pChip  = NULL,
765                                 .pBank  = NULL,
766                                 .bank_number = 0,
767                                 .base_address = FLASH_BANK_BASE_S,
768                                 .controller_address = 0x400e0a00,
769                                 .flash_wait_states = 6, /* workaround silicon bug */
770                                 .present = 1,
771                                 .size_bytes = 64 * 1024,
772                                 .nsectors   = 8,
773                                 .sector_size = 8192,
774                                 .page_size   = 256,
775                         },
776 /*              .bank[1] = { */
777                         {
778                                 .present = 0,
779                                 .probed = 0,
780                                 .bank_number = 1,
781
782                         },
783                 },
784         },
785         {
786                 .chipid_cidr    = 0x28990560,
787                 .name           = "at91sam3s1b",
788                 .total_flash_size     = 64 * 1024,
789                 .total_sram_size      = 16 * 1024,
790                 .n_gpnvms       = 2,
791                 .n_banks        = 1,
792                 {
793 /*              .bank[0] = { */
794                         {
795                                 .probed = 0,
796                                 .pChip  = NULL,
797                                 .pBank  = NULL,
798                                 .bank_number = 0,
799                                 .base_address = FLASH_BANK_BASE_S,
800                                 .controller_address = 0x400e0a00,
801                                 .flash_wait_states = 6, /* workaround silicon bug */
802                                 .present = 1,
803                                 .size_bytes = 64 * 1024,
804                                 .nsectors   = 8,
805                                 .sector_size = 8192,
806                                 .page_size   = 256,
807                         },
808 /*              .bank[1] = { */
809                         {
810                                 .present = 0,
811                                 .probed = 0,
812                                 .bank_number = 1,
813
814                         },
815                 },
816         },
817         {
818                 .chipid_cidr    = 0x28890560,
819                 .name           = "at91sam3s1a",
820                 .total_flash_size     = 64 * 1024,
821                 .total_sram_size      = 16 * 1024,
822                 .n_gpnvms       = 2,
823                 .n_banks        = 1,
824                 {
825 /*              .bank[0] = { */
826                         {
827                                 .probed = 0,
828                                 .pChip  = NULL,
829                                 .pBank  = NULL,
830                                 .bank_number = 0,
831                                 .base_address = FLASH_BANK_BASE_S,
832                                 .controller_address = 0x400e0a00,
833                                 .flash_wait_states = 6, /* workaround silicon bug */
834                                 .present = 1,
835                                 .size_bytes = 64 * 1024,
836                                 .nsectors   = 8,
837                                 .sector_size = 8192,
838                                 .page_size   = 256,
839                         },
840 /*              .bank[1] = { */
841                         {
842                                 .present = 0,
843                                 .probed = 0,
844                                 .bank_number = 1,
845
846                         },
847                 },
848         },
849
850         /* Start at91sam3n* series */
851         {
852                 .chipid_cidr    = 0x29540960,
853                 .name           = "at91sam3n4c",
854                 .total_flash_size     = 256 * 1024,
855                 .total_sram_size      = 24 * 1024,
856                 .n_gpnvms       = 3,
857                 .n_banks        = 1,
858
859                 /* System boots at address 0x0 */
860                 /* gpnvm[1] = selects boot code */
861                 /*     if gpnvm[1] == 0 */
862                 /*         boot is via "SAMBA" (rom) */
863                 /*     else */
864                 /*         boot is via FLASH */
865                 /*         Selection is via gpnvm[2] */
866                 /*     endif */
867                 /*  */
868                 /* NOTE: banks 0 & 1 switch places */
869                 /*     if gpnvm[2] == 0 */
870                 /*         Bank0 is the boot rom */
871                 /*      else */
872                 /*         Bank1 is the boot rom */
873                 /*      endif */
874 /*              .bank[0] = { */
875                 {
876                         {
877                                 .probed = 0,
878                                 .pChip  = NULL,
879                                 .pBank  = NULL,
880                                 .bank_number = 0,
881                                 .base_address = FLASH_BANK_BASE_N,
882                                 .controller_address = 0x400e0A00,
883                                 .flash_wait_states = 6, /* workaround silicon bug */
884                                 .present = 1,
885                                 .size_bytes = 256 * 1024,
886                                 .nsectors   = 16,
887                                 .sector_size = 16384,
888                                 .page_size   = 256,
889                         },
890
891 /*              .bank[1] = { */
892                         {
893                                 .present = 0,
894                                 .probed = 0,
895                                 .bank_number = 1,
896                         },
897                 },
898         },
899
900         {
901                 .chipid_cidr    = 0x29440960,
902                 .name           = "at91sam3n4b",
903                 .total_flash_size     = 256 * 1024,
904                 .total_sram_size      = 24 * 1024,
905                 .n_gpnvms       = 3,
906                 .n_banks        = 1,
907
908                 /* System boots at address 0x0 */
909                 /* gpnvm[1] = selects boot code */
910                 /*     if gpnvm[1] == 0 */
911                 /*         boot is via "SAMBA" (rom) */
912                 /*     else */
913                 /*         boot is via FLASH */
914                 /*         Selection is via gpnvm[2] */
915                 /*     endif */
916                 /*  */
917                 /* NOTE: banks 0 & 1 switch places */
918                 /*     if gpnvm[2] == 0 */
919                 /*         Bank0 is the boot rom */
920                 /*      else */
921                 /*         Bank1 is the boot rom */
922                 /*      endif */
923 /*              .bank[0] = { */
924                 {
925                         {
926                                 .probed = 0,
927                                 .pChip  = NULL,
928                                 .pBank  = NULL,
929                                 .bank_number = 0,
930                                 .base_address = FLASH_BANK_BASE_N,
931                                 .controller_address = 0x400e0A00,
932                                 .flash_wait_states = 6, /* workaround silicon bug */
933                                 .present = 1,
934                                 .size_bytes = 256 * 1024,
935                                 .nsectors   = 16,
936                                 .sector_size = 16384,
937                                 .page_size   = 256,
938                         },
939
940 /*              .bank[1] = { */
941                         {
942                                 .present = 0,
943                                 .probed = 0,
944                                 .bank_number = 1,
945                         },
946                 },
947         },
948
949         {
950                 .chipid_cidr    = 0x29340960,
951                 .name           = "at91sam3n4a",
952                 .total_flash_size     = 256 * 1024,
953                 .total_sram_size      = 24 * 1024,
954                 .n_gpnvms       = 3,
955                 .n_banks        = 1,
956
957                 /* System boots at address 0x0 */
958                 /* gpnvm[1] = selects boot code */
959                 /*     if gpnvm[1] == 0 */
960                 /*         boot is via "SAMBA" (rom) */
961                 /*     else */
962                 /*         boot is via FLASH */
963                 /*         Selection is via gpnvm[2] */
964                 /*     endif */
965                 /*  */
966                 /* NOTE: banks 0 & 1 switch places */
967                 /*     if gpnvm[2] == 0 */
968                 /*         Bank0 is the boot rom */
969                 /*      else */
970                 /*         Bank1 is the boot rom */
971                 /*      endif */
972 /*              .bank[0] = { */
973                 {
974                         {
975                                 .probed = 0,
976                                 .pChip  = NULL,
977                                 .pBank  = NULL,
978                                 .bank_number = 0,
979                                 .base_address = FLASH_BANK_BASE_N,
980                                 .controller_address = 0x400e0A00,
981                                 .flash_wait_states = 6, /* workaround silicon bug */
982                                 .present = 1,
983                                 .size_bytes = 256 * 1024,
984                                 .nsectors   = 16,
985                                 .sector_size = 16384,
986                                 .page_size   = 256,
987                         },
988
989 /*              .bank[1] = { */
990                         {
991                                 .present = 0,
992                                 .probed = 0,
993                                 .bank_number = 1,
994                         },
995                 },
996         },
997
998         {
999                 .chipid_cidr    = 0x29590760,
1000                 .name           = "at91sam3n2c",
1001                 .total_flash_size     = 128 * 1024,
1002                 .total_sram_size      = 16 * 1024,
1003                 .n_gpnvms       = 3,
1004                 .n_banks        = 1,
1005
1006                 /* System boots at address 0x0 */
1007                 /* gpnvm[1] = selects boot code */
1008                 /*     if gpnvm[1] == 0 */
1009                 /*         boot is via "SAMBA" (rom) */
1010                 /*     else */
1011                 /*         boot is via FLASH */
1012                 /*         Selection is via gpnvm[2] */
1013                 /*     endif */
1014                 /*  */
1015                 /* NOTE: banks 0 & 1 switch places */
1016                 /*     if gpnvm[2] == 0 */
1017                 /*         Bank0 is the boot rom */
1018                 /*      else */
1019                 /*         Bank1 is the boot rom */
1020                 /*      endif */
1021 /*              .bank[0] = { */
1022                 {
1023                         {
1024                                 .probed = 0,
1025                                 .pChip  = NULL,
1026                                 .pBank  = NULL,
1027                                 .bank_number = 0,
1028                                 .base_address = FLASH_BANK_BASE_N,
1029                                 .controller_address = 0x400e0A00,
1030                                 .flash_wait_states = 6, /* workaround silicon bug */
1031                                 .present = 1,
1032                                 .size_bytes = 128 * 1024,
1033                                 .nsectors   = 8,
1034                                 .sector_size = 16384,
1035                                 .page_size   = 256,
1036                         },
1037
1038 /*              .bank[1] = { */
1039                         {
1040                                 .present = 0,
1041                                 .probed = 0,
1042                                 .bank_number = 1,
1043                         },
1044                 },
1045         },
1046
1047         {
1048                 .chipid_cidr    = 0x29490760,
1049                 .name           = "at91sam3n2b",
1050                 .total_flash_size     = 128 * 1024,
1051                 .total_sram_size      = 16 * 1024,
1052                 .n_gpnvms       = 3,
1053                 .n_banks        = 1,
1054
1055                 /* System boots at address 0x0 */
1056                 /* gpnvm[1] = selects boot code */
1057                 /*     if gpnvm[1] == 0 */
1058                 /*         boot is via "SAMBA" (rom) */
1059                 /*     else */
1060                 /*         boot is via FLASH */
1061                 /*         Selection is via gpnvm[2] */
1062                 /*     endif */
1063                 /*  */
1064                 /* NOTE: banks 0 & 1 switch places */
1065                 /*     if gpnvm[2] == 0 */
1066                 /*         Bank0 is the boot rom */
1067                 /*      else */
1068                 /*         Bank1 is the boot rom */
1069                 /*      endif */
1070 /*              .bank[0] = { */
1071                 {
1072                         {
1073                                 .probed = 0,
1074                                 .pChip  = NULL,
1075                                 .pBank  = NULL,
1076                                 .bank_number = 0,
1077                                 .base_address = FLASH_BANK_BASE_N,
1078                                 .controller_address = 0x400e0A00,
1079                                 .flash_wait_states = 6, /* workaround silicon bug */
1080                                 .present = 1,
1081                                 .size_bytes = 128 * 1024,
1082                                 .nsectors   = 8,
1083                                 .sector_size = 16384,
1084                                 .page_size   = 256,
1085                         },
1086
1087 /*              .bank[1] = { */
1088                         {
1089                                 .present = 0,
1090                                 .probed = 0,
1091                                 .bank_number = 1,
1092                         },
1093                 },
1094         },
1095
1096         {
1097                 .chipid_cidr    = 0x29390760,
1098                 .name           = "at91sam3n2a",
1099                 .total_flash_size     = 128 * 1024,
1100                 .total_sram_size      = 16 * 1024,
1101                 .n_gpnvms       = 3,
1102                 .n_banks        = 1,
1103
1104                 /* System boots at address 0x0 */
1105                 /* gpnvm[1] = selects boot code */
1106                 /*     if gpnvm[1] == 0 */
1107                 /*         boot is via "SAMBA" (rom) */
1108                 /*     else */
1109                 /*         boot is via FLASH */
1110                 /*         Selection is via gpnvm[2] */
1111                 /*     endif */
1112                 /*  */
1113                 /* NOTE: banks 0 & 1 switch places */
1114                 /*     if gpnvm[2] == 0 */
1115                 /*         Bank0 is the boot rom */
1116                 /*      else */
1117                 /*         Bank1 is the boot rom */
1118                 /*      endif */
1119 /*              .bank[0] = { */
1120                 {
1121                         {
1122                                 .probed = 0,
1123                                 .pChip  = NULL,
1124                                 .pBank  = NULL,
1125                                 .bank_number = 0,
1126                                 .base_address = FLASH_BANK_BASE_N,
1127                                 .controller_address = 0x400e0A00,
1128                                 .flash_wait_states = 6, /* workaround silicon bug */
1129                                 .present = 1,
1130                                 .size_bytes = 128 * 1024,
1131                                 .nsectors   = 8,
1132                                 .sector_size = 16384,
1133                                 .page_size   = 256,
1134                         },
1135
1136 /*              .bank[1] = { */
1137                         {
1138                                 .present = 0,
1139                                 .probed = 0,
1140                                 .bank_number = 1,
1141                         },
1142                 },
1143         },
1144
1145         {
1146                 .chipid_cidr    = 0x29580560,
1147                 .name           = "at91sam3n1c",
1148                 .total_flash_size     = 64 * 1024,
1149                 .total_sram_size      = 8 * 1024,
1150                 .n_gpnvms       = 3,
1151                 .n_banks        = 1,
1152
1153                 /* System boots at address 0x0 */
1154                 /* gpnvm[1] = selects boot code */
1155                 /*     if gpnvm[1] == 0 */
1156                 /*         boot is via "SAMBA" (rom) */
1157                 /*     else */
1158                 /*         boot is via FLASH */
1159                 /*         Selection is via gpnvm[2] */
1160                 /*     endif */
1161                 /*  */
1162                 /* NOTE: banks 0 & 1 switch places */
1163                 /*     if gpnvm[2] == 0 */
1164                 /*         Bank0 is the boot rom */
1165                 /*      else */
1166                 /*         Bank1 is the boot rom */
1167                 /*      endif */
1168 /*              .bank[0] = { */
1169                 {
1170                         {
1171                                 .probed = 0,
1172                                 .pChip  = NULL,
1173                                 .pBank  = NULL,
1174                                 .bank_number = 0,
1175                                 .base_address = FLASH_BANK_BASE_N,
1176                                 .controller_address = 0x400e0A00,
1177                                 .flash_wait_states = 6, /* workaround silicon bug */
1178                                 .present = 1,
1179                                 .size_bytes = 64 * 1024,
1180                                 .nsectors   = 4,
1181                                 .sector_size = 16384,
1182                                 .page_size   = 256,
1183                         },
1184
1185 /*              .bank[1] = { */
1186                         {
1187                                 .present = 0,
1188                                 .probed = 0,
1189                                 .bank_number = 1,
1190                         },
1191                 },
1192         },
1193
1194         {
1195                 .chipid_cidr    = 0x29480560,
1196                 .name           = "at91sam3n1b",
1197                 .total_flash_size     = 64 * 1024,
1198                 .total_sram_size      = 8 * 1024,
1199                 .n_gpnvms       = 3,
1200                 .n_banks        = 1,
1201
1202                 /* System boots at address 0x0 */
1203                 /* gpnvm[1] = selects boot code */
1204                 /*     if gpnvm[1] == 0 */
1205                 /*         boot is via "SAMBA" (rom) */
1206                 /*     else */
1207                 /*         boot is via FLASH */
1208                 /*         Selection is via gpnvm[2] */
1209                 /*     endif */
1210                 /*  */
1211                 /* NOTE: banks 0 & 1 switch places */
1212                 /*     if gpnvm[2] == 0 */
1213                 /*         Bank0 is the boot rom */
1214                 /*      else */
1215                 /*         Bank1 is the boot rom */
1216                 /*      endif */
1217 /*              .bank[0] = { */
1218                 {
1219                         {
1220                                 .probed = 0,
1221                                 .pChip  = NULL,
1222                                 .pBank  = NULL,
1223                                 .bank_number = 0,
1224                                 .base_address = FLASH_BANK_BASE_N,
1225                                 .controller_address = 0x400e0A00,
1226                                 .flash_wait_states = 6, /* workaround silicon bug */
1227                                 .present = 1,
1228                                 .size_bytes = 64 * 1024,
1229                                 .nsectors   = 4,
1230                                 .sector_size = 16384,
1231                                 .page_size   = 256,
1232                         },
1233
1234 /*              .bank[1] = { */
1235                         {
1236                                 .present = 0,
1237                                 .probed = 0,
1238                                 .bank_number = 1,
1239                         },
1240                 },
1241         },
1242
1243         {
1244                 .chipid_cidr    = 0x29380560,
1245                 .name           = "at91sam3n1a",
1246                 .total_flash_size     = 64 * 1024,
1247                 .total_sram_size      = 8 * 1024,
1248                 .n_gpnvms       = 3,
1249                 .n_banks        = 1,
1250
1251                 /* System boots at address 0x0 */
1252                 /* gpnvm[1] = selects boot code */
1253                 /*     if gpnvm[1] == 0 */
1254                 /*         boot is via "SAMBA" (rom) */
1255                 /*     else */
1256                 /*         boot is via FLASH */
1257                 /*         Selection is via gpnvm[2] */
1258                 /*     endif */
1259                 /*  */
1260                 /* NOTE: banks 0 & 1 switch places */
1261                 /*     if gpnvm[2] == 0 */
1262                 /*         Bank0 is the boot rom */
1263                 /*      else */
1264                 /*         Bank1 is the boot rom */
1265                 /*      endif */
1266 /*              .bank[0] = { */
1267                 {
1268                         {
1269                                 .probed = 0,
1270                                 .pChip  = NULL,
1271                                 .pBank  = NULL,
1272                                 .bank_number = 0,
1273                                 .base_address = FLASH_BANK_BASE_N,
1274                                 .controller_address = 0x400e0A00,
1275                                 .flash_wait_states = 6, /* workaround silicon bug */
1276                                 .present = 1,
1277                                 .size_bytes = 64 * 1024,
1278                                 .nsectors   = 4,
1279                                 .sector_size = 16384,
1280                                 .page_size   = 256,
1281                         },
1282
1283 /*              .bank[1] = { */
1284                         {
1285                                 .present = 0,
1286                                 .probed = 0,
1287                                 .bank_number = 1,
1288                         },
1289                 },
1290         },
1291
1292         /* terminate */
1293         {
1294                 .chipid_cidr    = 0,
1295                 .name                   = NULL,
1296         }
1297 };
1298
1299 /* Globals above */
1300 /***********************************************************************
1301  **********************************************************************
1302  **********************************************************************
1303  **********************************************************************
1304  **********************************************************************
1305  **********************************************************************/
1306 /* *ATMEL* style code - from the SAM3 driver code */
1307
1308 /**
1309  * Get the current status of the EEFC and
1310  * the value of some status bits (LOCKE, PROGE).
1311  * @param pPrivate - info about the bank
1312  * @param v        - result goes here
1313  */
1314 static int EFC_GetStatus(struct sam3_bank_private *pPrivate, uint32_t *v)
1315 {
1316         int r;
1317         r = target_read_u32(pPrivate->pChip->target,
1318                         pPrivate->controller_address + offset_EFC_FSR,
1319                         v);
1320         LOG_DEBUG("Status: 0x%08x (lockerror: %d, cmderror: %d, ready: %d)",
1321                 (unsigned int)(*v),
1322                 ((unsigned int)((*v >> 2) & 1)),
1323                 ((unsigned int)((*v >> 1) & 1)),
1324                 ((unsigned int)((*v >> 0) & 1)));
1325
1326         return r;
1327 }
1328
1329 /**
1330  * Get the result of the last executed command.
1331  * @param pPrivate - info about the bank
1332  * @param v        - result goes here
1333  */
1334 static int EFC_GetResult(struct sam3_bank_private *pPrivate, uint32_t *v)
1335 {
1336         int r;
1337         uint32_t rv;
1338         r = target_read_u32(pPrivate->pChip->target,
1339                         pPrivate->controller_address + offset_EFC_FRR,
1340                         &rv);
1341         if (v)
1342                 *v = rv;
1343         LOG_DEBUG("Result: 0x%08x", ((unsigned int)(rv)));
1344         return r;
1345 }
1346
1347 static int EFC_StartCommand(struct sam3_bank_private *pPrivate,
1348         unsigned command, unsigned argument)
1349 {
1350         uint32_t n, v;
1351         int r;
1352         int retry;
1353
1354         retry = 0;
1355 do_retry:
1356
1357         /* Check command & argument */
1358         switch (command) {
1359
1360                 case AT91C_EFC_FCMD_WP:
1361                 case AT91C_EFC_FCMD_WPL:
1362                 case AT91C_EFC_FCMD_EWP:
1363                 case AT91C_EFC_FCMD_EWPL:
1364                 /* case AT91C_EFC_FCMD_EPL: */
1365                 /* case AT91C_EFC_FCMD_EPA: */
1366                 case AT91C_EFC_FCMD_SLB:
1367                 case AT91C_EFC_FCMD_CLB:
1368                         n = (pPrivate->size_bytes / pPrivate->page_size);
1369                         if (argument >= n)
1370                                 LOG_ERROR("*BUG*: Embedded flash has only %u pages", (unsigned)(n));
1371                         break;
1372
1373                 case AT91C_EFC_FCMD_SFB:
1374                 case AT91C_EFC_FCMD_CFB:
1375                         if (argument >= pPrivate->pChip->details.n_gpnvms) {
1376                                 LOG_ERROR("*BUG*: Embedded flash has only %d GPNVMs",
1377                                                 pPrivate->pChip->details.n_gpnvms);
1378                         }
1379                         break;
1380
1381                 case AT91C_EFC_FCMD_GETD:
1382                 case AT91C_EFC_FCMD_EA:
1383                 case AT91C_EFC_FCMD_GLB:
1384                 case AT91C_EFC_FCMD_GFB:
1385                 case AT91C_EFC_FCMD_STUI:
1386                 case AT91C_EFC_FCMD_SPUI:
1387                         if (argument != 0)
1388                                 LOG_ERROR("Argument is meaningless for cmd: %d", command);
1389                         break;
1390                 default:
1391                         LOG_ERROR("Unknown command %d", command);
1392                         break;
1393         }
1394
1395         if (command == AT91C_EFC_FCMD_SPUI) {
1396                 /* this is a very special situation. */
1397                 /* Situation (1) - error/retry - see below */
1398                 /*      And we are being called recursively */
1399                 /* Situation (2) - normal, finished reading unique id */
1400         } else {
1401                 /* it should be "ready" */
1402                 EFC_GetStatus(pPrivate, &v);
1403                 if (v & 1) {
1404                         /* then it is ready */
1405                         /* we go on */
1406                 } else {
1407                         if (retry) {
1408                                 /* we have done this before */
1409                                 /* the controller is not responding. */
1410                                 LOG_ERROR("flash controller(%d) is not ready! Error",
1411                                         pPrivate->bank_number);
1412                                 return ERROR_FAIL;
1413                         } else {
1414                                 retry++;
1415                                 LOG_ERROR("Flash controller(%d) is not ready, attempting reset",
1416                                         pPrivate->bank_number);
1417                                 /* we do that by issuing the *STOP* command */
1418                                 EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0);
1419                                 /* above is recursive, and further recursion is blocked by */
1420                                 /* if (command == AT91C_EFC_FCMD_SPUI) above */
1421                                 goto do_retry;
1422                         }
1423                 }
1424         }
1425
1426         v = (0x5A << 24) | (argument << 8) | command;
1427         LOG_DEBUG("Command: 0x%08x", ((unsigned int)(v)));
1428         r = target_write_u32(pPrivate->pBank->target,
1429                         pPrivate->controller_address + offset_EFC_FCR, v);
1430         if (r != ERROR_OK)
1431                 LOG_DEBUG("Error Write failed");
1432         return r;
1433 }
1434
1435 /**
1436  * Performs the given command and wait until its completion (or an error).
1437  * @param pPrivate - info about the bank
1438  * @param command  - Command to perform.
1439  * @param argument - Optional command argument.
1440  * @param status   - put command status bits here
1441  */
1442 static int EFC_PerformCommand(struct sam3_bank_private *pPrivate,
1443         unsigned command,
1444         unsigned argument,
1445         uint32_t *status)
1446 {
1447
1448         int r;
1449         uint32_t v;
1450         long long ms_now, ms_end;
1451
1452         /* default */
1453         if (status)
1454                 *status = 0;
1455
1456         r = EFC_StartCommand(pPrivate, command, argument);
1457         if (r != ERROR_OK)
1458                 return r;
1459
1460         ms_end = 500 + timeval_ms();
1461
1462         do {
1463                 r = EFC_GetStatus(pPrivate, &v);
1464                 if (r != ERROR_OK)
1465                         return r;
1466                 ms_now = timeval_ms();
1467                 if (ms_now > ms_end) {
1468                         /* error */
1469                         LOG_ERROR("Command timeout");
1470                         return ERROR_FAIL;
1471                 }
1472         } while ((v & 1) == 0);
1473
1474         /* error bits.. */
1475         if (status)
1476                 *status = (v & 0x6);
1477         return ERROR_OK;
1478
1479 }
1480
1481 /**
1482  * Read the unique ID.
1483  * @param pPrivate - info about the bank
1484  * The unique ID is stored in the 'pPrivate' structure.
1485  */
1486 static int FLASHD_ReadUniqueID(struct sam3_bank_private *pPrivate)
1487 {
1488         int r;
1489         uint32_t v;
1490         int x;
1491         /* assume 0 */
1492         pPrivate->pChip->cfg.unique_id[0] = 0;
1493         pPrivate->pChip->cfg.unique_id[1] = 0;
1494         pPrivate->pChip->cfg.unique_id[2] = 0;
1495         pPrivate->pChip->cfg.unique_id[3] = 0;
1496
1497         LOG_DEBUG("Begin");
1498         r = EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_STUI, 0);
1499         if (r < 0)
1500                 return r;
1501
1502         for (x = 0; x < 4; x++) {
1503                 r = target_read_u32(pPrivate->pChip->target,
1504                                 pPrivate->pBank->base + (x * 4),
1505                                 &v);
1506                 if (r < 0)
1507                         return r;
1508                 pPrivate->pChip->cfg.unique_id[x] = v;
1509         }
1510
1511         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0, NULL);
1512         LOG_DEBUG("End: R=%d, id = 0x%08x, 0x%08x, 0x%08x, 0x%08x",
1513                 r,
1514                 (unsigned int)(pPrivate->pChip->cfg.unique_id[0]),
1515                 (unsigned int)(pPrivate->pChip->cfg.unique_id[1]),
1516                 (unsigned int)(pPrivate->pChip->cfg.unique_id[2]),
1517                 (unsigned int)(pPrivate->pChip->cfg.unique_id[3]));
1518         return r;
1519
1520 }
1521
1522 /**
1523  * Erases the entire flash.
1524  * @param pPrivate - the info about the bank.
1525  */
1526 static int FLASHD_EraseEntireBank(struct sam3_bank_private *pPrivate)
1527 {
1528         LOG_DEBUG("Here");
1529         return EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_EA, 0, NULL);
1530 }
1531
1532 /**
1533  * Gets current GPNVM state.
1534  * @param pPrivate - info about the bank.
1535  * @param gpnvm    -  GPNVM bit index.
1536  * @param puthere  - result stored here.
1537  */
1538 /* ------------------------------------------------------------------------------ */
1539 static int FLASHD_GetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm, unsigned *puthere)
1540 {
1541         uint32_t v;
1542         int r;
1543
1544         LOG_DEBUG("Here");
1545         if (pPrivate->bank_number != 0) {
1546                 LOG_ERROR("GPNVM only works with Bank0");
1547                 return ERROR_FAIL;
1548         }
1549
1550         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
1551                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
1552                         gpnvm, pPrivate->pChip->details.n_gpnvms);
1553                 return ERROR_FAIL;
1554         }
1555
1556         /* Get GPNVMs status */
1557         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GFB, 0, NULL);
1558         if (r != ERROR_OK) {
1559                 LOG_ERROR("Failed");
1560                 return r;
1561         }
1562
1563         r = EFC_GetResult(pPrivate, &v);
1564
1565         if (puthere) {
1566                 /* Check if GPNVM is set */
1567                 /* get the bit and make it a 0/1 */
1568                 *puthere = (v >> gpnvm) & 1;
1569         }
1570
1571         return r;
1572 }
1573
1574 /**
1575  * Clears the selected GPNVM bit.
1576  * @param pPrivate info about the bank
1577  * @param gpnvm GPNVM index.
1578  * @returns 0 if successful; otherwise returns an error code.
1579  */
1580 static int FLASHD_ClrGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm)
1581 {
1582         int r;
1583         unsigned v;
1584
1585         LOG_DEBUG("Here");
1586         if (pPrivate->bank_number != 0) {
1587                 LOG_ERROR("GPNVM only works with Bank0");
1588                 return ERROR_FAIL;
1589         }
1590
1591         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
1592                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
1593                         gpnvm, pPrivate->pChip->details.n_gpnvms);
1594                 return ERROR_FAIL;
1595         }
1596
1597         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
1598         if (r != ERROR_OK) {
1599                 LOG_DEBUG("Failed: %d", r);
1600                 return r;
1601         }
1602         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CFB, gpnvm, NULL);
1603         LOG_DEBUG("End: %d", r);
1604         return r;
1605 }
1606
1607 /**
1608  * Sets the selected GPNVM bit.
1609  * @param pPrivate info about the bank
1610  * @param gpnvm GPNVM index.
1611  */
1612 static int FLASHD_SetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm)
1613 {
1614         int r;
1615         unsigned v;
1616
1617         if (pPrivate->bank_number != 0) {
1618                 LOG_ERROR("GPNVM only works with Bank0");
1619                 return ERROR_FAIL;
1620         }
1621
1622         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
1623                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
1624                         gpnvm, pPrivate->pChip->details.n_gpnvms);
1625                 return ERROR_FAIL;
1626         }
1627
1628         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
1629         if (r != ERROR_OK)
1630                 return r;
1631         if (v) {
1632                 /* already set */
1633                 r = ERROR_OK;
1634         } else {
1635                 /* set it */
1636                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SFB, gpnvm, NULL);
1637         }
1638         return r;
1639 }
1640
1641 /**
1642  * Returns a bit field (at most 64) of locked regions within a page.
1643  * @param pPrivate info about the bank
1644  * @param v where to store locked bits
1645  */
1646 static int FLASHD_GetLockBits(struct sam3_bank_private *pPrivate, uint32_t *v)
1647 {
1648         int r;
1649         LOG_DEBUG("Here");
1650         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GLB, 0, NULL);
1651         if (r == ERROR_OK)
1652                 r = EFC_GetResult(pPrivate, v);
1653         LOG_DEBUG("End: %d", r);
1654         return r;
1655 }
1656
1657 /**
1658  * Unlocks all the regions in the given address range.
1659  * @param pPrivate info about the bank
1660  * @param start_sector first sector to unlock
1661  * @param end_sector last (inclusive) to unlock
1662  */
1663
1664 static int FLASHD_Unlock(struct sam3_bank_private *pPrivate,
1665         unsigned start_sector,
1666         unsigned end_sector)
1667 {
1668         int r;
1669         uint32_t status;
1670         uint32_t pg;
1671         uint32_t pages_per_sector;
1672
1673         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
1674
1675         /* Unlock all pages */
1676         while (start_sector <= end_sector) {
1677                 pg = start_sector * pages_per_sector;
1678
1679                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CLB, pg, &status);
1680                 if (r != ERROR_OK)
1681                         return r;
1682                 start_sector++;
1683         }
1684
1685         return ERROR_OK;
1686 }
1687
1688 /**
1689  * Locks regions
1690  * @param pPrivate - info about the bank
1691  * @param start_sector - first sector to lock
1692  * @param end_sector   - last sector (inclusive) to lock
1693  */
1694 static int FLASHD_Lock(struct sam3_bank_private *pPrivate,
1695         unsigned start_sector,
1696         unsigned end_sector)
1697 {
1698         uint32_t status;
1699         uint32_t pg;
1700         uint32_t pages_per_sector;
1701         int r;
1702
1703         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
1704
1705         /* Lock all pages */
1706         while (start_sector <= end_sector) {
1707                 pg = start_sector * pages_per_sector;
1708
1709                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SLB, pg, &status);
1710                 if (r != ERROR_OK)
1711                         return r;
1712                 start_sector++;
1713         }
1714         return ERROR_OK;
1715 }
1716
1717 /****** END SAM3 CODE ********/
1718
1719 /* begin helpful debug code */
1720 /* print the fieldname, the field value, in dec & hex, and return field value */
1721 static uint32_t sam3_reg_fieldname(struct sam3_chip *pChip,
1722         const char *regname,
1723         uint32_t value,
1724         unsigned shift,
1725         unsigned width)
1726 {
1727         uint32_t v;
1728         int hwidth, dwidth;
1729
1730
1731         /* extract the field */
1732         v = value >> shift;
1733         v = v & ((1 << width)-1);
1734         if (width <= 16) {
1735                 hwidth = 4;
1736                 dwidth = 5;
1737         } else {
1738                 hwidth = 8;
1739                 dwidth = 12;
1740         }
1741
1742         /* show the basics */
1743         LOG_USER_N("\t%*s: %*d [0x%0*x] ",
1744                 REG_NAME_WIDTH, regname,
1745                 dwidth, v,
1746                 hwidth, v);
1747         return v;
1748 }
1749
1750 static const char _unknown[] = "unknown";
1751 static const char *const eproc_names[] = {
1752         _unknown,                                       /* 0 */
1753         "arm946es",                                     /* 1 */
1754         "arm7tdmi",                                     /* 2 */
1755         "cortex-m3",                            /* 3 */
1756         "arm920t",                                      /* 4 */
1757         "arm926ejs",                            /* 5 */
1758         _unknown,                                       /* 6 */
1759         _unknown,                                       /* 7 */
1760         _unknown,                                       /* 8 */
1761         _unknown,                                       /* 9 */
1762         _unknown,                                       /* 10 */
1763         _unknown,                                       /* 11 */
1764         _unknown,                                       /* 12 */
1765         _unknown,                                       /* 13 */
1766         _unknown,                                       /* 14 */
1767         _unknown,                                       /* 15 */
1768 };
1769
1770 #define nvpsize2 nvpsize                /* these two tables are identical */
1771 static const char *const nvpsize[] = {
1772         "none",                                         /*  0 */
1773         "8K bytes",                                     /*  1 */
1774         "16K bytes",                            /*  2 */
1775         "32K bytes",                            /*  3 */
1776         _unknown,                                       /*  4 */
1777         "64K bytes",                            /*  5 */
1778         _unknown,                                       /*  6 */
1779         "128K bytes",                           /*  7 */
1780         _unknown,                                       /*  8 */
1781         "256K bytes",                           /*  9 */
1782         "512K bytes",                           /* 10 */
1783         _unknown,                                       /* 11 */
1784         "1024K bytes",                          /* 12 */
1785         _unknown,                                       /* 13 */
1786         "2048K bytes",                          /* 14 */
1787         _unknown,                                       /* 15 */
1788 };
1789
1790 static const char *const sramsize[] = {
1791         "48K Bytes",                            /*  0 */
1792         "1K Bytes",                                     /*  1 */
1793         "2K Bytes",                                     /*  2 */
1794         "6K Bytes",                                     /*  3 */
1795         "112K Bytes",                           /*  4 */
1796         "4K Bytes",                                     /*  5 */
1797         "80K Bytes",                            /*  6 */
1798         "160K Bytes",                           /*  7 */
1799         "8K Bytes",                                     /*  8 */
1800         "16K Bytes",                            /*  9 */
1801         "32K Bytes",                            /* 10 */
1802         "64K Bytes",                            /* 11 */
1803         "128K Bytes",                           /* 12 */
1804         "256K Bytes",                           /* 13 */
1805         "96K Bytes",                            /* 14 */
1806         "512K Bytes",                           /* 15 */
1807
1808 };
1809
1810 static const struct archnames { unsigned value; const char *name; } archnames[] = {
1811         { 0x19,  "AT91SAM9xx Series"                                            },
1812         { 0x29,  "AT91SAM9XExx Series"                                          },
1813         { 0x34,  "AT91x34 Series"                                                       },
1814         { 0x37,  "CAP7 Series"                                                          },
1815         { 0x39,  "CAP9 Series"                                                          },
1816         { 0x3B,  "CAP11 Series"                                                         },
1817         { 0x40,  "AT91x40 Series"                                                       },
1818         { 0x42,  "AT91x42 Series"                                                       },
1819         { 0x55,  "AT91x55 Series"                                                       },
1820         { 0x60,  "AT91SAM7Axx Series"                                           },
1821         { 0x61,  "AT91SAM7AQxx Series"                                          },
1822         { 0x63,  "AT91x63 Series"                                                       },
1823         { 0x70,  "AT91SAM7Sxx Series"                                           },
1824         { 0x71,  "AT91SAM7XCxx Series"                                          },
1825         { 0x72,  "AT91SAM7SExx Series"                                          },
1826         { 0x73,  "AT91SAM7Lxx Series"                                           },
1827         { 0x75,  "AT91SAM7Xxx Series"                                           },
1828         { 0x76,  "AT91SAM7SLxx Series"                                          },
1829         { 0x80,  "ATSAM3UxC Series (100-pin version)"           },
1830         { 0x81,  "ATSAM3UxE Series (144-pin version)"           },
1831         { 0x83,  "ATSAM3AxC Series (100-pin version)"           },
1832         { 0x84,  "ATSAM3XxC Series (100-pin version)"           },
1833         { 0x85,  "ATSAM3XxE Series (144-pin version)"           },
1834         { 0x86,  "ATSAM3XxG Series (208/217-pin version)"       },
1835         { 0x88,  "ATSAM3SxA Series (48-pin version)"            },
1836         { 0x89,  "ATSAM3SxB Series (64-pin version)"            },
1837         { 0x8A,  "ATSAM3SxC Series (100-pin version)"           },
1838         { 0x92,  "AT91x92 Series"                                                       },
1839         { 0xF0,  "AT75Cxx Series"                                                       },
1840         { -1, NULL },
1841 };
1842
1843 static const char *const nvptype[] = {
1844         "rom",  /* 0 */
1845         "romless or onchip flash",      /* 1 */
1846         "embedded flash memory",/* 2 */
1847         "rom(nvpsiz) + embedded flash (nvpsiz2)",       /* 3 */
1848         "sram emulating flash", /* 4 */
1849         _unknown,       /* 5 */
1850         _unknown,       /* 6 */
1851         _unknown,       /* 7 */
1852 };
1853
1854 static const char *_yes_or_no(uint32_t v)
1855 {
1856         if (v)
1857                 return "YES";
1858         else
1859                 return "NO";
1860 }
1861
1862 static const char *const _rc_freq[] = {
1863         "4 MHz", "8 MHz", "12 MHz", "reserved"
1864 };
1865
1866 static void sam3_explain_ckgr_mor(struct sam3_chip *pChip)
1867 {
1868         uint32_t v;
1869         uint32_t rcen;
1870
1871         v = sam3_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
1872         LOG_USER("(main xtal enabled: %s)", _yes_or_no(v));
1873         v = sam3_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
1874         LOG_USER("(main osc bypass: %s)", _yes_or_no(v));
1875         rcen = sam3_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 3, 1);
1876         LOG_USER("(onchip RC-OSC enabled: %s)", _yes_or_no(rcen));
1877         v = sam3_reg_fieldname(pChip, "MOSCRCF", pChip->cfg.CKGR_MOR, 4, 3);
1878         LOG_USER("(onchip RC-OSC freq: %s)", _rc_freq[v]);
1879
1880         pChip->cfg.rc_freq = 0;
1881         if (rcen) {
1882                 switch (v) {
1883                         default:
1884                                 pChip->cfg.rc_freq = 0;
1885                                 break;
1886                         case 0:
1887                                 pChip->cfg.rc_freq = 4 * 1000 * 1000;
1888                                 break;
1889                         case 1:
1890                                 pChip->cfg.rc_freq = 8 * 1000 * 1000;
1891                                 break;
1892                         case 2:
1893                                 pChip->cfg.rc_freq = 12 * 1000 * 1000;
1894                                 break;
1895                 }
1896         }
1897
1898         v = sam3_reg_fieldname(pChip, "MOSCXTST", pChip->cfg.CKGR_MOR, 8, 8);
1899         LOG_USER("(startup clks, time= %f uSecs)",
1900                 ((float)(v * 1000000)) / ((float)(pChip->cfg.slow_freq)));
1901         v = sam3_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
1902         LOG_USER("(mainosc source: %s)",
1903                 v ? "external xtal" : "internal RC");
1904
1905         v = sam3_reg_fieldname(pChip, "CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
1906         LOG_USER("(clock failure enabled: %s)",
1907                 _yes_or_no(v));
1908 }
1909
1910 static void sam3_explain_chipid_cidr(struct sam3_chip *pChip)
1911 {
1912         int x;
1913         uint32_t v;
1914         const char *cp;
1915
1916         sam3_reg_fieldname(pChip, "Version", pChip->cfg.CHIPID_CIDR, 0, 5);
1917         LOG_USER_N("\n");
1918
1919         v = sam3_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
1920         LOG_USER("%s", eproc_names[v]);
1921
1922         v = sam3_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
1923         LOG_USER("%s", nvpsize[v]);
1924
1925         v = sam3_reg_fieldname(pChip, "NVPSIZE2", pChip->cfg.CHIPID_CIDR, 12, 4);
1926         LOG_USER("%s", nvpsize2[v]);
1927
1928         v = sam3_reg_fieldname(pChip, "SRAMSIZE", pChip->cfg.CHIPID_CIDR, 16, 4);
1929         LOG_USER("%s", sramsize[v]);
1930
1931         v = sam3_reg_fieldname(pChip, "ARCH", pChip->cfg.CHIPID_CIDR, 20, 8);
1932         cp = _unknown;
1933         for (x = 0; archnames[x].name; x++) {
1934                 if (v == archnames[x].value) {
1935                         cp = archnames[x].name;
1936                         break;
1937                 }
1938         }
1939
1940         LOG_USER("%s", cp);
1941
1942         v = sam3_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
1943         LOG_USER("%s", nvptype[v]);
1944
1945         v = sam3_reg_fieldname(pChip, "EXTID", pChip->cfg.CHIPID_CIDR, 31, 1);
1946         LOG_USER("(exists: %s)", _yes_or_no(v));
1947 }
1948
1949 static void sam3_explain_ckgr_mcfr(struct sam3_chip *pChip)
1950 {
1951         uint32_t v;
1952
1953         v = sam3_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
1954         LOG_USER("(main ready: %s)", _yes_or_no(v));
1955
1956         v = sam3_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
1957
1958         v = (v * pChip->cfg.slow_freq) / 16;
1959         pChip->cfg.mainosc_freq = v;
1960
1961         LOG_USER("(%3.03f Mhz (%d.%03dkhz slowclk)",
1962                 _tomhz(v),
1963                 pChip->cfg.slow_freq / 1000,
1964                 pChip->cfg.slow_freq % 1000);
1965 }
1966
1967 static void sam3_explain_ckgr_plla(struct sam3_chip *pChip)
1968 {
1969         uint32_t mula, diva;
1970
1971         diva = sam3_reg_fieldname(pChip, "DIVA", pChip->cfg.CKGR_PLLAR, 0, 8);
1972         LOG_USER_N("\n");
1973         mula = sam3_reg_fieldname(pChip, "MULA", pChip->cfg.CKGR_PLLAR, 16, 11);
1974         LOG_USER_N("\n");
1975         pChip->cfg.plla_freq = 0;
1976         if (mula == 0)
1977                 LOG_USER("\tPLLA Freq: (Disabled,mula = 0)");
1978         else if (diva == 0)
1979                 LOG_USER("\tPLLA Freq: (Disabled,diva = 0)");
1980         else if (diva == 1) {
1981                 pChip->cfg.plla_freq = (pChip->cfg.mainosc_freq * (mula + 1));
1982                 LOG_USER("\tPLLA Freq: %3.03f MHz",
1983                         _tomhz(pChip->cfg.plla_freq));
1984         }
1985 }
1986
1987 static void sam3_explain_mckr(struct sam3_chip *pChip)
1988 {
1989         uint32_t css, pres, fin = 0;
1990         int pdiv = 0;
1991         const char *cp = NULL;
1992
1993         css = sam3_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
1994         switch (css & 3) {
1995                 case 0:
1996                         fin = pChip->cfg.slow_freq;
1997                         cp = "slowclk";
1998                         break;
1999                 case 1:
2000                         fin = pChip->cfg.mainosc_freq;
2001                         cp  = "mainosc";
2002                         break;
2003                 case 2:
2004                         fin = pChip->cfg.plla_freq;
2005                         cp  = "plla";
2006                         break;
2007                 case 3:
2008                         if (pChip->cfg.CKGR_UCKR & (1 << 16)) {
2009                                 fin = 480 * 1000 * 1000;
2010                                 cp = "upll";
2011                         } else {
2012                                 fin = 0;
2013                                 cp  = "upll (*ERROR* UPLL is disabled)";
2014                         }
2015                         break;
2016                 default:
2017                         assert(0);
2018                         break;
2019         }
2020
2021         LOG_USER("%s (%3.03f Mhz)",
2022                 cp,
2023                 _tomhz(fin));
2024         pres = sam3_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
2025         switch (pres & 0x07) {
2026                 case 0:
2027                         pdiv = 1;
2028                         cp = "selected clock";
2029                         break;
2030                 case 1:
2031                         pdiv = 2;
2032                         cp = "clock/2";
2033                         break;
2034                 case 2:
2035                         pdiv = 4;
2036                         cp = "clock/4";
2037                         break;
2038                 case 3:
2039                         pdiv = 8;
2040                         cp = "clock/8";
2041                         break;
2042                 case 4:
2043                         pdiv = 16;
2044                         cp = "clock/16";
2045                         break;
2046                 case 5:
2047                         pdiv = 32;
2048                         cp = "clock/32";
2049                         break;
2050                 case 6:
2051                         pdiv = 64;
2052                         cp = "clock/64";
2053                         break;
2054                 case 7:
2055                         pdiv = 6;
2056                         cp = "clock/6";
2057                         break;
2058                 default:
2059                         assert(0);
2060                         break;
2061         }
2062         LOG_USER("(%s)", cp);
2063         fin = fin / pdiv;
2064         /* sam3 has a *SINGLE* clock - */
2065         /* other at91 series parts have divisors for these. */
2066         pChip->cfg.cpu_freq = fin;
2067         pChip->cfg.mclk_freq = fin;
2068         pChip->cfg.fclk_freq = fin;
2069         LOG_USER("\t\tResult CPU Freq: %3.03f",
2070                 _tomhz(fin));
2071 }
2072
2073 #if 0
2074 static struct sam3_chip *target2sam3(struct target *pTarget)
2075 {
2076         struct sam3_chip *pChip;
2077
2078         if (pTarget == NULL)
2079                 return NULL;
2080
2081         pChip = all_sam3_chips;
2082         while (pChip) {
2083                 if (pChip->target == pTarget)
2084                         break;  /* return below */
2085                 else
2086                         pChip = pChip->next;
2087         }
2088         return pChip;
2089 }
2090 #endif
2091
2092 static uint32_t *sam3_get_reg_ptr(struct sam3_cfg *pCfg, const struct sam3_reg_list *pList)
2093 {
2094         /* this function exists to help */
2095         /* keep funky offsetof() errors */
2096         /* and casting from causing bugs */
2097
2098         /* By using prototypes - we can detect what would */
2099         /* be casting errors. */
2100
2101         return (uint32_t *)(void *)(((char *)(pCfg)) + pList->struct_offset);
2102 }
2103
2104
2105 #define SAM3_ENTRY(NAME, FUNC)  { .address = SAM3_ ## NAME, .struct_offset = offsetof( \
2106                                                   struct sam3_cfg, \
2107                                                   NAME), # NAME, FUNC }
2108 static const struct sam3_reg_list sam3_all_regs[] = {
2109         SAM3_ENTRY(CKGR_MOR, sam3_explain_ckgr_mor),
2110         SAM3_ENTRY(CKGR_MCFR, sam3_explain_ckgr_mcfr),
2111         SAM3_ENTRY(CKGR_PLLAR, sam3_explain_ckgr_plla),
2112         SAM3_ENTRY(CKGR_UCKR, NULL),
2113         SAM3_ENTRY(PMC_FSMR, NULL),
2114         SAM3_ENTRY(PMC_FSPR, NULL),
2115         SAM3_ENTRY(PMC_IMR, NULL),
2116         SAM3_ENTRY(PMC_MCKR, sam3_explain_mckr),
2117         SAM3_ENTRY(PMC_PCK0, NULL),
2118         SAM3_ENTRY(PMC_PCK1, NULL),
2119         SAM3_ENTRY(PMC_PCK2, NULL),
2120         SAM3_ENTRY(PMC_PCSR, NULL),
2121         SAM3_ENTRY(PMC_SCSR, NULL),
2122         SAM3_ENTRY(PMC_SR, NULL),
2123         SAM3_ENTRY(CHIPID_CIDR, sam3_explain_chipid_cidr),
2124         SAM3_ENTRY(CHIPID_EXID, NULL),
2125         SAM3_ENTRY(SUPC_CR, NULL),
2126
2127         /* TERMINATE THE LIST */
2128         { .name = NULL }
2129 };
2130 #undef SAM3_ENTRY
2131
2132 static struct sam3_bank_private *get_sam3_bank_private(struct flash_bank *bank)
2133 {
2134         return (struct sam3_bank_private *)(bank->driver_priv);
2135 }
2136
2137 /**
2138  * Given a pointer to where it goes in the structure,
2139  * determine the register name, address from the all registers table.
2140  */
2141 static const struct sam3_reg_list *sam3_GetReg(struct sam3_chip *pChip, uint32_t *goes_here)
2142 {
2143         const struct sam3_reg_list *pReg;
2144
2145         pReg = &(sam3_all_regs[0]);
2146         while (pReg->name) {
2147                 uint32_t *pPossible;
2148
2149                 /* calculate where this one go.. */
2150                 /* it is "possibly" this register. */
2151
2152                 pPossible = ((uint32_t *)(void *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
2153
2154                 /* well? Is it this register */
2155                 if (pPossible == goes_here) {
2156                         /* Jump for joy! */
2157                         return pReg;
2158                 }
2159
2160                 /* next... */
2161                 pReg++;
2162         }
2163         /* This is *TOTAL*PANIC* - we are totally screwed. */
2164         LOG_ERROR("INVALID SAM3 REGISTER");
2165         return NULL;
2166 }
2167
2168 static int sam3_ReadThisReg(struct sam3_chip *pChip, uint32_t *goes_here)
2169 {
2170         const struct sam3_reg_list *pReg;
2171         int r;
2172
2173         pReg = sam3_GetReg(pChip, goes_here);
2174         if (!pReg)
2175                 return ERROR_FAIL;
2176
2177         r = target_read_u32(pChip->target, pReg->address, goes_here);
2178         if (r != ERROR_OK) {
2179                 LOG_ERROR("Cannot read SAM3 register: %s @ 0x%08x, Err: %d",
2180                         pReg->name, (unsigned)(pReg->address), r);
2181         }
2182         return r;
2183 }
2184
2185 static int sam3_ReadAllRegs(struct sam3_chip *pChip)
2186 {
2187         int r;
2188         const struct sam3_reg_list *pReg;
2189
2190         pReg = &(sam3_all_regs[0]);
2191         while (pReg->name) {
2192                 r = sam3_ReadThisReg(pChip,
2193                                 sam3_get_reg_ptr(&(pChip->cfg), pReg));
2194                 if (r != ERROR_OK) {
2195                         LOG_ERROR("Cannot read SAM3 registere: %s @ 0x%08x, Error: %d",
2196                                 pReg->name, ((unsigned)(pReg->address)), r);
2197                         return r;
2198                 }
2199
2200                 pReg++;
2201         }
2202
2203         return ERROR_OK;
2204 }
2205
2206 static int sam3_GetInfo(struct sam3_chip *pChip)
2207 {
2208         const struct sam3_reg_list *pReg;
2209         uint32_t regval;
2210
2211         pReg = &(sam3_all_regs[0]);
2212         while (pReg->name) {
2213                 /* display all regs */
2214                 LOG_DEBUG("Start: %s", pReg->name);
2215                 regval = *sam3_get_reg_ptr(&(pChip->cfg), pReg);
2216                 LOG_USER("%*s: [0x%08x] -> 0x%08x",
2217                         REG_NAME_WIDTH,
2218                         pReg->name,
2219                         pReg->address,
2220                         regval);
2221                 if (pReg->explain_func)
2222                         (*(pReg->explain_func))(pChip);
2223                 LOG_DEBUG("End: %s", pReg->name);
2224                 pReg++;
2225         }
2226         LOG_USER("   rc-osc: %3.03f MHz", _tomhz(pChip->cfg.rc_freq));
2227         LOG_USER("  mainosc: %3.03f MHz", _tomhz(pChip->cfg.mainosc_freq));
2228         LOG_USER("     plla: %3.03f MHz", _tomhz(pChip->cfg.plla_freq));
2229         LOG_USER(" cpu-freq: %3.03f MHz", _tomhz(pChip->cfg.cpu_freq));
2230         LOG_USER("mclk-freq: %3.03f MHz", _tomhz(pChip->cfg.mclk_freq));
2231
2232         LOG_USER(" UniqueId: 0x%08x 0x%08x 0x%08x 0x%08x",
2233                 pChip->cfg.unique_id[0],
2234                 pChip->cfg.unique_id[1],
2235                 pChip->cfg.unique_id[2],
2236                 pChip->cfg.unique_id[3]);
2237
2238         return ERROR_OK;
2239 }
2240
2241 static int sam3_erase_check(struct flash_bank *bank)
2242 {
2243         int x;
2244
2245         LOG_DEBUG("Here");
2246         if (bank->target->state != TARGET_HALTED) {
2247                 LOG_ERROR("Target not halted");
2248                 return ERROR_TARGET_NOT_HALTED;
2249         }
2250         if (0 == bank->num_sectors) {
2251                 LOG_ERROR("Target: not supported/not probed");
2252                 return ERROR_FAIL;
2253         }
2254
2255         LOG_INFO("sam3 - supports auto-erase, erase_check ignored");
2256         for (x = 0; x < bank->num_sectors; x++)
2257                 bank->sectors[x].is_erased = 1;
2258
2259         LOG_DEBUG("Done");
2260         return ERROR_OK;
2261 }
2262
2263 static int sam3_protect_check(struct flash_bank *bank)
2264 {
2265         int r;
2266         uint32_t v = 0;
2267         unsigned x;
2268         struct sam3_bank_private *pPrivate;
2269
2270         LOG_DEBUG("Begin");
2271         if (bank->target->state != TARGET_HALTED) {
2272                 LOG_ERROR("Target not halted");
2273                 return ERROR_TARGET_NOT_HALTED;
2274         }
2275
2276         pPrivate = get_sam3_bank_private(bank);
2277         if (!pPrivate) {
2278                 LOG_ERROR("no private for this bank?");
2279                 return ERROR_FAIL;
2280         }
2281         if (!(pPrivate->probed))
2282                 return ERROR_FLASH_BANK_NOT_PROBED;
2283
2284         r = FLASHD_GetLockBits(pPrivate, &v);
2285         if (r != ERROR_OK) {
2286                 LOG_DEBUG("Failed: %d", r);
2287                 return r;
2288         }
2289
2290         for (x = 0; x < pPrivate->nsectors; x++)
2291                 bank->sectors[x].is_protected = (!!(v & (1 << x)));
2292         LOG_DEBUG("Done");
2293         return ERROR_OK;
2294 }
2295
2296 FLASH_BANK_COMMAND_HANDLER(sam3_flash_bank_command)
2297 {
2298         struct sam3_chip *pChip;
2299
2300         pChip = all_sam3_chips;
2301
2302         /* is this an existing chip? */
2303         while (pChip) {
2304                 if (pChip->target == bank->target)
2305                         break;
2306                 pChip = pChip->next;
2307         }
2308
2309         if (!pChip) {
2310                 /* this is a *NEW* chip */
2311                 pChip = calloc(1, sizeof(struct sam3_chip));
2312                 if (!pChip) {
2313                         LOG_ERROR("NO RAM!");
2314                         return ERROR_FAIL;
2315                 }
2316                 pChip->target = bank->target;
2317                 /* insert at head */
2318                 pChip->next = all_sam3_chips;
2319                 all_sam3_chips = pChip;
2320                 pChip->target = bank->target;
2321                 /* assumption is this runs at 32khz */
2322                 pChip->cfg.slow_freq = 32768;
2323                 pChip->probed = 0;
2324         }
2325
2326         switch (bank->base) {
2327                 default:
2328                         LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x or 0x%08x "
2329                         "[at91sam3u series] or 0x%08x [at91sam3s series] or "
2330                         "0x%08x [at91sam3n series])",
2331                         ((unsigned int)(bank->base)),
2332                         ((unsigned int)(FLASH_BANK0_BASE_U)),
2333                         ((unsigned int)(FLASH_BANK1_BASE_U)),
2334                         ((unsigned int)(FLASH_BANK_BASE_S)),
2335                         ((unsigned int)(FLASH_BANK_BASE_N)));
2336                         return ERROR_FAIL;
2337                         break;
2338
2339                 /* at91sam3u series */
2340                 case FLASH_BANK0_BASE_U:
2341                         bank->driver_priv = &(pChip->details.bank[0]);
2342                         bank->bank_number = 0;
2343                         pChip->details.bank[0].pChip = pChip;
2344                         pChip->details.bank[0].pBank = bank;
2345                         break;
2346                 case FLASH_BANK1_BASE_U:
2347                         bank->driver_priv = &(pChip->details.bank[1]);
2348                         bank->bank_number = 1;
2349                         pChip->details.bank[1].pChip = pChip;
2350                         pChip->details.bank[1].pBank = bank;
2351                         break;
2352
2353                 /* at91sam3s and at91sam3n series */
2354                 case FLASH_BANK_BASE_S:
2355                         bank->driver_priv = &(pChip->details.bank[0]);
2356                         bank->bank_number = 0;
2357                         pChip->details.bank[0].pChip = pChip;
2358                         pChip->details.bank[0].pBank = bank;
2359                         break;
2360         }
2361
2362         /* we initialize after probing. */
2363         return ERROR_OK;
2364 }
2365
2366 static int sam3_GetDetails(struct sam3_bank_private *pPrivate)
2367 {
2368         const struct sam3_chip_details *pDetails;
2369         struct sam3_chip *pChip;
2370         struct flash_bank *saved_banks[SAM3_MAX_FLASH_BANKS];
2371         unsigned x;
2372
2373         LOG_DEBUG("Begin");
2374         pDetails = all_sam3_details;
2375         while (pDetails->name) {
2376                 /* Compare cidr without version bits */
2377                 if (pDetails->chipid_cidr == (pPrivate->pChip->cfg.CHIPID_CIDR & 0xFFFFFFE0))
2378                         break;
2379                 else
2380                         pDetails++;
2381         }
2382         if (pDetails->name == NULL) {
2383                 LOG_ERROR("SAM3 ChipID 0x%08x not found in table (perhaps you can this chip?)",
2384                         (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
2385                 /* Help the victim, print details about the chip */
2386                 LOG_INFO("SAM3 CHIPID_CIDR: 0x%08x decodes as follows",
2387                         pPrivate->pChip->cfg.CHIPID_CIDR);
2388                 sam3_explain_chipid_cidr(pPrivate->pChip);
2389                 return ERROR_FAIL;
2390         }
2391
2392         /* DANGER: THERE ARE DRAGONS HERE */
2393
2394         /* get our pChip - it is going */
2395         /* to be over-written shortly */
2396         pChip = pPrivate->pChip;
2397
2398         /* Note that, in reality: */
2399         /*  */
2400         /*     pPrivate = &(pChip->details.bank[0]) */
2401         /* or  pPrivate = &(pChip->details.bank[1]) */
2402         /*  */
2403
2404         /* save the "bank" pointers */
2405         for (x = 0; x < SAM3_MAX_FLASH_BANKS; x++)
2406                 saved_banks[x] = pChip->details.bank[x].pBank;
2407
2408         /* Overwrite the "details" structure. */
2409         memcpy(&(pPrivate->pChip->details),
2410                 pDetails,
2411                 sizeof(pPrivate->pChip->details));
2412
2413         /* now fix the ghosted pointers */
2414         for (x = 0; x < SAM3_MAX_FLASH_BANKS; x++) {
2415                 pChip->details.bank[x].pChip = pChip;
2416                 pChip->details.bank[x].pBank = saved_banks[x];
2417         }
2418
2419         /* update the *BANK*SIZE* */
2420
2421         LOG_DEBUG("End");
2422         return ERROR_OK;
2423 }
2424
2425 static int _sam3_probe(struct flash_bank *bank, int noise)
2426 {
2427         unsigned x;
2428         int r;
2429         struct sam3_bank_private *pPrivate;
2430
2431
2432         LOG_DEBUG("Begin: Bank: %d, Noise: %d", bank->bank_number, noise);
2433         if (bank->target->state != TARGET_HALTED) {
2434                 LOG_ERROR("Target not halted");
2435                 return ERROR_TARGET_NOT_HALTED;
2436         }
2437
2438         pPrivate = get_sam3_bank_private(bank);
2439         if (!pPrivate) {
2440                 LOG_ERROR("Invalid/unknown bank number");
2441                 return ERROR_FAIL;
2442         }
2443
2444         r = sam3_ReadAllRegs(pPrivate->pChip);
2445         if (r != ERROR_OK)
2446                 return r;
2447
2448         LOG_DEBUG("Here");
2449         if (pPrivate->pChip->probed)
2450                 r = sam3_GetInfo(pPrivate->pChip);
2451         else
2452                 r = sam3_GetDetails(pPrivate);
2453         if (r != ERROR_OK)
2454                 return r;
2455
2456         /* update the flash bank size */
2457         for (x = 0; x < SAM3_MAX_FLASH_BANKS; x++) {
2458                 if (bank->base == pPrivate->pChip->details.bank[x].base_address) {
2459                         bank->size = pPrivate->pChip->details.bank[x].size_bytes;
2460                         break;
2461                 }
2462         }
2463
2464         if (bank->sectors == NULL) {
2465                 bank->sectors = calloc(pPrivate->nsectors, (sizeof((bank->sectors)[0])));
2466                 if (bank->sectors == NULL) {
2467                         LOG_ERROR("No memory!");
2468                         return ERROR_FAIL;
2469                 }
2470                 bank->num_sectors = pPrivate->nsectors;
2471
2472                 for (x = 0; ((int)(x)) < bank->num_sectors; x++) {
2473                         bank->sectors[x].size = pPrivate->sector_size;
2474                         bank->sectors[x].offset = x * (pPrivate->sector_size);
2475                         /* mark as unknown */
2476                         bank->sectors[x].is_erased = -1;
2477                         bank->sectors[x].is_protected = -1;
2478                 }
2479         }
2480
2481         pPrivate->probed = 1;
2482
2483         r = sam3_protect_check(bank);
2484         if (r != ERROR_OK)
2485                 return r;
2486
2487         LOG_DEBUG("Bank = %d, nbanks = %d",
2488                 pPrivate->bank_number, pPrivate->pChip->details.n_banks);
2489         if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
2490                 /* read unique id, */
2491                 /* it appears to be associated with the *last* flash bank. */
2492                 FLASHD_ReadUniqueID(pPrivate);
2493         }
2494
2495         return r;
2496 }
2497
2498 static int sam3_probe(struct flash_bank *bank)
2499 {
2500         return _sam3_probe(bank, 1);
2501 }
2502
2503 static int sam3_auto_probe(struct flash_bank *bank)
2504 {
2505         return _sam3_probe(bank, 0);
2506 }
2507
2508 static int sam3_erase(struct flash_bank *bank, int first, int last)
2509 {
2510         struct sam3_bank_private *pPrivate;
2511         int r;
2512
2513         LOG_DEBUG("Here");
2514         if (bank->target->state != TARGET_HALTED) {
2515                 LOG_ERROR("Target not halted");
2516                 return ERROR_TARGET_NOT_HALTED;
2517         }
2518
2519         r = sam3_auto_probe(bank);
2520         if (r != ERROR_OK) {
2521                 LOG_DEBUG("Here,r=%d", r);
2522                 return r;
2523         }
2524
2525         pPrivate = get_sam3_bank_private(bank);
2526         if (!(pPrivate->probed))
2527                 return ERROR_FLASH_BANK_NOT_PROBED;
2528
2529         if ((first == 0) && ((last + 1) == ((int)(pPrivate->nsectors)))) {
2530                 /* whole chip */
2531                 LOG_DEBUG("Here");
2532                 return FLASHD_EraseEntireBank(pPrivate);
2533         }
2534         LOG_INFO("sam3 auto-erases while programing (request ignored)");
2535         return ERROR_OK;
2536 }
2537
2538 static int sam3_protect(struct flash_bank *bank, int set, int first, int last)
2539 {
2540         struct sam3_bank_private *pPrivate;
2541         int r;
2542
2543         LOG_DEBUG("Here");
2544         if (bank->target->state != TARGET_HALTED) {
2545                 LOG_ERROR("Target not halted");
2546                 return ERROR_TARGET_NOT_HALTED;
2547         }
2548
2549         pPrivate = get_sam3_bank_private(bank);
2550         if (!(pPrivate->probed))
2551                 return ERROR_FLASH_BANK_NOT_PROBED;
2552
2553         if (set)
2554                 r = FLASHD_Lock(pPrivate, (unsigned)(first), (unsigned)(last));
2555         else
2556                 r = FLASHD_Unlock(pPrivate, (unsigned)(first), (unsigned)(last));
2557         LOG_DEBUG("End: r=%d", r);
2558
2559         return r;
2560
2561 }
2562
2563 static int sam3_info(struct flash_bank *bank, char *buf, int buf_size)
2564 {
2565         if (bank->target->state != TARGET_HALTED) {
2566                 LOG_ERROR("Target not halted");
2567                 return ERROR_TARGET_NOT_HALTED;
2568         }
2569         buf[0] = 0;
2570         return ERROR_OK;
2571 }
2572
2573 static int sam3_page_read(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
2574 {
2575         uint32_t adr;
2576         int r;
2577
2578         adr = pagenum * pPrivate->page_size;
2579         adr += adr + pPrivate->base_address;
2580
2581         r = target_read_memory(pPrivate->pChip->target,
2582                         adr,
2583                         4,                                      /* THIS*MUST*BE* in 32bit values */
2584                         pPrivate->page_size / 4,
2585                         buf);
2586         if (r != ERROR_OK)
2587                 LOG_ERROR("SAM3: Flash program failed to read page phys address: 0x%08x",
2588                         (unsigned int)(adr));
2589         return r;
2590 }
2591
2592 /* The code below is basically this: */
2593 /* compiled with */
2594 /* arm-none-eabi-gcc -mthumb -mcpu = cortex-m3 -O9 -S ./foobar.c -o foobar.s */
2595 /*  */
2596 /* Only the *CPU* can write to the flash buffer. */
2597 /* the DAP cannot... so - we download this 28byte thing */
2598 /* Run the algorithm - (below) */
2599 /* to program the device */
2600 /*  */
2601 /* ======================================== */
2602 /* #include <stdint.h> */
2603 /*  */
2604 /* struct foo { */
2605 /*   uint32_t *dst; */
2606 /*   const uint32_t *src; */
2607 /*   int   n; */
2608 /*   volatile uint32_t *base; */
2609 /*   uint32_t   cmd; */
2610 /* }; */
2611 /*  */
2612 /*  */
2613 /* uint32_t sam3_function(struct foo *p) */
2614 /* { */
2615 /*   volatile uint32_t *v; */
2616 /*   uint32_t *d; */
2617 /*   const uint32_t *s; */
2618 /*   int   n; */
2619 /*   uint32_t r; */
2620 /*  */
2621 /*   d = p->dst; */
2622 /*   s = p->src; */
2623 /*   n = p->n; */
2624 /*  */
2625 /*   do { */
2626 /*     *d++ = *s++; */
2627 /*   } while (--n) */
2628 /*     ; */
2629 /*  */
2630 /*   v = p->base; */
2631 /*  */
2632 /*   v[ 1 ] = p->cmd; */
2633 /*   do { */
2634 /*     r = v[8/4]; */
2635 /*   } while (!(r&1)) */
2636 /*     ; */
2637 /*   return r; */
2638 /* } */
2639 /* ======================================== */
2640
2641 static const uint8_t
2642         sam3_page_write_opcodes[] = {
2643         /*  24 0000 0446                mov     r4, r0 */
2644         0x04, 0x46,
2645         /*  25 0002 6168                ldr     r1, [r4, #4] */
2646         0x61, 0x68,
2647         /*  26 0004 0068                ldr     r0, [r0, #0] */
2648         0x00, 0x68,
2649         /*  27 0006 A268                ldr     r2, [r4, #8] */
2650         0xa2, 0x68,
2651         /*  28                          @ lr needed for prologue */
2652         /*  29                  .L2: */
2653         /*  30 0008 51F8043B            ldr     r3, [r1], #4 */
2654         0x51, 0xf8, 0x04, 0x3b,
2655         /*  31 000c 12F1FF32            adds    r2, r2, #-1 */
2656         0x12, 0xf1, 0xff, 0x32,
2657         /*  32 0010 40F8043B            str     r3, [r0], #4 */
2658         0x40, 0xf8, 0x04, 0x3b,
2659         /*  33 0014 F8D1                bne     .L2 */
2660         0xf8, 0xd1,
2661         /*  34 0016 E268                ldr     r2, [r4, #12] */
2662         0xe2, 0x68,
2663         /*  35 0018 2369                ldr     r3, [r4, #16] */
2664         0x23, 0x69,
2665         /*  36 001a 5360                str     r3, [r2, #4] */
2666         0x53, 0x60,
2667         /*  37 001c 0832                adds    r2, r2, #8 */
2668         0x08, 0x32,
2669         /*  38                  .L4: */
2670         /*  39 001e 1068                ldr     r0, [r2, #0] */
2671         0x10, 0x68,
2672         /*  40 0020 10F0010F            tst     r0, #1 */
2673         0x10, 0xf0, 0x01, 0x0f,
2674         /*  41 0024 FBD0                beq     .L4 */
2675         0xfb, 0xd0,
2676         0x00, 0xBE                              /* bkpt #0 */
2677 };
2678
2679 static int sam3_page_write(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
2680 {
2681         uint32_t adr;
2682         uint32_t status;
2683         uint32_t fmr;   /* EEFC Flash Mode Register */
2684         int r;
2685
2686         adr = pagenum * pPrivate->page_size;
2687         adr += (adr + pPrivate->base_address);
2688
2689         /* Get flash mode register value */
2690         r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address, &fmr);
2691         if (r != ERROR_OK)
2692                 LOG_DEBUG("Error Read failed: read flash mode register");
2693
2694         /* Clear flash wait state field */
2695         fmr &= 0xfffff0ff;
2696
2697         /* set FWS (flash wait states) field in the FMR (flash mode register) */
2698         fmr |= (pPrivate->flash_wait_states << 8);
2699
2700         LOG_DEBUG("Flash Mode: 0x%08x", ((unsigned int)(fmr)));
2701         r = target_write_u32(pPrivate->pBank->target, pPrivate->controller_address, fmr);
2702         if (r != ERROR_OK)
2703                 LOG_DEBUG("Error Write failed: set flash mode register");
2704
2705         LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
2706         r = target_write_memory(pPrivate->pChip->target,
2707                         adr,
2708                         4,                                      /* THIS*MUST*BE* in 32bit values */
2709                         pPrivate->page_size / 4,
2710                         buf);
2711         if (r != ERROR_OK) {
2712                 LOG_ERROR("SAM3: Failed to write (buffer) page at phys address 0x%08x",
2713                         (unsigned int)(adr));
2714                 return r;
2715         }
2716
2717         r = EFC_PerformCommand(pPrivate,
2718                         /* send Erase & Write Page */
2719                         AT91C_EFC_FCMD_EWP,
2720                         pagenum,
2721                         &status);
2722
2723         if (r != ERROR_OK)
2724                 LOG_ERROR("SAM3: Error performing Erase & Write page @ phys address 0x%08x",
2725                         (unsigned int)(adr));
2726         if (status & (1 << 2)) {
2727                 LOG_ERROR("SAM3: Page @ Phys address 0x%08x is locked", (unsigned int)(adr));
2728                 return ERROR_FAIL;
2729         }
2730         if (status & (1 << 1)) {
2731                 LOG_ERROR("SAM3: Flash Command error @phys address 0x%08x", (unsigned int)(adr));
2732                 return ERROR_FAIL;
2733         }
2734         return ERROR_OK;
2735 }
2736
2737 static int sam3_write(struct flash_bank *bank,
2738         uint8_t *buffer,
2739         uint32_t offset,
2740         uint32_t count)
2741 {
2742         int n;
2743         unsigned page_cur;
2744         unsigned page_end;
2745         int r;
2746         unsigned page_offset;
2747         struct sam3_bank_private *pPrivate;
2748         uint8_t *pagebuffer;
2749
2750         /* incase we bail further below, set this to null */
2751         pagebuffer = NULL;
2752
2753         /* ignore dumb requests */
2754         if (count == 0) {
2755                 r = ERROR_OK;
2756                 goto done;
2757         }
2758
2759         if (bank->target->state != TARGET_HALTED) {
2760                 LOG_ERROR("Target not halted");
2761                 r = ERROR_TARGET_NOT_HALTED;
2762                 goto done;
2763         }
2764
2765         pPrivate = get_sam3_bank_private(bank);
2766         if (!(pPrivate->probed)) {
2767                 r = ERROR_FLASH_BANK_NOT_PROBED;
2768                 goto done;
2769         }
2770
2771         if ((offset + count) > pPrivate->size_bytes) {
2772                 LOG_ERROR("Flash write error - past end of bank");
2773                 LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
2774                         (unsigned int)(offset),
2775                         (unsigned int)(count),
2776                         (unsigned int)(pPrivate->size_bytes));
2777                 r = ERROR_FAIL;
2778                 goto done;
2779         }
2780
2781         pagebuffer = malloc(pPrivate->page_size);
2782         if (!pagebuffer) {
2783                 LOG_ERROR("No memory for %d Byte page buffer", (int)(pPrivate->page_size));
2784                 r = ERROR_FAIL;
2785                 goto done;
2786         }
2787
2788         /* what page do we start & end in? */
2789         page_cur = offset / pPrivate->page_size;
2790         page_end = (offset + count - 1) / pPrivate->page_size;
2791
2792         LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
2793         LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
2794
2795         /* Special case: all one page */
2796         /*  */
2797         /* Otherwise: */
2798         /*    (1) non-aligned start */
2799         /*    (2) body pages */
2800         /*    (3) non-aligned end. */
2801
2802         /* Handle special case - all one page. */
2803         if (page_cur == page_end) {
2804                 LOG_DEBUG("Special case, all in one page");
2805                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2806                 if (r != ERROR_OK)
2807                         goto done;
2808
2809                 page_offset = (offset & (pPrivate->page_size-1));
2810                 memcpy(pagebuffer + page_offset,
2811                         buffer,
2812                         count);
2813
2814                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2815                 if (r != ERROR_OK)
2816                         goto done;
2817                 r = ERROR_OK;
2818                 goto done;
2819         }
2820
2821         /* non-aligned start */
2822         page_offset = offset & (pPrivate->page_size - 1);
2823         if (page_offset) {
2824                 LOG_DEBUG("Not-Aligned start");
2825                 /* read the partial */
2826                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2827                 if (r != ERROR_OK)
2828                         goto done;
2829
2830                 /* over-write with new data */
2831                 n = (pPrivate->page_size - page_offset);
2832                 memcpy(pagebuffer + page_offset,
2833                         buffer,
2834                         n);
2835
2836                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2837                 if (r != ERROR_OK)
2838                         goto done;
2839
2840                 count  -= n;
2841                 offset += n;
2842                 buffer += n;
2843                 page_cur++;
2844         }
2845
2846         /* By checking that offset is correct here, we also
2847         fix a clang warning */
2848         assert(offset % pPrivate->page_size == 0);
2849
2850         /* intermediate large pages */
2851         /* also - the final *terminal* */
2852         /* if that terminal page is a full page */
2853         LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
2854                 (int)page_cur, (int)page_end, (unsigned int)(count));
2855
2856         while ((page_cur < page_end) &&
2857                         (count >= pPrivate->page_size)) {
2858                 r = sam3_page_write(pPrivate, page_cur, buffer);
2859                 if (r != ERROR_OK)
2860                         goto done;
2861                 count -= pPrivate->page_size;
2862                 buffer += pPrivate->page_size;
2863                 page_cur += 1;
2864         }
2865
2866         /* terminal partial page? */
2867         if (count) {
2868                 LOG_DEBUG("Terminal partial page, count = 0x%08x", (unsigned int)(count));
2869                 /* we have a partial page */
2870                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2871                 if (r != ERROR_OK)
2872                         goto done;
2873                                         /* data goes at start */
2874                 memcpy(pagebuffer, buffer, count);
2875                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2876                 if (r != ERROR_OK)
2877                         goto done;
2878                 buffer += count;
2879         }
2880         LOG_DEBUG("Done!");
2881         r = ERROR_OK;
2882 done:
2883         if (pagebuffer)
2884                 free(pagebuffer);
2885         return r;
2886 }
2887
2888 COMMAND_HANDLER(sam3_handle_info_command)
2889 {
2890         struct sam3_chip *pChip;
2891         pChip = get_current_sam3(CMD_CTX);
2892         if (!pChip)
2893                 return ERROR_OK;
2894
2895         unsigned x;
2896         int r;
2897
2898         /* bank0 must exist before we can do anything */
2899         if (pChip->details.bank[0].pBank == NULL) {
2900                 x = 0;
2901 need_define:
2902                 command_print(CMD_CTX,
2903                         "Please define bank %d via command: flash bank %s ... ",
2904                         x,
2905                         at91sam3_flash.name);
2906                 return ERROR_FAIL;
2907         }
2908
2909         /* if bank 0 is not probed, then probe it */
2910         if (!(pChip->details.bank[0].probed)) {
2911                 r = sam3_auto_probe(pChip->details.bank[0].pBank);
2912                 if (r != ERROR_OK)
2913                         return ERROR_FAIL;
2914         }
2915         /* above guarantees the "chip details" structure is valid */
2916         /* and thus, bank private areas are valid */
2917         /* and we have a SAM3 chip, what a concept! */
2918
2919         /* auto-probe other banks, 0 done above */
2920         for (x = 1; x < SAM3_MAX_FLASH_BANKS; x++) {
2921                 /* skip banks not present */
2922                 if (!(pChip->details.bank[x].present))
2923                         continue;
2924
2925                 if (pChip->details.bank[x].pBank == NULL)
2926                         goto need_define;
2927
2928                 if (pChip->details.bank[x].probed)
2929                         continue;
2930
2931                 r = sam3_auto_probe(pChip->details.bank[x].pBank);
2932                 if (r != ERROR_OK)
2933                         return r;
2934         }
2935
2936         r = sam3_GetInfo(pChip);
2937         if (r != ERROR_OK) {
2938                 LOG_DEBUG("Sam3Info, Failed %d", r);
2939                 return r;
2940         }
2941
2942         return ERROR_OK;
2943 }
2944
2945 COMMAND_HANDLER(sam3_handle_gpnvm_command)
2946 {
2947         unsigned x, v;
2948         int r, who;
2949         struct sam3_chip *pChip;
2950
2951         pChip = get_current_sam3(CMD_CTX);
2952         if (!pChip)
2953                 return ERROR_OK;
2954
2955         if (pChip->target->state != TARGET_HALTED) {
2956                 LOG_ERROR("sam3 - target not halted");
2957                 return ERROR_TARGET_NOT_HALTED;
2958         }
2959
2960         if (pChip->details.bank[0].pBank == NULL) {
2961                 command_print(CMD_CTX, "Bank0 must be defined first via: flash bank %s ...",
2962                         at91sam3_flash.name);
2963                 return ERROR_FAIL;
2964         }
2965         if (!pChip->details.bank[0].probed) {
2966                 r = sam3_auto_probe(pChip->details.bank[0].pBank);
2967                 if (r != ERROR_OK)
2968                         return r;
2969         }
2970
2971         switch (CMD_ARGC) {
2972                 default:
2973                         return ERROR_COMMAND_SYNTAX_ERROR;
2974                         break;
2975                 case 0:
2976                         goto showall;
2977                         break;
2978                 case 1:
2979                         who = -1;
2980                         break;
2981                 case 2:
2982                         if ((0 == strcmp(CMD_ARGV[0], "show")) && (0 == strcmp(CMD_ARGV[1], "all")))
2983                                 who = -1;
2984                         else {
2985                                 uint32_t v32;
2986                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], v32);
2987                                 who = v32;
2988                         }
2989                         break;
2990         }
2991
2992         if (0 == strcmp("show", CMD_ARGV[0])) {
2993                 if (who == -1) {
2994 showall:
2995                         r = ERROR_OK;
2996                         for (x = 0; x < pChip->details.n_gpnvms; x++) {
2997                                 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
2998                                 if (r != ERROR_OK)
2999                                         break;
3000                                 command_print(CMD_CTX, "sam3-gpnvm%u: %u", x, v);
3001                         }
3002                         return r;
3003                 }
3004                 if ((who >= 0) && (((unsigned)(who)) < pChip->details.n_gpnvms)) {
3005                         r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), who, &v);
3006                         command_print(CMD_CTX, "sam3-gpnvm%u: %u", who, v);
3007                         return r;
3008                 } else {
3009                         command_print(CMD_CTX, "sam3-gpnvm invalid GPNVM: %u", who);
3010                         return ERROR_COMMAND_SYNTAX_ERROR;
3011                 }
3012         }
3013
3014         if (who == -1) {
3015                 command_print(CMD_CTX, "Missing GPNVM number");
3016                 return ERROR_COMMAND_SYNTAX_ERROR;
3017         }
3018
3019         if (0 == strcmp("set", CMD_ARGV[0]))
3020                 r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
3021         else if ((0 == strcmp("clr", CMD_ARGV[0])) ||
3022                  (0 == strcmp("clear", CMD_ARGV[0])))                   /* quietly accept both */
3023                 r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
3024         else {
3025                 command_print(CMD_CTX, "Unknown command: %s", CMD_ARGV[0]);
3026                 r = ERROR_COMMAND_SYNTAX_ERROR;
3027         }
3028         return r;
3029 }
3030
3031 COMMAND_HANDLER(sam3_handle_slowclk_command)
3032 {
3033         struct sam3_chip *pChip;
3034
3035         pChip = get_current_sam3(CMD_CTX);
3036         if (!pChip)
3037                 return ERROR_OK;
3038
3039         switch (CMD_ARGC) {
3040                 case 0:
3041                         /* show */
3042                         break;
3043                 case 1:
3044                 {
3045                         /* set */
3046                         uint32_t v;
3047                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], v);
3048                         if (v > 200000) {
3049                                 /* absurd slow clock of 200Khz? */
3050                                 command_print(CMD_CTX, "Absurd/illegal slow clock freq: %d\n", (int)(v));
3051                                 return ERROR_COMMAND_SYNTAX_ERROR;
3052                         }
3053                         pChip->cfg.slow_freq = v;
3054                         break;
3055                 }
3056                 default:
3057                         /* error */
3058                         command_print(CMD_CTX, "Too many parameters");
3059                         return ERROR_COMMAND_SYNTAX_ERROR;
3060                         break;
3061         }
3062         command_print(CMD_CTX, "Slowclk freq: %d.%03dkhz",
3063                 (int)(pChip->cfg.slow_freq / 1000),
3064                 (int)(pChip->cfg.slow_freq % 1000));
3065         return ERROR_OK;
3066 }
3067
3068 static const struct command_registration at91sam3_exec_command_handlers[] = {
3069         {
3070                 .name = "gpnvm",
3071                 .handler = sam3_handle_gpnvm_command,
3072                 .mode = COMMAND_EXEC,
3073                 .usage = "[('clr'|'set'|'show') bitnum]",
3074                 .help = "Without arguments, shows all bits in the gpnvm "
3075                         "register.  Otherwise, clears, sets, or shows one "
3076                         "General Purpose Non-Volatile Memory (gpnvm) bit.",
3077         },
3078         {
3079                 .name = "info",
3080                 .handler = sam3_handle_info_command,
3081                 .mode = COMMAND_EXEC,
3082                 .help = "Print information about the current at91sam3 chip"
3083                         "and its flash configuration.",
3084         },
3085         {
3086                 .name = "slowclk",
3087                 .handler = sam3_handle_slowclk_command,
3088                 .mode = COMMAND_EXEC,
3089                 .usage = "[clock_hz]",
3090                 .help = "Display or set the slowclock frequency "
3091                         "(default 32768 Hz).",
3092         },
3093         COMMAND_REGISTRATION_DONE
3094 };
3095 static const struct command_registration at91sam3_command_handlers[] = {
3096         {
3097                 .name = "at91sam3",
3098                 .mode = COMMAND_ANY,
3099                 .help = "at91sam3 flash command group",
3100                 .usage = "",
3101                 .chain = at91sam3_exec_command_handlers,
3102         },
3103         COMMAND_REGISTRATION_DONE
3104 };
3105
3106 struct flash_driver at91sam3_flash = {
3107         .name = "at91sam3",
3108         .commands = at91sam3_command_handlers,
3109         .flash_bank_command = sam3_flash_bank_command,
3110         .erase = sam3_erase,
3111         .protect = sam3_protect,
3112         .write = sam3_write,
3113         .read = default_flash_read,
3114         .probe = sam3_probe,
3115         .auto_probe = sam3_auto_probe,
3116         .erase_check = sam3_erase_check,
3117         .protect_check = sam3_protect_check,
3118         .info = sam3_info,
3119 };