SAM3: Add missing architecture names for SAM3S and SAM3N
[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   = 16,
580                                 .sector_size = 16384,
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   = 16,
613                                 .sector_size = 16384,
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   = 16,
645                                 .sector_size = 16384,
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   = 8,
677                                 .sector_size = 16384,
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   = 8,
709                                 .sector_size = 16384,
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   = 8,
741                                 .sector_size = 16384,
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   = 4,
773                                 .sector_size = 16384,
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   = 4,
805                                 .sector_size = 16384,
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   = 4,
837                                 .sector_size = 16384,
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         { 0x93,  "ATSAM3NxA Series (48-pin version)"            },
1840         { 0x94,  "ATSAM3NxB Series (64-pin version)"            },
1841         { 0x95,  "ATSAM3NxC Series (100-pin version)"           },
1842         { 0x98,  "ATSAM3SDxA Series (48-pin version)"           },
1843         { 0x99,  "ATSAM3SDxB Series (64-pin version)"           },
1844         { 0x9A,  "ATSAM3SDxC Series (100-pin version)"          },
1845         { 0xA5,  "ATSAM5A"                                                              },
1846         { 0xF0,  "AT75Cxx Series"                                                       },
1847         { -1, NULL },
1848 };
1849
1850 static const char *const nvptype[] = {
1851         "rom",  /* 0 */
1852         "romless or onchip flash",      /* 1 */
1853         "embedded flash memory",/* 2 */
1854         "rom(nvpsiz) + embedded flash (nvpsiz2)",       /* 3 */
1855         "sram emulating flash", /* 4 */
1856         _unknown,       /* 5 */
1857         _unknown,       /* 6 */
1858         _unknown,       /* 7 */
1859 };
1860
1861 static const char *_yes_or_no(uint32_t v)
1862 {
1863         if (v)
1864                 return "YES";
1865         else
1866                 return "NO";
1867 }
1868
1869 static const char *const _rc_freq[] = {
1870         "4 MHz", "8 MHz", "12 MHz", "reserved"
1871 };
1872
1873 static void sam3_explain_ckgr_mor(struct sam3_chip *pChip)
1874 {
1875         uint32_t v;
1876         uint32_t rcen;
1877
1878         v = sam3_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
1879         LOG_USER("(main xtal enabled: %s)", _yes_or_no(v));
1880         v = sam3_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
1881         LOG_USER("(main osc bypass: %s)", _yes_or_no(v));
1882         rcen = sam3_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 3, 1);
1883         LOG_USER("(onchip RC-OSC enabled: %s)", _yes_or_no(rcen));
1884         v = sam3_reg_fieldname(pChip, "MOSCRCF", pChip->cfg.CKGR_MOR, 4, 3);
1885         LOG_USER("(onchip RC-OSC freq: %s)", _rc_freq[v]);
1886
1887         pChip->cfg.rc_freq = 0;
1888         if (rcen) {
1889                 switch (v) {
1890                         default:
1891                                 pChip->cfg.rc_freq = 0;
1892                                 break;
1893                         case 0:
1894                                 pChip->cfg.rc_freq = 4 * 1000 * 1000;
1895                                 break;
1896                         case 1:
1897                                 pChip->cfg.rc_freq = 8 * 1000 * 1000;
1898                                 break;
1899                         case 2:
1900                                 pChip->cfg.rc_freq = 12 * 1000 * 1000;
1901                                 break;
1902                 }
1903         }
1904
1905         v = sam3_reg_fieldname(pChip, "MOSCXTST", pChip->cfg.CKGR_MOR, 8, 8);
1906         LOG_USER("(startup clks, time= %f uSecs)",
1907                 ((float)(v * 1000000)) / ((float)(pChip->cfg.slow_freq)));
1908         v = sam3_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
1909         LOG_USER("(mainosc source: %s)",
1910                 v ? "external xtal" : "internal RC");
1911
1912         v = sam3_reg_fieldname(pChip, "CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
1913         LOG_USER("(clock failure enabled: %s)",
1914                 _yes_or_no(v));
1915 }
1916
1917 static void sam3_explain_chipid_cidr(struct sam3_chip *pChip)
1918 {
1919         int x;
1920         uint32_t v;
1921         const char *cp;
1922
1923         sam3_reg_fieldname(pChip, "Version", pChip->cfg.CHIPID_CIDR, 0, 5);
1924         LOG_USER_N("\n");
1925
1926         v = sam3_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
1927         LOG_USER("%s", eproc_names[v]);
1928
1929         v = sam3_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
1930         LOG_USER("%s", nvpsize[v]);
1931
1932         v = sam3_reg_fieldname(pChip, "NVPSIZE2", pChip->cfg.CHIPID_CIDR, 12, 4);
1933         LOG_USER("%s", nvpsize2[v]);
1934
1935         v = sam3_reg_fieldname(pChip, "SRAMSIZE", pChip->cfg.CHIPID_CIDR, 16, 4);
1936         LOG_USER("%s", sramsize[v]);
1937
1938         v = sam3_reg_fieldname(pChip, "ARCH", pChip->cfg.CHIPID_CIDR, 20, 8);
1939         cp = _unknown;
1940         for (x = 0; archnames[x].name; x++) {
1941                 if (v == archnames[x].value) {
1942                         cp = archnames[x].name;
1943                         break;
1944                 }
1945         }
1946
1947         LOG_USER("%s", cp);
1948
1949         v = sam3_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
1950         LOG_USER("%s", nvptype[v]);
1951
1952         v = sam3_reg_fieldname(pChip, "EXTID", pChip->cfg.CHIPID_CIDR, 31, 1);
1953         LOG_USER("(exists: %s)", _yes_or_no(v));
1954 }
1955
1956 static void sam3_explain_ckgr_mcfr(struct sam3_chip *pChip)
1957 {
1958         uint32_t v;
1959
1960         v = sam3_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
1961         LOG_USER("(main ready: %s)", _yes_or_no(v));
1962
1963         v = sam3_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
1964
1965         v = (v * pChip->cfg.slow_freq) / 16;
1966         pChip->cfg.mainosc_freq = v;
1967
1968         LOG_USER("(%3.03f Mhz (%d.%03dkhz slowclk)",
1969                 _tomhz(v),
1970                 pChip->cfg.slow_freq / 1000,
1971                 pChip->cfg.slow_freq % 1000);
1972 }
1973
1974 static void sam3_explain_ckgr_plla(struct sam3_chip *pChip)
1975 {
1976         uint32_t mula, diva;
1977
1978         diva = sam3_reg_fieldname(pChip, "DIVA", pChip->cfg.CKGR_PLLAR, 0, 8);
1979         LOG_USER_N("\n");
1980         mula = sam3_reg_fieldname(pChip, "MULA", pChip->cfg.CKGR_PLLAR, 16, 11);
1981         LOG_USER_N("\n");
1982         pChip->cfg.plla_freq = 0;
1983         if (mula == 0)
1984                 LOG_USER("\tPLLA Freq: (Disabled,mula = 0)");
1985         else if (diva == 0)
1986                 LOG_USER("\tPLLA Freq: (Disabled,diva = 0)");
1987         else if (diva == 1) {
1988                 pChip->cfg.plla_freq = (pChip->cfg.mainosc_freq * (mula + 1));
1989                 LOG_USER("\tPLLA Freq: %3.03f MHz",
1990                         _tomhz(pChip->cfg.plla_freq));
1991         }
1992 }
1993
1994 static void sam3_explain_mckr(struct sam3_chip *pChip)
1995 {
1996         uint32_t css, pres, fin = 0;
1997         int pdiv = 0;
1998         const char *cp = NULL;
1999
2000         css = sam3_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
2001         switch (css & 3) {
2002                 case 0:
2003                         fin = pChip->cfg.slow_freq;
2004                         cp = "slowclk";
2005                         break;
2006                 case 1:
2007                         fin = pChip->cfg.mainosc_freq;
2008                         cp  = "mainosc";
2009                         break;
2010                 case 2:
2011                         fin = pChip->cfg.plla_freq;
2012                         cp  = "plla";
2013                         break;
2014                 case 3:
2015                         if (pChip->cfg.CKGR_UCKR & (1 << 16)) {
2016                                 fin = 480 * 1000 * 1000;
2017                                 cp = "upll";
2018                         } else {
2019                                 fin = 0;
2020                                 cp  = "upll (*ERROR* UPLL is disabled)";
2021                         }
2022                         break;
2023                 default:
2024                         assert(0);
2025                         break;
2026         }
2027
2028         LOG_USER("%s (%3.03f Mhz)",
2029                 cp,
2030                 _tomhz(fin));
2031         pres = sam3_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
2032         switch (pres & 0x07) {
2033                 case 0:
2034                         pdiv = 1;
2035                         cp = "selected clock";
2036                         break;
2037                 case 1:
2038                         pdiv = 2;
2039                         cp = "clock/2";
2040                         break;
2041                 case 2:
2042                         pdiv = 4;
2043                         cp = "clock/4";
2044                         break;
2045                 case 3:
2046                         pdiv = 8;
2047                         cp = "clock/8";
2048                         break;
2049                 case 4:
2050                         pdiv = 16;
2051                         cp = "clock/16";
2052                         break;
2053                 case 5:
2054                         pdiv = 32;
2055                         cp = "clock/32";
2056                         break;
2057                 case 6:
2058                         pdiv = 64;
2059                         cp = "clock/64";
2060                         break;
2061                 case 7:
2062                         pdiv = 6;
2063                         cp = "clock/6";
2064                         break;
2065                 default:
2066                         assert(0);
2067                         break;
2068         }
2069         LOG_USER("(%s)", cp);
2070         fin = fin / pdiv;
2071         /* sam3 has a *SINGLE* clock - */
2072         /* other at91 series parts have divisors for these. */
2073         pChip->cfg.cpu_freq = fin;
2074         pChip->cfg.mclk_freq = fin;
2075         pChip->cfg.fclk_freq = fin;
2076         LOG_USER("\t\tResult CPU Freq: %3.03f",
2077                 _tomhz(fin));
2078 }
2079
2080 #if 0
2081 static struct sam3_chip *target2sam3(struct target *pTarget)
2082 {
2083         struct sam3_chip *pChip;
2084
2085         if (pTarget == NULL)
2086                 return NULL;
2087
2088         pChip = all_sam3_chips;
2089         while (pChip) {
2090                 if (pChip->target == pTarget)
2091                         break;  /* return below */
2092                 else
2093                         pChip = pChip->next;
2094         }
2095         return pChip;
2096 }
2097 #endif
2098
2099 static uint32_t *sam3_get_reg_ptr(struct sam3_cfg *pCfg, const struct sam3_reg_list *pList)
2100 {
2101         /* this function exists to help */
2102         /* keep funky offsetof() errors */
2103         /* and casting from causing bugs */
2104
2105         /* By using prototypes - we can detect what would */
2106         /* be casting errors. */
2107
2108         return (uint32_t *)(void *)(((char *)(pCfg)) + pList->struct_offset);
2109 }
2110
2111
2112 #define SAM3_ENTRY(NAME, FUNC)  { .address = SAM3_ ## NAME, .struct_offset = offsetof( \
2113                                                   struct sam3_cfg, \
2114                                                   NAME), # NAME, FUNC }
2115 static const struct sam3_reg_list sam3_all_regs[] = {
2116         SAM3_ENTRY(CKGR_MOR, sam3_explain_ckgr_mor),
2117         SAM3_ENTRY(CKGR_MCFR, sam3_explain_ckgr_mcfr),
2118         SAM3_ENTRY(CKGR_PLLAR, sam3_explain_ckgr_plla),
2119         SAM3_ENTRY(CKGR_UCKR, NULL),
2120         SAM3_ENTRY(PMC_FSMR, NULL),
2121         SAM3_ENTRY(PMC_FSPR, NULL),
2122         SAM3_ENTRY(PMC_IMR, NULL),
2123         SAM3_ENTRY(PMC_MCKR, sam3_explain_mckr),
2124         SAM3_ENTRY(PMC_PCK0, NULL),
2125         SAM3_ENTRY(PMC_PCK1, NULL),
2126         SAM3_ENTRY(PMC_PCK2, NULL),
2127         SAM3_ENTRY(PMC_PCSR, NULL),
2128         SAM3_ENTRY(PMC_SCSR, NULL),
2129         SAM3_ENTRY(PMC_SR, NULL),
2130         SAM3_ENTRY(CHIPID_CIDR, sam3_explain_chipid_cidr),
2131         SAM3_ENTRY(CHIPID_EXID, NULL),
2132         SAM3_ENTRY(SUPC_CR, NULL),
2133
2134         /* TERMINATE THE LIST */
2135         { .name = NULL }
2136 };
2137 #undef SAM3_ENTRY
2138
2139 static struct sam3_bank_private *get_sam3_bank_private(struct flash_bank *bank)
2140 {
2141         return (struct sam3_bank_private *)(bank->driver_priv);
2142 }
2143
2144 /**
2145  * Given a pointer to where it goes in the structure,
2146  * determine the register name, address from the all registers table.
2147  */
2148 static const struct sam3_reg_list *sam3_GetReg(struct sam3_chip *pChip, uint32_t *goes_here)
2149 {
2150         const struct sam3_reg_list *pReg;
2151
2152         pReg = &(sam3_all_regs[0]);
2153         while (pReg->name) {
2154                 uint32_t *pPossible;
2155
2156                 /* calculate where this one go.. */
2157                 /* it is "possibly" this register. */
2158
2159                 pPossible = ((uint32_t *)(void *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
2160
2161                 /* well? Is it this register */
2162                 if (pPossible == goes_here) {
2163                         /* Jump for joy! */
2164                         return pReg;
2165                 }
2166
2167                 /* next... */
2168                 pReg++;
2169         }
2170         /* This is *TOTAL*PANIC* - we are totally screwed. */
2171         LOG_ERROR("INVALID SAM3 REGISTER");
2172         return NULL;
2173 }
2174
2175 static int sam3_ReadThisReg(struct sam3_chip *pChip, uint32_t *goes_here)
2176 {
2177         const struct sam3_reg_list *pReg;
2178         int r;
2179
2180         pReg = sam3_GetReg(pChip, goes_here);
2181         if (!pReg)
2182                 return ERROR_FAIL;
2183
2184         r = target_read_u32(pChip->target, pReg->address, goes_here);
2185         if (r != ERROR_OK) {
2186                 LOG_ERROR("Cannot read SAM3 register: %s @ 0x%08x, Err: %d",
2187                         pReg->name, (unsigned)(pReg->address), r);
2188         }
2189         return r;
2190 }
2191
2192 static int sam3_ReadAllRegs(struct sam3_chip *pChip)
2193 {
2194         int r;
2195         const struct sam3_reg_list *pReg;
2196
2197         pReg = &(sam3_all_regs[0]);
2198         while (pReg->name) {
2199                 r = sam3_ReadThisReg(pChip,
2200                                 sam3_get_reg_ptr(&(pChip->cfg), pReg));
2201                 if (r != ERROR_OK) {
2202                         LOG_ERROR("Cannot read SAM3 registere: %s @ 0x%08x, Error: %d",
2203                                 pReg->name, ((unsigned)(pReg->address)), r);
2204                         return r;
2205                 }
2206
2207                 pReg++;
2208         }
2209
2210         return ERROR_OK;
2211 }
2212
2213 static int sam3_GetInfo(struct sam3_chip *pChip)
2214 {
2215         const struct sam3_reg_list *pReg;
2216         uint32_t regval;
2217
2218         pReg = &(sam3_all_regs[0]);
2219         while (pReg->name) {
2220                 /* display all regs */
2221                 LOG_DEBUG("Start: %s", pReg->name);
2222                 regval = *sam3_get_reg_ptr(&(pChip->cfg), pReg);
2223                 LOG_USER("%*s: [0x%08x] -> 0x%08x",
2224                         REG_NAME_WIDTH,
2225                         pReg->name,
2226                         pReg->address,
2227                         regval);
2228                 if (pReg->explain_func)
2229                         (*(pReg->explain_func))(pChip);
2230                 LOG_DEBUG("End: %s", pReg->name);
2231                 pReg++;
2232         }
2233         LOG_USER("   rc-osc: %3.03f MHz", _tomhz(pChip->cfg.rc_freq));
2234         LOG_USER("  mainosc: %3.03f MHz", _tomhz(pChip->cfg.mainosc_freq));
2235         LOG_USER("     plla: %3.03f MHz", _tomhz(pChip->cfg.plla_freq));
2236         LOG_USER(" cpu-freq: %3.03f MHz", _tomhz(pChip->cfg.cpu_freq));
2237         LOG_USER("mclk-freq: %3.03f MHz", _tomhz(pChip->cfg.mclk_freq));
2238
2239         LOG_USER(" UniqueId: 0x%08x 0x%08x 0x%08x 0x%08x",
2240                 pChip->cfg.unique_id[0],
2241                 pChip->cfg.unique_id[1],
2242                 pChip->cfg.unique_id[2],
2243                 pChip->cfg.unique_id[3]);
2244
2245         return ERROR_OK;
2246 }
2247
2248 static int sam3_erase_check(struct flash_bank *bank)
2249 {
2250         int x;
2251
2252         LOG_DEBUG("Here");
2253         if (bank->target->state != TARGET_HALTED) {
2254                 LOG_ERROR("Target not halted");
2255                 return ERROR_TARGET_NOT_HALTED;
2256         }
2257         if (0 == bank->num_sectors) {
2258                 LOG_ERROR("Target: not supported/not probed");
2259                 return ERROR_FAIL;
2260         }
2261
2262         LOG_INFO("sam3 - supports auto-erase, erase_check ignored");
2263         for (x = 0; x < bank->num_sectors; x++)
2264                 bank->sectors[x].is_erased = 1;
2265
2266         LOG_DEBUG("Done");
2267         return ERROR_OK;
2268 }
2269
2270 static int sam3_protect_check(struct flash_bank *bank)
2271 {
2272         int r;
2273         uint32_t v = 0;
2274         unsigned x;
2275         struct sam3_bank_private *pPrivate;
2276
2277         LOG_DEBUG("Begin");
2278         if (bank->target->state != TARGET_HALTED) {
2279                 LOG_ERROR("Target not halted");
2280                 return ERROR_TARGET_NOT_HALTED;
2281         }
2282
2283         pPrivate = get_sam3_bank_private(bank);
2284         if (!pPrivate) {
2285                 LOG_ERROR("no private for this bank?");
2286                 return ERROR_FAIL;
2287         }
2288         if (!(pPrivate->probed))
2289                 return ERROR_FLASH_BANK_NOT_PROBED;
2290
2291         r = FLASHD_GetLockBits(pPrivate, &v);
2292         if (r != ERROR_OK) {
2293                 LOG_DEBUG("Failed: %d", r);
2294                 return r;
2295         }
2296
2297         for (x = 0; x < pPrivate->nsectors; x++)
2298                 bank->sectors[x].is_protected = (!!(v & (1 << x)));
2299         LOG_DEBUG("Done");
2300         return ERROR_OK;
2301 }
2302
2303 FLASH_BANK_COMMAND_HANDLER(sam3_flash_bank_command)
2304 {
2305         struct sam3_chip *pChip;
2306
2307         pChip = all_sam3_chips;
2308
2309         /* is this an existing chip? */
2310         while (pChip) {
2311                 if (pChip->target == bank->target)
2312                         break;
2313                 pChip = pChip->next;
2314         }
2315
2316         if (!pChip) {
2317                 /* this is a *NEW* chip */
2318                 pChip = calloc(1, sizeof(struct sam3_chip));
2319                 if (!pChip) {
2320                         LOG_ERROR("NO RAM!");
2321                         return ERROR_FAIL;
2322                 }
2323                 pChip->target = bank->target;
2324                 /* insert at head */
2325                 pChip->next = all_sam3_chips;
2326                 all_sam3_chips = pChip;
2327                 pChip->target = bank->target;
2328                 /* assumption is this runs at 32khz */
2329                 pChip->cfg.slow_freq = 32768;
2330                 pChip->probed = 0;
2331         }
2332
2333         switch (bank->base) {
2334                 default:
2335                         LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x or 0x%08x "
2336                         "[at91sam3u series] or 0x%08x [at91sam3s series] or "
2337                         "0x%08x [at91sam3n series])",
2338                         ((unsigned int)(bank->base)),
2339                         ((unsigned int)(FLASH_BANK0_BASE_U)),
2340                         ((unsigned int)(FLASH_BANK1_BASE_U)),
2341                         ((unsigned int)(FLASH_BANK_BASE_S)),
2342                         ((unsigned int)(FLASH_BANK_BASE_N)));
2343                         return ERROR_FAIL;
2344                         break;
2345
2346                 /* at91sam3u series */
2347                 case FLASH_BANK0_BASE_U:
2348                         bank->driver_priv = &(pChip->details.bank[0]);
2349                         bank->bank_number = 0;
2350                         pChip->details.bank[0].pChip = pChip;
2351                         pChip->details.bank[0].pBank = bank;
2352                         break;
2353                 case FLASH_BANK1_BASE_U:
2354                         bank->driver_priv = &(pChip->details.bank[1]);
2355                         bank->bank_number = 1;
2356                         pChip->details.bank[1].pChip = pChip;
2357                         pChip->details.bank[1].pBank = bank;
2358                         break;
2359
2360                 /* at91sam3s and at91sam3n series */
2361                 case FLASH_BANK_BASE_S:
2362                         bank->driver_priv = &(pChip->details.bank[0]);
2363                         bank->bank_number = 0;
2364                         pChip->details.bank[0].pChip = pChip;
2365                         pChip->details.bank[0].pBank = bank;
2366                         break;
2367         }
2368
2369         /* we initialize after probing. */
2370         return ERROR_OK;
2371 }
2372
2373 static int sam3_GetDetails(struct sam3_bank_private *pPrivate)
2374 {
2375         const struct sam3_chip_details *pDetails;
2376         struct sam3_chip *pChip;
2377         struct flash_bank *saved_banks[SAM3_MAX_FLASH_BANKS];
2378         unsigned x;
2379
2380         LOG_DEBUG("Begin");
2381         pDetails = all_sam3_details;
2382         while (pDetails->name) {
2383                 /* Compare cidr without version bits */
2384                 if (pDetails->chipid_cidr == (pPrivate->pChip->cfg.CHIPID_CIDR & 0xFFFFFFE0))
2385                         break;
2386                 else
2387                         pDetails++;
2388         }
2389         if (pDetails->name == NULL) {
2390                 LOG_ERROR("SAM3 ChipID 0x%08x not found in table (perhaps you can this chip?)",
2391                         (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
2392                 /* Help the victim, print details about the chip */
2393                 LOG_INFO("SAM3 CHIPID_CIDR: 0x%08x decodes as follows",
2394                         pPrivate->pChip->cfg.CHIPID_CIDR);
2395                 sam3_explain_chipid_cidr(pPrivate->pChip);
2396                 return ERROR_FAIL;
2397         }
2398
2399         /* DANGER: THERE ARE DRAGONS HERE */
2400
2401         /* get our pChip - it is going */
2402         /* to be over-written shortly */
2403         pChip = pPrivate->pChip;
2404
2405         /* Note that, in reality: */
2406         /*  */
2407         /*     pPrivate = &(pChip->details.bank[0]) */
2408         /* or  pPrivate = &(pChip->details.bank[1]) */
2409         /*  */
2410
2411         /* save the "bank" pointers */
2412         for (x = 0; x < SAM3_MAX_FLASH_BANKS; x++)
2413                 saved_banks[x] = pChip->details.bank[x].pBank;
2414
2415         /* Overwrite the "details" structure. */
2416         memcpy(&(pPrivate->pChip->details),
2417                 pDetails,
2418                 sizeof(pPrivate->pChip->details));
2419
2420         /* now fix the ghosted pointers */
2421         for (x = 0; x < SAM3_MAX_FLASH_BANKS; x++) {
2422                 pChip->details.bank[x].pChip = pChip;
2423                 pChip->details.bank[x].pBank = saved_banks[x];
2424         }
2425
2426         /* update the *BANK*SIZE* */
2427
2428         LOG_DEBUG("End");
2429         return ERROR_OK;
2430 }
2431
2432 static int _sam3_probe(struct flash_bank *bank, int noise)
2433 {
2434         unsigned x;
2435         int r;
2436         struct sam3_bank_private *pPrivate;
2437
2438
2439         LOG_DEBUG("Begin: Bank: %d, Noise: %d", bank->bank_number, noise);
2440         if (bank->target->state != TARGET_HALTED) {
2441                 LOG_ERROR("Target not halted");
2442                 return ERROR_TARGET_NOT_HALTED;
2443         }
2444
2445         pPrivate = get_sam3_bank_private(bank);
2446         if (!pPrivate) {
2447                 LOG_ERROR("Invalid/unknown bank number");
2448                 return ERROR_FAIL;
2449         }
2450
2451         r = sam3_ReadAllRegs(pPrivate->pChip);
2452         if (r != ERROR_OK)
2453                 return r;
2454
2455         LOG_DEBUG("Here");
2456         if (pPrivate->pChip->probed)
2457                 r = sam3_GetInfo(pPrivate->pChip);
2458         else
2459                 r = sam3_GetDetails(pPrivate);
2460         if (r != ERROR_OK)
2461                 return r;
2462
2463         /* update the flash bank size */
2464         for (x = 0; x < SAM3_MAX_FLASH_BANKS; x++) {
2465                 if (bank->base == pPrivate->pChip->details.bank[x].base_address) {
2466                         bank->size = pPrivate->pChip->details.bank[x].size_bytes;
2467                         break;
2468                 }
2469         }
2470
2471         if (bank->sectors == NULL) {
2472                 bank->sectors = calloc(pPrivate->nsectors, (sizeof((bank->sectors)[0])));
2473                 if (bank->sectors == NULL) {
2474                         LOG_ERROR("No memory!");
2475                         return ERROR_FAIL;
2476                 }
2477                 bank->num_sectors = pPrivate->nsectors;
2478
2479                 for (x = 0; ((int)(x)) < bank->num_sectors; x++) {
2480                         bank->sectors[x].size = pPrivate->sector_size;
2481                         bank->sectors[x].offset = x * (pPrivate->sector_size);
2482                         /* mark as unknown */
2483                         bank->sectors[x].is_erased = -1;
2484                         bank->sectors[x].is_protected = -1;
2485                 }
2486         }
2487
2488         pPrivate->probed = 1;
2489
2490         r = sam3_protect_check(bank);
2491         if (r != ERROR_OK)
2492                 return r;
2493
2494         LOG_DEBUG("Bank = %d, nbanks = %d",
2495                 pPrivate->bank_number, pPrivate->pChip->details.n_banks);
2496         if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
2497                 /* read unique id, */
2498                 /* it appears to be associated with the *last* flash bank. */
2499                 FLASHD_ReadUniqueID(pPrivate);
2500         }
2501
2502         return r;
2503 }
2504
2505 static int sam3_probe(struct flash_bank *bank)
2506 {
2507         return _sam3_probe(bank, 1);
2508 }
2509
2510 static int sam3_auto_probe(struct flash_bank *bank)
2511 {
2512         return _sam3_probe(bank, 0);
2513 }
2514
2515 static int sam3_erase(struct flash_bank *bank, int first, int last)
2516 {
2517         struct sam3_bank_private *pPrivate;
2518         int r;
2519
2520         LOG_DEBUG("Here");
2521         if (bank->target->state != TARGET_HALTED) {
2522                 LOG_ERROR("Target not halted");
2523                 return ERROR_TARGET_NOT_HALTED;
2524         }
2525
2526         r = sam3_auto_probe(bank);
2527         if (r != ERROR_OK) {
2528                 LOG_DEBUG("Here,r=%d", r);
2529                 return r;
2530         }
2531
2532         pPrivate = get_sam3_bank_private(bank);
2533         if (!(pPrivate->probed))
2534                 return ERROR_FLASH_BANK_NOT_PROBED;
2535
2536         if ((first == 0) && ((last + 1) == ((int)(pPrivate->nsectors)))) {
2537                 /* whole chip */
2538                 LOG_DEBUG("Here");
2539                 return FLASHD_EraseEntireBank(pPrivate);
2540         }
2541         LOG_INFO("sam3 auto-erases while programing (request ignored)");
2542         return ERROR_OK;
2543 }
2544
2545 static int sam3_protect(struct flash_bank *bank, int set, int first, int last)
2546 {
2547         struct sam3_bank_private *pPrivate;
2548         int r;
2549
2550         LOG_DEBUG("Here");
2551         if (bank->target->state != TARGET_HALTED) {
2552                 LOG_ERROR("Target not halted");
2553                 return ERROR_TARGET_NOT_HALTED;
2554         }
2555
2556         pPrivate = get_sam3_bank_private(bank);
2557         if (!(pPrivate->probed))
2558                 return ERROR_FLASH_BANK_NOT_PROBED;
2559
2560         if (set)
2561                 r = FLASHD_Lock(pPrivate, (unsigned)(first), (unsigned)(last));
2562         else
2563                 r = FLASHD_Unlock(pPrivate, (unsigned)(first), (unsigned)(last));
2564         LOG_DEBUG("End: r=%d", r);
2565
2566         return r;
2567
2568 }
2569
2570 static int sam3_info(struct flash_bank *bank, char *buf, int buf_size)
2571 {
2572         if (bank->target->state != TARGET_HALTED) {
2573                 LOG_ERROR("Target not halted");
2574                 return ERROR_TARGET_NOT_HALTED;
2575         }
2576         buf[0] = 0;
2577         return ERROR_OK;
2578 }
2579
2580 static int sam3_page_read(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
2581 {
2582         uint32_t adr;
2583         int r;
2584
2585         adr = pagenum * pPrivate->page_size;
2586         adr += adr + pPrivate->base_address;
2587
2588         r = target_read_memory(pPrivate->pChip->target,
2589                         adr,
2590                         4,                                      /* THIS*MUST*BE* in 32bit values */
2591                         pPrivate->page_size / 4,
2592                         buf);
2593         if (r != ERROR_OK)
2594                 LOG_ERROR("SAM3: Flash program failed to read page phys address: 0x%08x",
2595                         (unsigned int)(adr));
2596         return r;
2597 }
2598
2599 /* The code below is basically this: */
2600 /* compiled with */
2601 /* arm-none-eabi-gcc -mthumb -mcpu = cortex-m3 -O9 -S ./foobar.c -o foobar.s */
2602 /*  */
2603 /* Only the *CPU* can write to the flash buffer. */
2604 /* the DAP cannot... so - we download this 28byte thing */
2605 /* Run the algorithm - (below) */
2606 /* to program the device */
2607 /*  */
2608 /* ======================================== */
2609 /* #include <stdint.h> */
2610 /*  */
2611 /* struct foo { */
2612 /*   uint32_t *dst; */
2613 /*   const uint32_t *src; */
2614 /*   int   n; */
2615 /*   volatile uint32_t *base; */
2616 /*   uint32_t   cmd; */
2617 /* }; */
2618 /*  */
2619 /*  */
2620 /* uint32_t sam3_function(struct foo *p) */
2621 /* { */
2622 /*   volatile uint32_t *v; */
2623 /*   uint32_t *d; */
2624 /*   const uint32_t *s; */
2625 /*   int   n; */
2626 /*   uint32_t r; */
2627 /*  */
2628 /*   d = p->dst; */
2629 /*   s = p->src; */
2630 /*   n = p->n; */
2631 /*  */
2632 /*   do { */
2633 /*     *d++ = *s++; */
2634 /*   } while (--n) */
2635 /*     ; */
2636 /*  */
2637 /*   v = p->base; */
2638 /*  */
2639 /*   v[ 1 ] = p->cmd; */
2640 /*   do { */
2641 /*     r = v[8/4]; */
2642 /*   } while (!(r&1)) */
2643 /*     ; */
2644 /*   return r; */
2645 /* } */
2646 /* ======================================== */
2647
2648 static const uint8_t
2649         sam3_page_write_opcodes[] = {
2650         /*  24 0000 0446                mov     r4, r0 */
2651         0x04, 0x46,
2652         /*  25 0002 6168                ldr     r1, [r4, #4] */
2653         0x61, 0x68,
2654         /*  26 0004 0068                ldr     r0, [r0, #0] */
2655         0x00, 0x68,
2656         /*  27 0006 A268                ldr     r2, [r4, #8] */
2657         0xa2, 0x68,
2658         /*  28                          @ lr needed for prologue */
2659         /*  29                  .L2: */
2660         /*  30 0008 51F8043B            ldr     r3, [r1], #4 */
2661         0x51, 0xf8, 0x04, 0x3b,
2662         /*  31 000c 12F1FF32            adds    r2, r2, #-1 */
2663         0x12, 0xf1, 0xff, 0x32,
2664         /*  32 0010 40F8043B            str     r3, [r0], #4 */
2665         0x40, 0xf8, 0x04, 0x3b,
2666         /*  33 0014 F8D1                bne     .L2 */
2667         0xf8, 0xd1,
2668         /*  34 0016 E268                ldr     r2, [r4, #12] */
2669         0xe2, 0x68,
2670         /*  35 0018 2369                ldr     r3, [r4, #16] */
2671         0x23, 0x69,
2672         /*  36 001a 5360                str     r3, [r2, #4] */
2673         0x53, 0x60,
2674         /*  37 001c 0832                adds    r2, r2, #8 */
2675         0x08, 0x32,
2676         /*  38                  .L4: */
2677         /*  39 001e 1068                ldr     r0, [r2, #0] */
2678         0x10, 0x68,
2679         /*  40 0020 10F0010F            tst     r0, #1 */
2680         0x10, 0xf0, 0x01, 0x0f,
2681         /*  41 0024 FBD0                beq     .L4 */
2682         0xfb, 0xd0,
2683         0x00, 0xBE                              /* bkpt #0 */
2684 };
2685
2686 static int sam3_page_write(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
2687 {
2688         uint32_t adr;
2689         uint32_t status;
2690         uint32_t fmr;   /* EEFC Flash Mode Register */
2691         int r;
2692
2693         adr = pagenum * pPrivate->page_size;
2694         adr += (adr + pPrivate->base_address);
2695
2696         /* Get flash mode register value */
2697         r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address, &fmr);
2698         if (r != ERROR_OK)
2699                 LOG_DEBUG("Error Read failed: read flash mode register");
2700
2701         /* Clear flash wait state field */
2702         fmr &= 0xfffff0ff;
2703
2704         /* set FWS (flash wait states) field in the FMR (flash mode register) */
2705         fmr |= (pPrivate->flash_wait_states << 8);
2706
2707         LOG_DEBUG("Flash Mode: 0x%08x", ((unsigned int)(fmr)));
2708         r = target_write_u32(pPrivate->pBank->target, pPrivate->controller_address, fmr);
2709         if (r != ERROR_OK)
2710                 LOG_DEBUG("Error Write failed: set flash mode register");
2711
2712         LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
2713         r = target_write_memory(pPrivate->pChip->target,
2714                         adr,
2715                         4,                                      /* THIS*MUST*BE* in 32bit values */
2716                         pPrivate->page_size / 4,
2717                         buf);
2718         if (r != ERROR_OK) {
2719                 LOG_ERROR("SAM3: Failed to write (buffer) page at phys address 0x%08x",
2720                         (unsigned int)(adr));
2721                 return r;
2722         }
2723
2724         r = EFC_PerformCommand(pPrivate,
2725                         /* send Erase & Write Page */
2726                         AT91C_EFC_FCMD_EWP,
2727                         pagenum,
2728                         &status);
2729
2730         if (r != ERROR_OK)
2731                 LOG_ERROR("SAM3: Error performing Erase & Write page @ phys address 0x%08x",
2732                         (unsigned int)(adr));
2733         if (status & (1 << 2)) {
2734                 LOG_ERROR("SAM3: Page @ Phys address 0x%08x is locked", (unsigned int)(adr));
2735                 return ERROR_FAIL;
2736         }
2737         if (status & (1 << 1)) {
2738                 LOG_ERROR("SAM3: Flash Command error @phys address 0x%08x", (unsigned int)(adr));
2739                 return ERROR_FAIL;
2740         }
2741         return ERROR_OK;
2742 }
2743
2744 static int sam3_write(struct flash_bank *bank,
2745         uint8_t *buffer,
2746         uint32_t offset,
2747         uint32_t count)
2748 {
2749         int n;
2750         unsigned page_cur;
2751         unsigned page_end;
2752         int r;
2753         unsigned page_offset;
2754         struct sam3_bank_private *pPrivate;
2755         uint8_t *pagebuffer;
2756
2757         /* incase we bail further below, set this to null */
2758         pagebuffer = NULL;
2759
2760         /* ignore dumb requests */
2761         if (count == 0) {
2762                 r = ERROR_OK;
2763                 goto done;
2764         }
2765
2766         if (bank->target->state != TARGET_HALTED) {
2767                 LOG_ERROR("Target not halted");
2768                 r = ERROR_TARGET_NOT_HALTED;
2769                 goto done;
2770         }
2771
2772         pPrivate = get_sam3_bank_private(bank);
2773         if (!(pPrivate->probed)) {
2774                 r = ERROR_FLASH_BANK_NOT_PROBED;
2775                 goto done;
2776         }
2777
2778         if ((offset + count) > pPrivate->size_bytes) {
2779                 LOG_ERROR("Flash write error - past end of bank");
2780                 LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
2781                         (unsigned int)(offset),
2782                         (unsigned int)(count),
2783                         (unsigned int)(pPrivate->size_bytes));
2784                 r = ERROR_FAIL;
2785                 goto done;
2786         }
2787
2788         pagebuffer = malloc(pPrivate->page_size);
2789         if (!pagebuffer) {
2790                 LOG_ERROR("No memory for %d Byte page buffer", (int)(pPrivate->page_size));
2791                 r = ERROR_FAIL;
2792                 goto done;
2793         }
2794
2795         /* what page do we start & end in? */
2796         page_cur = offset / pPrivate->page_size;
2797         page_end = (offset + count - 1) / pPrivate->page_size;
2798
2799         LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
2800         LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
2801
2802         /* Special case: all one page */
2803         /*  */
2804         /* Otherwise: */
2805         /*    (1) non-aligned start */
2806         /*    (2) body pages */
2807         /*    (3) non-aligned end. */
2808
2809         /* Handle special case - all one page. */
2810         if (page_cur == page_end) {
2811                 LOG_DEBUG("Special case, all in one page");
2812                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2813                 if (r != ERROR_OK)
2814                         goto done;
2815
2816                 page_offset = (offset & (pPrivate->page_size-1));
2817                 memcpy(pagebuffer + page_offset,
2818                         buffer,
2819                         count);
2820
2821                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2822                 if (r != ERROR_OK)
2823                         goto done;
2824                 r = ERROR_OK;
2825                 goto done;
2826         }
2827
2828         /* non-aligned start */
2829         page_offset = offset & (pPrivate->page_size - 1);
2830         if (page_offset) {
2831                 LOG_DEBUG("Not-Aligned start");
2832                 /* read the partial */
2833                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2834                 if (r != ERROR_OK)
2835                         goto done;
2836
2837                 /* over-write with new data */
2838                 n = (pPrivate->page_size - page_offset);
2839                 memcpy(pagebuffer + page_offset,
2840                         buffer,
2841                         n);
2842
2843                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2844                 if (r != ERROR_OK)
2845                         goto done;
2846
2847                 count  -= n;
2848                 offset += n;
2849                 buffer += n;
2850                 page_cur++;
2851         }
2852
2853         /* By checking that offset is correct here, we also
2854         fix a clang warning */
2855         assert(offset % pPrivate->page_size == 0);
2856
2857         /* intermediate large pages */
2858         /* also - the final *terminal* */
2859         /* if that terminal page is a full page */
2860         LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
2861                 (int)page_cur, (int)page_end, (unsigned int)(count));
2862
2863         while ((page_cur < page_end) &&
2864                         (count >= pPrivate->page_size)) {
2865                 r = sam3_page_write(pPrivate, page_cur, buffer);
2866                 if (r != ERROR_OK)
2867                         goto done;
2868                 count -= pPrivate->page_size;
2869                 buffer += pPrivate->page_size;
2870                 page_cur += 1;
2871         }
2872
2873         /* terminal partial page? */
2874         if (count) {
2875                 LOG_DEBUG("Terminal partial page, count = 0x%08x", (unsigned int)(count));
2876                 /* we have a partial page */
2877                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2878                 if (r != ERROR_OK)
2879                         goto done;
2880                                         /* data goes at start */
2881                 memcpy(pagebuffer, buffer, count);
2882                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2883                 if (r != ERROR_OK)
2884                         goto done;
2885                 buffer += count;
2886         }
2887         LOG_DEBUG("Done!");
2888         r = ERROR_OK;
2889 done:
2890         if (pagebuffer)
2891                 free(pagebuffer);
2892         return r;
2893 }
2894
2895 COMMAND_HANDLER(sam3_handle_info_command)
2896 {
2897         struct sam3_chip *pChip;
2898         pChip = get_current_sam3(CMD_CTX);
2899         if (!pChip)
2900                 return ERROR_OK;
2901
2902         unsigned x;
2903         int r;
2904
2905         /* bank0 must exist before we can do anything */
2906         if (pChip->details.bank[0].pBank == NULL) {
2907                 x = 0;
2908 need_define:
2909                 command_print(CMD_CTX,
2910                         "Please define bank %d via command: flash bank %s ... ",
2911                         x,
2912                         at91sam3_flash.name);
2913                 return ERROR_FAIL;
2914         }
2915
2916         /* if bank 0 is not probed, then probe it */
2917         if (!(pChip->details.bank[0].probed)) {
2918                 r = sam3_auto_probe(pChip->details.bank[0].pBank);
2919                 if (r != ERROR_OK)
2920                         return ERROR_FAIL;
2921         }
2922         /* above guarantees the "chip details" structure is valid */
2923         /* and thus, bank private areas are valid */
2924         /* and we have a SAM3 chip, what a concept! */
2925
2926         /* auto-probe other banks, 0 done above */
2927         for (x = 1; x < SAM3_MAX_FLASH_BANKS; x++) {
2928                 /* skip banks not present */
2929                 if (!(pChip->details.bank[x].present))
2930                         continue;
2931
2932                 if (pChip->details.bank[x].pBank == NULL)
2933                         goto need_define;
2934
2935                 if (pChip->details.bank[x].probed)
2936                         continue;
2937
2938                 r = sam3_auto_probe(pChip->details.bank[x].pBank);
2939                 if (r != ERROR_OK)
2940                         return r;
2941         }
2942
2943         r = sam3_GetInfo(pChip);
2944         if (r != ERROR_OK) {
2945                 LOG_DEBUG("Sam3Info, Failed %d", r);
2946                 return r;
2947         }
2948
2949         return ERROR_OK;
2950 }
2951
2952 COMMAND_HANDLER(sam3_handle_gpnvm_command)
2953 {
2954         unsigned x, v;
2955         int r, who;
2956         struct sam3_chip *pChip;
2957
2958         pChip = get_current_sam3(CMD_CTX);
2959         if (!pChip)
2960                 return ERROR_OK;
2961
2962         if (pChip->target->state != TARGET_HALTED) {
2963                 LOG_ERROR("sam3 - target not halted");
2964                 return ERROR_TARGET_NOT_HALTED;
2965         }
2966
2967         if (pChip->details.bank[0].pBank == NULL) {
2968                 command_print(CMD_CTX, "Bank0 must be defined first via: flash bank %s ...",
2969                         at91sam3_flash.name);
2970                 return ERROR_FAIL;
2971         }
2972         if (!pChip->details.bank[0].probed) {
2973                 r = sam3_auto_probe(pChip->details.bank[0].pBank);
2974                 if (r != ERROR_OK)
2975                         return r;
2976         }
2977
2978         switch (CMD_ARGC) {
2979                 default:
2980                         return ERROR_COMMAND_SYNTAX_ERROR;
2981                         break;
2982                 case 0:
2983                         goto showall;
2984                         break;
2985                 case 1:
2986                         who = -1;
2987                         break;
2988                 case 2:
2989                         if ((0 == strcmp(CMD_ARGV[0], "show")) && (0 == strcmp(CMD_ARGV[1], "all")))
2990                                 who = -1;
2991                         else {
2992                                 uint32_t v32;
2993                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], v32);
2994                                 who = v32;
2995                         }
2996                         break;
2997         }
2998
2999         if (0 == strcmp("show", CMD_ARGV[0])) {
3000                 if (who == -1) {
3001 showall:
3002                         r = ERROR_OK;
3003                         for (x = 0; x < pChip->details.n_gpnvms; x++) {
3004                                 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
3005                                 if (r != ERROR_OK)
3006                                         break;
3007                                 command_print(CMD_CTX, "sam3-gpnvm%u: %u", x, v);
3008                         }
3009                         return r;
3010                 }
3011                 if ((who >= 0) && (((unsigned)(who)) < pChip->details.n_gpnvms)) {
3012                         r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), who, &v);
3013                         command_print(CMD_CTX, "sam3-gpnvm%u: %u", who, v);
3014                         return r;
3015                 } else {
3016                         command_print(CMD_CTX, "sam3-gpnvm invalid GPNVM: %u", who);
3017                         return ERROR_COMMAND_SYNTAX_ERROR;
3018                 }
3019         }
3020
3021         if (who == -1) {
3022                 command_print(CMD_CTX, "Missing GPNVM number");
3023                 return ERROR_COMMAND_SYNTAX_ERROR;
3024         }
3025
3026         if (0 == strcmp("set", CMD_ARGV[0]))
3027                 r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
3028         else if ((0 == strcmp("clr", CMD_ARGV[0])) ||
3029                  (0 == strcmp("clear", CMD_ARGV[0])))                   /* quietly accept both */
3030                 r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
3031         else {
3032                 command_print(CMD_CTX, "Unknown command: %s", CMD_ARGV[0]);
3033                 r = ERROR_COMMAND_SYNTAX_ERROR;
3034         }
3035         return r;
3036 }
3037
3038 COMMAND_HANDLER(sam3_handle_slowclk_command)
3039 {
3040         struct sam3_chip *pChip;
3041
3042         pChip = get_current_sam3(CMD_CTX);
3043         if (!pChip)
3044                 return ERROR_OK;
3045
3046         switch (CMD_ARGC) {
3047                 case 0:
3048                         /* show */
3049                         break;
3050                 case 1:
3051                 {
3052                         /* set */
3053                         uint32_t v;
3054                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], v);
3055                         if (v > 200000) {
3056                                 /* absurd slow clock of 200Khz? */
3057                                 command_print(CMD_CTX, "Absurd/illegal slow clock freq: %d\n", (int)(v));
3058                                 return ERROR_COMMAND_SYNTAX_ERROR;
3059                         }
3060                         pChip->cfg.slow_freq = v;
3061                         break;
3062                 }
3063                 default:
3064                         /* error */
3065                         command_print(CMD_CTX, "Too many parameters");
3066                         return ERROR_COMMAND_SYNTAX_ERROR;
3067                         break;
3068         }
3069         command_print(CMD_CTX, "Slowclk freq: %d.%03dkhz",
3070                 (int)(pChip->cfg.slow_freq / 1000),
3071                 (int)(pChip->cfg.slow_freq % 1000));
3072         return ERROR_OK;
3073 }
3074
3075 static const struct command_registration at91sam3_exec_command_handlers[] = {
3076         {
3077                 .name = "gpnvm",
3078                 .handler = sam3_handle_gpnvm_command,
3079                 .mode = COMMAND_EXEC,
3080                 .usage = "[('clr'|'set'|'show') bitnum]",
3081                 .help = "Without arguments, shows all bits in the gpnvm "
3082                         "register.  Otherwise, clears, sets, or shows one "
3083                         "General Purpose Non-Volatile Memory (gpnvm) bit.",
3084         },
3085         {
3086                 .name = "info",
3087                 .handler = sam3_handle_info_command,
3088                 .mode = COMMAND_EXEC,
3089                 .help = "Print information about the current at91sam3 chip"
3090                         "and its flash configuration.",
3091         },
3092         {
3093                 .name = "slowclk",
3094                 .handler = sam3_handle_slowclk_command,
3095                 .mode = COMMAND_EXEC,
3096                 .usage = "[clock_hz]",
3097                 .help = "Display or set the slowclock frequency "
3098                         "(default 32768 Hz).",
3099         },
3100         COMMAND_REGISTRATION_DONE
3101 };
3102 static const struct command_registration at91sam3_command_handlers[] = {
3103         {
3104                 .name = "at91sam3",
3105                 .mode = COMMAND_ANY,
3106                 .help = "at91sam3 flash command group",
3107                 .usage = "",
3108                 .chain = at91sam3_exec_command_handlers,
3109         },
3110         COMMAND_REGISTRATION_DONE
3111 };
3112
3113 struct flash_driver at91sam3_flash = {
3114         .name = "at91sam3",
3115         .commands = at91sam3_command_handlers,
3116         .flash_bank_command = sam3_flash_bank_command,
3117         .erase = sam3_erase,
3118         .protect = sam3_protect,
3119         .write = sam3_write,
3120         .read = default_flash_read,
3121         .probe = sam3_probe,
3122         .auto_probe = sam3_auto_probe,
3123         .erase_check = sam3_erase_check,
3124         .protect_check = sam3_protect_check,
3125         .info = sam3_info,
3126 };