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