]> git.sur5r.net Git - openocd/blob - src/flash/nor/at91sam4.c
at91sam4 Flash: Added identification of atsam4n's
[openocd] / src / flash / nor / at91sam4.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  *   Copyright (C) 2011 by Olivier Schonken, Jim Norris                    *
9  *   (at91sam3x* & at91sam4 support)*                                      *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS for A PARTICULAR PURPOSE.  See the         *
19  *   GNU General public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General public License     *
22  *   along with this program; if not, write to the                         *
23  *   Free Software Foundation, Inc.,                                       *
24  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
25 ****************************************************************************/
26
27 /* Some of the the lower level code was based on code supplied by
28  * ATMEL under this copyright. */
29
30 /* BEGIN ATMEL COPYRIGHT */
31 /* ----------------------------------------------------------------------------
32  *         ATMEL Microcontroller Software Support
33  * ----------------------------------------------------------------------------
34  * Copyright (c) 2009, Atmel Corporation
35  *
36  * All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions are met:
40  *
41  * - Redistributions of source code must retain the above copyright notice,
42  * this list of conditions and the disclaimer below.
43  *
44  * Atmel's name may not be used to endorse or promote products derived from
45  * this software without specific prior written permission.
46  *
47  * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
48  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
49  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
50  * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
51  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
52  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
53  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
54  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
55  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
56  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
57  * ----------------------------------------------------------------------------
58  */
59 /* END ATMEL COPYRIGHT */
60
61 #ifdef HAVE_CONFIG_H
62 #include "config.h"
63 #endif
64
65 #include "imp.h"
66 #include <helper/time_support.h>
67
68 #define REG_NAME_WIDTH  (12)
69
70 /* at91sam4s/at91sam4e series (has always one flash bank)*/
71 #define FLASH_BANK_BASE_S   0x00400000
72
73 /* at91sam4sd series (two one flash banks), first bank address */
74 #define FLASH_BANK0_BASE_SD FLASH_BANK_BASE_S
75 /* at91sam4sd16x, second bank address */
76 #define FLASH_BANK1_BASE_1024K_SD (FLASH_BANK0_BASE_SD+(1024*1024/2))
77 /* at91sam4sd32x, second bank address */
78 #define FLASH_BANK1_BASE_2048K_SD (FLASH_BANK0_BASE_SD+(2048*1024/2))
79
80 #define         AT91C_EFC_FCMD_GETD                 (0x0)       /* (EFC) Get Flash Descriptor */
81 #define         AT91C_EFC_FCMD_WP                   (0x1)       /* (EFC) Write Page */
82 #define         AT91C_EFC_FCMD_WPL                  (0x2)       /* (EFC) Write Page and Lock */
83 #define         AT91C_EFC_FCMD_EWP                  (0x3)       /* (EFC) Erase Page and Write Page */
84 #define         AT91C_EFC_FCMD_EWPL                 (0x4)       /* (EFC) Erase Page and Write Page then Lock */
85 #define         AT91C_EFC_FCMD_EA                   (0x5)       /* (EFC) Erase All */
86 /* cmd6 is not present in the at91sam4u4/2/1 data sheet table 19-2 */
87 /* #define      AT91C_EFC_FCMD_EPL                  (0x6) // (EFC) Erase plane? */
88 #define                 AT91C_EFC_FCMD_EPA                  (0x7)     /* (EFC) Erase pages */
89 #define         AT91C_EFC_FCMD_SLB                  (0x8)       /* (EFC) Set Lock Bit */
90 #define         AT91C_EFC_FCMD_CLB                  (0x9)       /* (EFC) Clear Lock Bit */
91 #define         AT91C_EFC_FCMD_GLB                  (0xA)       /* (EFC) Get Lock Bit */
92 #define         AT91C_EFC_FCMD_SFB                  (0xB)       /* (EFC) Set Fuse Bit */
93 #define         AT91C_EFC_FCMD_CFB                  (0xC)       /* (EFC) Clear Fuse Bit */
94 #define         AT91C_EFC_FCMD_GFB                  (0xD)       /* (EFC) Get Fuse Bit */
95 #define         AT91C_EFC_FCMD_STUI                 (0xE)       /* (EFC) Start Read Unique ID */
96 #define         AT91C_EFC_FCMD_SPUI                 (0xF)       /* (EFC) Stop Read Unique ID */
97
98 #define  offset_EFC_FMR   0
99 #define  offset_EFC_FCR   4
100 #define  offset_EFC_FSR   8
101 #define  offset_EFC_FRR   12
102
103 extern struct flash_driver at91sam4_flash;
104
105 static float _tomhz(uint32_t freq_hz)
106 {
107         float f;
108
109         f = ((float)(freq_hz)) / 1000000.0;
110         return f;
111 }
112
113 /* How the chip is configured. */
114 struct sam4_cfg {
115         uint32_t unique_id[4];
116
117         uint32_t slow_freq;
118         uint32_t rc_freq;
119         uint32_t mainosc_freq;
120         uint32_t plla_freq;
121         uint32_t mclk_freq;
122         uint32_t cpu_freq;
123         uint32_t fclk_freq;
124         uint32_t pclk0_freq;
125         uint32_t pclk1_freq;
126         uint32_t pclk2_freq;
127
128
129 #define SAM4_CHIPID_CIDR          (0x400E0740)
130         uint32_t CHIPID_CIDR;
131 #define SAM4_CHIPID_EXID          (0x400E0744)
132         uint32_t CHIPID_EXID;
133
134 #define SAM4_PMC_BASE             (0x400E0400)
135 #define SAM4_PMC_SCSR             (SAM4_PMC_BASE + 0x0008)
136         uint32_t PMC_SCSR;
137 #define SAM4_PMC_PCSR             (SAM4_PMC_BASE + 0x0018)
138         uint32_t PMC_PCSR;
139 #define SAM4_CKGR_UCKR            (SAM4_PMC_BASE + 0x001c)
140         uint32_t CKGR_UCKR;
141 #define SAM4_CKGR_MOR             (SAM4_PMC_BASE + 0x0020)
142         uint32_t CKGR_MOR;
143 #define SAM4_CKGR_MCFR            (SAM4_PMC_BASE + 0x0024)
144         uint32_t CKGR_MCFR;
145 #define SAM4_CKGR_PLLAR           (SAM4_PMC_BASE + 0x0028)
146         uint32_t CKGR_PLLAR;
147 #define SAM4_PMC_MCKR             (SAM4_PMC_BASE + 0x0030)
148         uint32_t PMC_MCKR;
149 #define SAM4_PMC_PCK0             (SAM4_PMC_BASE + 0x0040)
150         uint32_t PMC_PCK0;
151 #define SAM4_PMC_PCK1             (SAM4_PMC_BASE + 0x0044)
152         uint32_t PMC_PCK1;
153 #define SAM4_PMC_PCK2             (SAM4_PMC_BASE + 0x0048)
154         uint32_t PMC_PCK2;
155 #define SAM4_PMC_SR               (SAM4_PMC_BASE + 0x0068)
156         uint32_t PMC_SR;
157 #define SAM4_PMC_IMR              (SAM4_PMC_BASE + 0x006c)
158         uint32_t PMC_IMR;
159 #define SAM4_PMC_FSMR             (SAM4_PMC_BASE + 0x0070)
160         uint32_t PMC_FSMR;
161 #define SAM4_PMC_FSPR             (SAM4_PMC_BASE + 0x0074)
162         uint32_t PMC_FSPR;
163 };
164
165 struct sam4_bank_private {
166         int probed;
167         /* DANGER: THERE ARE DRAGONS HERE.. */
168         /* NOTE: If you add more 'ghost' pointers */
169         /* be aware that you must *manually* update */
170         /* these pointers in the function sam4_GetDetails() */
171         /* See the comment "Here there be dragons" */
172
173         /* so we can find the chip we belong to */
174         struct sam4_chip *pChip;
175         /* so we can find the original bank pointer */
176         struct flash_bank *pBank;
177         unsigned bank_number;
178         uint32_t controller_address;
179         uint32_t base_address;
180         uint32_t flash_wait_states;
181         bool present;
182         unsigned size_bytes;
183         unsigned nsectors;
184         unsigned sector_size;
185         unsigned page_size;
186 };
187
188 struct sam4_chip_details {
189         /* THERE ARE DRAGONS HERE.. */
190         /* note: If you add pointers here */
191         /* be careful about them as they */
192         /* may need to be updated inside */
193         /* the function: "sam4_GetDetails() */
194         /* which copy/overwrites the */
195         /* 'runtime' copy of this structure */
196         uint32_t chipid_cidr;
197         const char *name;
198
199         unsigned n_gpnvms;
200 #define SAM4_N_NVM_BITS 3
201         unsigned gpnvm[SAM4_N_NVM_BITS];
202         unsigned total_flash_size;
203         unsigned total_sram_size;
204         unsigned n_banks;
205 #define SAM4_MAX_FLASH_BANKS 2
206         /* these are "initialized" from the global const data */
207         struct sam4_bank_private bank[SAM4_MAX_FLASH_BANKS];
208 };
209
210 struct sam4_chip {
211         struct sam4_chip *next;
212         int probed;
213
214         /* this is "initialized" from the global const structure */
215         struct sam4_chip_details details;
216         struct target *target;
217         struct sam4_cfg cfg;
218 };
219
220
221 struct sam4_reg_list {
222         uint32_t address;  size_t struct_offset; const char *name;
223         void (*explain_func)(struct sam4_chip *pInfo);
224 };
225
226 static struct sam4_chip *all_sam4_chips;
227
228 static struct sam4_chip *get_current_sam4(struct command_context *cmd_ctx)
229 {
230         struct target *t;
231         static struct sam4_chip *p;
232
233         t = get_current_target(cmd_ctx);
234         if (!t) {
235                 command_print(cmd_ctx, "No current target?");
236                 return NULL;
237         }
238
239         p = all_sam4_chips;
240         if (!p) {
241                 /* this should not happen */
242                 /* the command is not registered until the chip is created? */
243                 command_print(cmd_ctx, "No SAM4 chips exist?");
244                 return NULL;
245         }
246
247         while (p) {
248                 if (p->target == t)
249                         return p;
250                 p = p->next;
251         }
252         command_print(cmd_ctx, "Cannot find SAM4 chip?");
253         return NULL;
254 }
255
256 /*The actual sector size of the SAM4S flash memory is 65536 bytes. 16 sectors for a 1024KB device*/
257 /*The lockregions are 8KB per lock region, with a 1024KB device having 128 lock regions. */
258 /*For the best results, nsectors are thus set to the amount of lock regions, and the sector_size*/
259 /*set to the lock region size.  Page erases are used to erase 8KB sections when programming*/
260
261 /* these are used to *initialize* the "pChip->details" structure. */
262 static const struct sam4_chip_details all_sam4_details[] = {
263
264         /* Start at91sam4e* series */
265         /*atsam4e16e - LQFP144/LFBGA144*/
266         {
267                 .chipid_cidr    = 0xA3CC0CE0,
268                 .name           = "at91sam4e16e",
269                 .total_flash_size     = 1024 * 1024,
270                 .total_sram_size      = 128 * 1024,
271                 .n_gpnvms       = 2,
272                 .n_banks        = 1,
273                 {
274 /*              .bank[0] = {*/
275                   {
276                         .probed = 0,
277                         .pChip  = NULL,
278                         .pBank  = NULL,
279                         .bank_number = 0,
280                         .base_address = FLASH_BANK_BASE_S,
281                         .controller_address = 0x400e0a00,
282                         .flash_wait_states = 6, /* workaround silicon bug */
283                         .present = 1,
284                         .size_bytes =  1024 * 1024,
285                         .nsectors   =  128,
286                         .sector_size = 8192,
287                         .page_size   = 512,
288                   },
289 /*              .bank[1] = {*/
290                   {
291                         .present = 0,
292                         .probed = 0,
293                         .bank_number = 1,
294
295                   },
296                 },
297         },
298
299         /* Start at91sam4n* series */
300         /*atsam4n8a - LQFP48/QFN48*/
301         {
302                 .chipid_cidr    = 0x293B0AE0,
303                 .name           = "at91sam4n8a",
304                 .total_flash_size     = 512 * 1024,
305                 .total_sram_size      = 64 * 1024,
306                 .n_gpnvms       = 2,
307                 .n_banks        = 1,
308                 {
309 /*              .bank[0] = {*/
310                   {
311                         .probed = 0,
312                         .pChip  = NULL,
313                         .pBank  = NULL,
314                         .bank_number = 0,
315                         .base_address = FLASH_BANK_BASE_S,
316                         .controller_address = 0x400e0a00,
317                         .flash_wait_states = 6, /* workaround silicon bug */
318                         .present = 1,
319                         .size_bytes =  512 * 1024,
320                         .nsectors   =  64,
321                         .sector_size = 8192,
322                         .page_size   = 512,
323                   },
324 /*              .bank[1] = {*/
325                   {
326                         .present = 0,
327                         .probed = 0,
328                         .bank_number = 1,
329
330                   },
331                 },
332         },
333         /*atsam4n8b - LQFP64/QFN64*/
334         {
335                 .chipid_cidr    = 0x294B0AE0,
336                 .name           = "at91sam4n8b",
337                 .total_flash_size     = 512 * 1024,
338                 .total_sram_size      = 64 * 1024,
339                 .n_gpnvms       = 2,
340                 .n_banks        = 1,
341                 {
342 /*              .bank[0] = {*/
343                   {
344                         .probed = 0,
345                         .pChip  = NULL,
346                         .pBank  = NULL,
347                         .bank_number = 0,
348                         .base_address = FLASH_BANK_BASE_S,
349                         .controller_address = 0x400e0a00,
350                         .flash_wait_states = 6, /* workaround silicon bug */
351                         .present = 1,
352                         .size_bytes =  512 * 1024,
353                         .nsectors   =  64,
354                         .sector_size = 8192,
355                         .page_size   = 512,
356                   },
357 /*              .bank[1] = {*/
358                   {
359                         .present = 0,
360                         .probed = 0,
361                         .bank_number = 1,
362
363                   },
364                 },
365         },
366         /*atsam4n8c - LQFP100/TFBGA100/VFBGA100*/
367         {
368                 .chipid_cidr    = 0x295B0AE0,
369                 .name           = "at91sam4n8c",
370                 .total_flash_size     = 512 * 1024,
371                 .total_sram_size      = 64 * 1024,
372                 .n_gpnvms       = 2,
373                 .n_banks        = 1,
374                 {
375 /*              .bank[0] = {*/
376                   {
377                         .probed = 0,
378                         .pChip  = NULL,
379                         .pBank  = NULL,
380                         .bank_number = 0,
381                         .base_address = FLASH_BANK_BASE_S,
382                         .controller_address = 0x400e0a00,
383                         .flash_wait_states = 6, /* workaround silicon bug */
384                         .present = 1,
385                         .size_bytes =  512 * 1024,
386                         .nsectors   =  64,
387                         .sector_size = 8192,
388                         .page_size   = 512,
389                   },
390 /*              .bank[1] = {*/
391                   {
392                         .present = 0,
393                         .probed = 0,
394                         .bank_number = 1,
395
396                   },
397                 },
398         },
399         /*atsam4n16b - LQFP64/QFN64*/
400         {
401                 .chipid_cidr    = 0x29460CE0,
402                 .name           = "at91sam4n16b",
403                 .total_flash_size     = 1024 * 1024,
404                 .total_sram_size      = 80 * 1024,
405                 .n_gpnvms       = 2,
406                 .n_banks        = 1,
407                 {
408 /*              .bank[0] = {*/
409                   {
410                         .probed = 0,
411                         .pChip  = NULL,
412                         .pBank  = NULL,
413                         .bank_number = 0,
414                         .base_address = FLASH_BANK_BASE_S,
415                         .controller_address = 0x400e0a00,
416                         .flash_wait_states = 6, /* workaround silicon bug */
417                         .present = 1,
418                         .size_bytes =  1024 * 1024,
419                         .nsectors   =  128,
420                         .sector_size = 8192,
421                         .page_size   = 512,
422                   },
423 /*              .bank[1] = {*/
424                   {
425                         .present = 0,
426                         .probed = 0,
427                         .bank_number = 1,
428
429                   },
430                 },
431         },
432         /*atsam4n16c - LQFP100/TFBGA100/VFBGA100*/
433         {
434                 .chipid_cidr    = 0x29560CE0,
435                 .name           = "at91sam4n16c",
436                 .total_flash_size     = 1024 * 1024,
437                 .total_sram_size      = 80 * 1024,
438                 .n_gpnvms       = 2,
439                 .n_banks        = 1,
440                 {
441 /*              .bank[0] = {*/
442                   {
443                         .probed = 0,
444                         .pChip  = NULL,
445                         .pBank  = NULL,
446                         .bank_number = 0,
447                         .base_address = FLASH_BANK_BASE_S,
448                         .controller_address = 0x400e0a00,
449                         .flash_wait_states = 6, /* workaround silicon bug */
450                         .present = 1,
451                         .size_bytes =  1024 * 1024,
452                         .nsectors   =  128,
453                         .sector_size = 8192,
454                         .page_size   = 512,
455                   },
456 /*              .bank[1] = {*/
457                   {
458                         .present = 0,
459                         .probed = 0,
460                         .bank_number = 1,
461
462                   },
463                 },
464         },
465
466         /* Start at91sam4s* series */
467         /*atsam4s16c - LQFP100/BGA100*/
468         {
469                 .chipid_cidr    = 0x28AC0CE0,
470                 .name           = "at91sam4s16c",
471                 .total_flash_size     = 1024 * 1024,
472                 .total_sram_size      = 128 * 1024,
473                 .n_gpnvms       = 2,
474                 .n_banks        = 1,
475                 {
476 /*              .bank[0] = {*/
477                   {
478                         .probed = 0,
479                         .pChip  = NULL,
480                         .pBank  = NULL,
481                         .bank_number = 0,
482                         .base_address = FLASH_BANK_BASE_S,
483                         .controller_address = 0x400e0a00,
484                         .flash_wait_states = 6, /* workaround silicon bug */
485                         .present = 1,
486                         .size_bytes =  1024 * 1024,
487                         .nsectors   =  128,
488                         .sector_size = 8192,
489                         .page_size   = 512,
490                   },
491 /*              .bank[1] = {*/
492                   {
493                         .present = 0,
494                         .probed = 0,
495                         .bank_number = 1,
496
497                   },
498                 },
499         },
500         /*atsam4s16b - LQFP64/QFN64*/
501         {
502                 .chipid_cidr    = 0x289C0CE0,
503                 .name           = "at91sam4s16b",
504                 .total_flash_size     = 1024 * 1024,
505                 .total_sram_size      = 128 * 1024,
506                 .n_gpnvms       = 2,
507                 .n_banks        = 1,
508                 {
509 /*              .bank[0] = {*/
510                   {
511                         .probed = 0,
512                         .pChip  = NULL,
513                         .pBank  = NULL,
514                         .bank_number = 0,
515                         .base_address = FLASH_BANK_BASE_S,
516                         .controller_address = 0x400e0a00,
517                         .flash_wait_states = 6, /* workaround silicon bug */
518                         .present = 1,
519                         .size_bytes =  1024 * 1024,
520                         .nsectors   =  128,
521                         .sector_size = 8192,
522                         .page_size   = 512,
523                   },
524 /*              .bank[1] = {*/
525                   {
526                         .present = 0,
527                         .probed = 0,
528                         .bank_number = 1,
529
530                   },
531                 },
532         },
533         /*atsam4sa16b - LQFP64/QFN64*/
534         {
535                 .chipid_cidr    = 0x28970CE0,
536                 .name           = "at91sam4sa16b",
537                 .total_flash_size     = 1024 * 1024,
538                 .total_sram_size      = 160 * 1024,
539                 .n_gpnvms       = 2,
540                 .n_banks        = 1,
541                 {
542 /*              .bank[0] = {*/
543                   {
544                         .probed = 0,
545                         .pChip  = NULL,
546                         .pBank  = NULL,
547                         .bank_number = 0,
548                         .base_address = FLASH_BANK_BASE_S,
549                         .controller_address = 0x400e0a00,
550                         .flash_wait_states = 6, /* workaround silicon bug */
551                         .present = 1,
552                         .size_bytes =  1024 * 1024,
553                         .nsectors   =  128,
554                         .sector_size = 8192,
555                         .page_size   = 512,
556                   },
557 /*              .bank[1] = {*/
558                   {
559                         .present = 0,
560                         .probed = 0,
561                         .bank_number = 1,
562
563                   },
564                 },
565         },
566         /*atsam4s16a - LQFP48/QFN48*/
567         {
568                 .chipid_cidr    = 0x288C0CE0,
569                 .name           = "at91sam4s16a",
570                 .total_flash_size     = 1024 * 1024,
571                 .total_sram_size      = 128 * 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 =  1024 * 1024,
586                         .nsectors   =  128,
587                         .sector_size = 8192,
588                         .page_size   = 512,
589                   },
590 /*              .bank[1] = {*/
591                   {
592                         .present = 0,
593                         .probed = 0,
594                         .bank_number = 1,
595
596                   },
597                 },
598         },
599         /*atsam4s8c - LQFP100/BGA100*/
600         {
601                 .chipid_cidr    = 0x28AC0AE0,
602                 .name           = "at91sam4s8c",
603                 .total_flash_size     = 512 * 1024,
604                 .total_sram_size      = 128 * 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 =  512 * 1024,
619                         .nsectors   =  64,
620                         .sector_size = 8192,
621                         .page_size   = 512,
622                   },
623 /*              .bank[1] = {*/
624                   {
625                         .present = 0,
626                         .probed = 0,
627                         .bank_number = 1,
628
629                   },
630                 },
631         },
632         /*atsam4s8b - LQFP64/BGA64*/
633         {
634                 .chipid_cidr    = 0x289C0AE0,
635                 .name           = "at91sam4s8b",
636                 .total_flash_size     = 512 * 1024,
637                 .total_sram_size      = 128 * 1024,
638                 .n_gpnvms       = 2,
639                 .n_banks        = 1,
640                 {
641 /*              .bank[0] = {*/
642                   {
643                         .probed = 0,
644                         .pChip  = NULL,
645                         .pBank  = NULL,
646                         .bank_number = 0,
647                         .base_address = FLASH_BANK_BASE_S,
648                         .controller_address = 0x400e0a00,
649                         .flash_wait_states = 6, /* workaround silicon bug */
650                         .present = 1,
651                         .size_bytes =  512 * 1024,
652                         .nsectors   =  64,
653                         .sector_size = 8192,
654                         .page_size   = 512,
655                   },
656 /*              .bank[1] = {*/
657                   {
658                         .present = 0,
659                         .probed = 0,
660                         .bank_number = 1,
661
662                   },
663                 },
664         },
665         /*atsam4s8a - LQFP48/BGA48*/
666         {
667                 .chipid_cidr    = 0x288C0AE0,
668                 .name           = "at91sam4s8a",
669                 .total_flash_size     = 512 * 1024,
670                 .total_sram_size      = 128 * 1024,
671                 .n_gpnvms       = 2,
672                 .n_banks        = 1,
673                 {
674 /*              .bank[0] = {*/
675                   {
676                         .probed = 0,
677                         .pChip  = NULL,
678                         .pBank  = NULL,
679                         .bank_number = 0,
680                         .base_address = FLASH_BANK_BASE_S,
681                         .controller_address = 0x400e0a00,
682                         .flash_wait_states = 6, /* workaround silicon bug */
683                         .present = 1,
684                         .size_bytes =  512 * 1024,
685                         .nsectors   =  64,
686                         .sector_size = 8192,
687                         .page_size   = 512,
688                   },
689 /*              .bank[1] = {*/
690                   {
691                         .present = 0,
692                         .probed = 0,
693                         .bank_number = 1,
694
695                   },
696                 },
697         },
698
699         /*atsam4s4a - LQFP48/BGA48*/
700         {
701                 .chipid_cidr    = 0x288b09e0,
702                 .name           = "at91sam4s4a",
703                 .total_flash_size     = 256 * 1024,
704                 .total_sram_size      = 64 * 1024,
705                 .n_gpnvms       = 2,
706                 .n_banks        = 1,
707                 {
708 /*              .bank[0] = {*/
709                   {
710                         .probed = 0,
711                         .pChip  = NULL,
712                         .pBank  = NULL,
713                         .bank_number = 0,
714                         .base_address = FLASH_BANK_BASE_S,
715                         .controller_address = 0x400e0a00,
716                         .flash_wait_states = 6, /* workaround silicon bug */
717                         .present = 1,
718                         .size_bytes =  256 * 1024,
719                         .nsectors   =  32,
720                         .sector_size = 8192,
721                         .page_size   = 512,
722                   },
723 /*              .bank[1] = {*/
724                   {
725                         .present = 0,
726                         .probed = 0,
727                         .bank_number = 1,
728
729                   },
730                 },
731         },
732
733         /*at91sam4sd32c*/
734         {
735                 .chipid_cidr    = 0x29a70ee0,
736                 .name           = "at91sam4sd32c",
737                 .total_flash_size     = 2048 * 1024,
738                 .total_sram_size      = 160 * 1024,
739                 .n_gpnvms       = 3,
740                 .n_banks        = 2,
741
742 /*              .bank[0] = { */
743                 {
744                         {
745                                 .probed = 0,
746                                 .pChip  = NULL,
747                                 .pBank  = NULL,
748                                 .bank_number = 0,
749                                 .base_address = FLASH_BANK0_BASE_SD,
750                                 .controller_address = 0x400e0a00,
751                                 .flash_wait_states = 6, /* workaround silicon bug */
752                                 .present = 1,
753                                 .size_bytes =  1024 * 1024,
754                                 .nsectors   =  128,
755                                 .sector_size = 8192,
756                                 .page_size   = 512,
757                         },
758
759 /*              .bank[1] = { */
760                         {
761                                 .probed = 0,
762                                 .pChip  = NULL,
763                                 .pBank  = NULL,
764                                 .bank_number = 1,
765                                 .base_address = FLASH_BANK1_BASE_2048K_SD,
766                                 .controller_address = 0x400e0c00,
767                                 .flash_wait_states = 6, /* workaround silicon bug */
768                                 .present = 1,
769                                 .size_bytes =  1024 * 1024,
770                                 .nsectors   =  128,
771                                 .sector_size = 8192,
772                                 .page_size   = 512,
773                         },
774                 },
775         },
776
777         /*at91sam4sd16c*/
778         {
779                 .chipid_cidr    = 0x29a70ce0,
780                 .name           = "at91sam4sd16c",
781                 .total_flash_size     = 1024 * 1024,
782                 .total_sram_size      = 160 * 1024,
783                 .n_gpnvms       = 3,
784                 .n_banks        = 2,
785
786 /*              .bank[0] = { */
787                 {
788                         {
789                                 .probed = 0,
790                                 .pChip  = NULL,
791                                 .pBank  = NULL,
792                                 .bank_number = 0,
793                                 .base_address = FLASH_BANK0_BASE_SD,
794                                 .controller_address = 0x400e0a00,
795                                 .flash_wait_states = 6, /* workaround silicon bug */
796                                 .present = 1,
797                                 .size_bytes =  512 * 1024,
798                                 .nsectors   =  64,
799                                 .sector_size = 8192,
800                                 .page_size   = 512,
801                         },
802
803 /*              .bank[1] = { */
804                         {
805                                 .probed = 0,
806                                 .pChip  = NULL,
807                                 .pBank  = NULL,
808                                 .bank_number = 1,
809                                 .base_address = FLASH_BANK1_BASE_1024K_SD,
810                                 .controller_address = 0x400e0c00,
811                                 .flash_wait_states = 6, /* workaround silicon bug */
812                                 .present = 1,
813                                 .size_bytes =  512 * 1024,
814                                 .nsectors   =  64,
815                                 .sector_size = 8192,
816                                 .page_size   = 512,
817                         },
818                 },
819         },
820
821         /*at91sam4sa16c*/
822         {
823                 .chipid_cidr    = 0x28a70ce0,
824                 .name           = "at91sam4sa16c",
825                 .total_flash_size     = 1024 * 1024,
826                 .total_sram_size      = 160 * 1024,
827                 .n_gpnvms       = 3,
828                 .n_banks        = 2,
829
830 /*              .bank[0] = { */
831                 {
832                         {
833                                 .probed = 0,
834                                 .pChip  = NULL,
835                                 .pBank  = NULL,
836                                 .bank_number = 0,
837                                 .base_address = FLASH_BANK0_BASE_SD,
838                                 .controller_address = 0x400e0a00,
839                                 .flash_wait_states = 6, /* workaround silicon bug */
840                                 .present = 1,
841                                 .size_bytes =  512 * 1024,
842                                 .nsectors   =  64,
843                                 .sector_size = 8192,
844                                 .page_size   = 512,
845                         },
846
847 /*              .bank[1] = { */
848                         {
849                                 .probed = 0,
850                                 .pChip  = NULL,
851                                 .pBank  = NULL,
852                                 .bank_number = 1,
853                                 .base_address = FLASH_BANK1_BASE_1024K_SD,
854                                 .controller_address = 0x400e0c00,
855                                 .flash_wait_states = 6, /* workaround silicon bug */
856                                 .present = 1,
857                                 .size_bytes =  512 * 1024,
858                                 .nsectors   =  64,
859                                 .sector_size = 8192,
860                                 .page_size   = 512,
861                         },
862                 },
863         },
864
865         /* at91samg53n19 */
866         {
867                 .chipid_cidr    = 0x247e0ae0,
868                 .name           = "at91samg53n19",
869                 .total_flash_size     = 512 * 1024,
870                 .total_sram_size      = 96 * 1024,
871                 .n_gpnvms       = 2,
872                 .n_banks        = 1,
873
874 /*              .bank[0] = {*/
875                 {
876                         {
877                                 .probed = 0,
878                                 .pChip  = NULL,
879                                 .pBank  = NULL,
880                                 .bank_number = 0,
881                                 .base_address = FLASH_BANK_BASE_S,
882                                 .controller_address = 0x400e0a00,
883                                 .flash_wait_states = 6, /* workaround silicon bug */
884                                 .present = 1,
885                                 .size_bytes =  512 * 1024,
886                                 .nsectors   =  64,
887                                 .sector_size = 8192,
888                                 .page_size   = 512,
889                         },
890 /*              .bank[1] = {*/
891                   {
892                         .present = 0,
893                         .probed = 0,
894                         .bank_number = 1,
895
896                   },
897                 }
898         },
899
900         /* terminate */
901         {
902                 .chipid_cidr    = 0,
903                 .name                   = NULL,
904         }
905 };
906
907 /* Globals above */
908 /***********************************************************************
909  **********************************************************************
910  **********************************************************************
911  **********************************************************************
912  **********************************************************************
913  **********************************************************************/
914 /* *ATMEL* style code - from the SAM4 driver code */
915
916 /**
917  * Get the current status of the EEFC and
918  * the value of some status bits (LOCKE, PROGE).
919  * @param pPrivate - info about the bank
920  * @param v        - result goes here
921  */
922 static int EFC_GetStatus(struct sam4_bank_private *pPrivate, uint32_t *v)
923 {
924         int r;
925         r = target_read_u32(pPrivate->pChip->target,
926                         pPrivate->controller_address + offset_EFC_FSR,
927                         v);
928         LOG_DEBUG("Status: 0x%08x (lockerror: %d, cmderror: %d, ready: %d)",
929                 (unsigned int)(*v),
930                 ((unsigned int)((*v >> 2) & 1)),
931                 ((unsigned int)((*v >> 1) & 1)),
932                 ((unsigned int)((*v >> 0) & 1)));
933
934         return r;
935 }
936
937 /**
938  * Get the result of the last executed command.
939  * @param pPrivate - info about the bank
940  * @param v        - result goes here
941  */
942 static int EFC_GetResult(struct sam4_bank_private *pPrivate, uint32_t *v)
943 {
944         int r;
945         uint32_t rv;
946         r = target_read_u32(pPrivate->pChip->target,
947                         pPrivate->controller_address + offset_EFC_FRR,
948                         &rv);
949         if (v)
950                 *v = rv;
951         LOG_DEBUG("Result: 0x%08x", ((unsigned int)(rv)));
952         return r;
953 }
954
955 static int EFC_StartCommand(struct sam4_bank_private *pPrivate,
956         unsigned command, unsigned argument)
957 {
958         uint32_t n, v;
959         int r;
960         int retry;
961
962         retry = 0;
963 do_retry:
964
965         /* Check command & argument */
966         switch (command) {
967
968                 case AT91C_EFC_FCMD_WP:
969                 case AT91C_EFC_FCMD_WPL:
970                 case AT91C_EFC_FCMD_EWP:
971                 case AT91C_EFC_FCMD_EWPL:
972                 /* case AT91C_EFC_FCMD_EPL: */
973                 case AT91C_EFC_FCMD_EPA:
974                 case AT91C_EFC_FCMD_SLB:
975                 case AT91C_EFC_FCMD_CLB:
976                         n = (pPrivate->size_bytes / pPrivate->page_size);
977                         if (argument >= n)
978                                 LOG_ERROR("*BUG*: Embedded flash has only %u pages", (unsigned)(n));
979                         break;
980
981                 case AT91C_EFC_FCMD_SFB:
982                 case AT91C_EFC_FCMD_CFB:
983                         if (argument >= pPrivate->pChip->details.n_gpnvms) {
984                                 LOG_ERROR("*BUG*: Embedded flash has only %d GPNVMs",
985                                                 pPrivate->pChip->details.n_gpnvms);
986                         }
987                         break;
988
989                 case AT91C_EFC_FCMD_GETD:
990                 case AT91C_EFC_FCMD_EA:
991                 case AT91C_EFC_FCMD_GLB:
992                 case AT91C_EFC_FCMD_GFB:
993                 case AT91C_EFC_FCMD_STUI:
994                 case AT91C_EFC_FCMD_SPUI:
995                         if (argument != 0)
996                                 LOG_ERROR("Argument is meaningless for cmd: %d", command);
997                         break;
998                 default:
999                         LOG_ERROR("Unknown command %d", command);
1000                         break;
1001         }
1002
1003         if (command == AT91C_EFC_FCMD_SPUI) {
1004                 /* this is a very special situation. */
1005                 /* Situation (1) - error/retry - see below */
1006                 /*      And we are being called recursively */
1007                 /* Situation (2) - normal, finished reading unique id */
1008         } else {
1009                 /* it should be "ready" */
1010                 EFC_GetStatus(pPrivate, &v);
1011                 if (v & 1) {
1012                         /* then it is ready */
1013                         /* we go on */
1014                 } else {
1015                         if (retry) {
1016                                 /* we have done this before */
1017                                 /* the controller is not responding. */
1018                                 LOG_ERROR("flash controller(%d) is not ready! Error",
1019                                         pPrivate->bank_number);
1020                                 return ERROR_FAIL;
1021                         } else {
1022                                 retry++;
1023                                 LOG_ERROR("Flash controller(%d) is not ready, attempting reset",
1024                                         pPrivate->bank_number);
1025                                 /* we do that by issuing the *STOP* command */
1026                                 EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0);
1027                                 /* above is recursive, and further recursion is blocked by */
1028                                 /* if (command == AT91C_EFC_FCMD_SPUI) above */
1029                                 goto do_retry;
1030                         }
1031                 }
1032         }
1033
1034         v = (0x5A << 24) | (argument << 8) | command;
1035         LOG_DEBUG("Command: 0x%08x", ((unsigned int)(v)));
1036         r = target_write_u32(pPrivate->pBank->target,
1037                         pPrivate->controller_address + offset_EFC_FCR, v);
1038         if (r != ERROR_OK)
1039                 LOG_DEBUG("Error Write failed");
1040         return r;
1041 }
1042
1043 /**
1044  * Performs the given command and wait until its completion (or an error).
1045  * @param pPrivate - info about the bank
1046  * @param command  - Command to perform.
1047  * @param argument - Optional command argument.
1048  * @param status   - put command status bits here
1049  */
1050 static int EFC_PerformCommand(struct sam4_bank_private *pPrivate,
1051         unsigned command,
1052         unsigned argument,
1053         uint32_t *status)
1054 {
1055
1056         int r;
1057         uint32_t v;
1058         long long ms_now, ms_end;
1059
1060         /* default */
1061         if (status)
1062                 *status = 0;
1063
1064         r = EFC_StartCommand(pPrivate, command, argument);
1065         if (r != ERROR_OK)
1066                 return r;
1067
1068         ms_end = 10000 + timeval_ms();
1069
1070         do {
1071                 r = EFC_GetStatus(pPrivate, &v);
1072                 if (r != ERROR_OK)
1073                         return r;
1074                 ms_now = timeval_ms();
1075                 if (ms_now > ms_end) {
1076                         /* error */
1077                         LOG_ERROR("Command timeout");
1078                         return ERROR_FAIL;
1079                 }
1080         } while ((v & 1) == 0);
1081
1082         /* error bits.. */
1083         if (status)
1084                 *status = (v & 0x6);
1085         return ERROR_OK;
1086
1087 }
1088
1089 /**
1090  * Read the unique ID.
1091  * @param pPrivate - info about the bank
1092  * The unique ID is stored in the 'pPrivate' structure.
1093  */
1094 static int FLASHD_ReadUniqueID(struct sam4_bank_private *pPrivate)
1095 {
1096         int r;
1097         uint32_t v;
1098         int x;
1099         /* assume 0 */
1100         pPrivate->pChip->cfg.unique_id[0] = 0;
1101         pPrivate->pChip->cfg.unique_id[1] = 0;
1102         pPrivate->pChip->cfg.unique_id[2] = 0;
1103         pPrivate->pChip->cfg.unique_id[3] = 0;
1104
1105         LOG_DEBUG("Begin");
1106         r = EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_STUI, 0);
1107         if (r < 0)
1108                 return r;
1109
1110         for (x = 0; x < 4; x++) {
1111                 r = target_read_u32(pPrivate->pChip->target,
1112                                 pPrivate->pBank->base + (x * 4),
1113                                 &v);
1114                 if (r < 0)
1115                         return r;
1116                 pPrivate->pChip->cfg.unique_id[x] = v;
1117         }
1118
1119         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0, NULL);
1120         LOG_DEBUG("End: R=%d, id = 0x%08x, 0x%08x, 0x%08x, 0x%08x",
1121                 r,
1122                 (unsigned int)(pPrivate->pChip->cfg.unique_id[0]),
1123                 (unsigned int)(pPrivate->pChip->cfg.unique_id[1]),
1124                 (unsigned int)(pPrivate->pChip->cfg.unique_id[2]),
1125                 (unsigned int)(pPrivate->pChip->cfg.unique_id[3]));
1126         return r;
1127
1128 }
1129
1130 /**
1131  * Erases the entire flash.
1132  * @param pPrivate - the info about the bank.
1133  */
1134 static int FLASHD_EraseEntireBank(struct sam4_bank_private *pPrivate)
1135 {
1136         LOG_DEBUG("Here");
1137         return EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_EA, 0, NULL);
1138 }
1139
1140 /**
1141  * Erases the entire flash.
1142  * @param pPrivate - the info about the bank.
1143  */
1144 static int FLASHD_ErasePages(struct sam4_bank_private *pPrivate,
1145                                                          int firstPage,
1146                                                          int numPages,
1147                                                          uint32_t *status)
1148 {
1149         LOG_DEBUG("Here");
1150         uint8_t erasePages;
1151         switch (numPages)       {
1152                 case 4:
1153                         erasePages = 0x00;
1154                         break;
1155                 case 8:
1156                         erasePages = 0x01;
1157                         break;
1158                 case 16:
1159                         erasePages = 0x02;
1160                         break;
1161                 case 32:
1162                         erasePages = 0x03;
1163                         break;
1164                 default:
1165                         erasePages = 0x00;
1166                         break;
1167         }
1168
1169         /* AT91C_EFC_FCMD_EPA
1170          * According to the datasheet FARG[15:2] defines the page from which
1171          * the erase will start.This page must be modulo 4, 8, 16 or 32
1172          * according to the number of pages to erase. FARG[1:0] defines the
1173          * number of pages to be erased. Previously (firstpage << 2) was used
1174          * to conform to this, seems it should not be shifted...
1175          */
1176         return EFC_PerformCommand(pPrivate,
1177                 /* send Erase Page */
1178                 AT91C_EFC_FCMD_EPA,
1179                 (firstPage) | erasePages,
1180                 status);
1181 }
1182
1183 /**
1184  * Gets current GPNVM state.
1185  * @param pPrivate - info about the bank.
1186  * @param gpnvm    -  GPNVM bit index.
1187  * @param puthere  - result stored here.
1188  */
1189 /* ------------------------------------------------------------------------------ */
1190 static int FLASHD_GetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm, unsigned *puthere)
1191 {
1192         uint32_t v;
1193         int r;
1194
1195         LOG_DEBUG("Here");
1196         if (pPrivate->bank_number != 0) {
1197                 LOG_ERROR("GPNVM only works with Bank0");
1198                 return ERROR_FAIL;
1199         }
1200
1201         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
1202                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
1203                         gpnvm, pPrivate->pChip->details.n_gpnvms);
1204                 return ERROR_FAIL;
1205         }
1206
1207         /* Get GPNVMs status */
1208         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GFB, 0, NULL);
1209         if (r != ERROR_OK) {
1210                 LOG_ERROR("Failed");
1211                 return r;
1212         }
1213
1214         r = EFC_GetResult(pPrivate, &v);
1215
1216         if (puthere) {
1217                 /* Check if GPNVM is set */
1218                 /* get the bit and make it a 0/1 */
1219                 *puthere = (v >> gpnvm) & 1;
1220         }
1221
1222         return r;
1223 }
1224
1225 /**
1226  * Clears the selected GPNVM bit.
1227  * @param pPrivate info about the bank
1228  * @param gpnvm GPNVM index.
1229  * @returns 0 if successful; otherwise returns an error code.
1230  */
1231 static int FLASHD_ClrGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
1232 {
1233         int r;
1234         unsigned v;
1235
1236         LOG_DEBUG("Here");
1237         if (pPrivate->bank_number != 0) {
1238                 LOG_ERROR("GPNVM only works with Bank0");
1239                 return ERROR_FAIL;
1240         }
1241
1242         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
1243                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
1244                         gpnvm, pPrivate->pChip->details.n_gpnvms);
1245                 return ERROR_FAIL;
1246         }
1247
1248         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
1249         if (r != ERROR_OK) {
1250                 LOG_DEBUG("Failed: %d", r);
1251                 return r;
1252         }
1253         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CFB, gpnvm, NULL);
1254         LOG_DEBUG("End: %d", r);
1255         return r;
1256 }
1257
1258 /**
1259  * Sets the selected GPNVM bit.
1260  * @param pPrivate info about the bank
1261  * @param gpnvm GPNVM index.
1262  */
1263 static int FLASHD_SetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
1264 {
1265         int r;
1266         unsigned v;
1267
1268         if (pPrivate->bank_number != 0) {
1269                 LOG_ERROR("GPNVM only works with Bank0");
1270                 return ERROR_FAIL;
1271         }
1272
1273         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
1274                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
1275                         gpnvm, pPrivate->pChip->details.n_gpnvms);
1276                 return ERROR_FAIL;
1277         }
1278
1279         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
1280         if (r != ERROR_OK)
1281                 return r;
1282         if (v) {
1283                 /* already set */
1284                 r = ERROR_OK;
1285         } else {
1286                 /* set it */
1287                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SFB, gpnvm, NULL);
1288         }
1289         return r;
1290 }
1291
1292 /**
1293  * Returns a bit field (at most 64) of locked regions within a page.
1294  * @param pPrivate info about the bank
1295  * @param v where to store locked bits
1296  */
1297 static int FLASHD_GetLockBits(struct sam4_bank_private *pPrivate, uint32_t *v)
1298 {
1299         int r;
1300         LOG_DEBUG("Here");
1301         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GLB, 0, NULL);
1302         if (r == ERROR_OK)      {
1303                 EFC_GetResult(pPrivate, v);
1304                 EFC_GetResult(pPrivate, v);
1305                 EFC_GetResult(pPrivate, v);
1306                 r = EFC_GetResult(pPrivate, v);
1307         }
1308         LOG_DEBUG("End: %d", r);
1309         return r;
1310 }
1311
1312 /**
1313  * Unlocks all the regions in the given address range.
1314  * @param pPrivate info about the bank
1315  * @param start_sector first sector to unlock
1316  * @param end_sector last (inclusive) to unlock
1317  */
1318
1319 static int FLASHD_Unlock(struct sam4_bank_private *pPrivate,
1320         unsigned start_sector,
1321         unsigned end_sector)
1322 {
1323         int r;
1324         uint32_t status;
1325         uint32_t pg;
1326         uint32_t pages_per_sector;
1327
1328         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
1329
1330         /* Unlock all pages */
1331         while (start_sector <= end_sector) {
1332                 pg = start_sector * pages_per_sector;
1333
1334                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CLB, pg, &status);
1335                 if (r != ERROR_OK)
1336                         return r;
1337                 start_sector++;
1338         }
1339
1340         return ERROR_OK;
1341 }
1342
1343 /**
1344  * Locks regions
1345  * @param pPrivate - info about the bank
1346  * @param start_sector - first sector to lock
1347  * @param end_sector   - last sector (inclusive) to lock
1348  */
1349 static int FLASHD_Lock(struct sam4_bank_private *pPrivate,
1350         unsigned start_sector,
1351         unsigned end_sector)
1352 {
1353         uint32_t status;
1354         uint32_t pg;
1355         uint32_t pages_per_sector;
1356         int r;
1357
1358         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
1359
1360         /* Lock all pages */
1361         while (start_sector <= end_sector) {
1362                 pg = start_sector * pages_per_sector;
1363
1364                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SLB, pg, &status);
1365                 if (r != ERROR_OK)
1366                         return r;
1367                 start_sector++;
1368         }
1369         return ERROR_OK;
1370 }
1371
1372 /****** END SAM4 CODE ********/
1373
1374 /* begin helpful debug code */
1375 /* print the fieldname, the field value, in dec & hex, and return field value */
1376 static uint32_t sam4_reg_fieldname(struct sam4_chip *pChip,
1377         const char *regname,
1378         uint32_t value,
1379         unsigned shift,
1380         unsigned width)
1381 {
1382         uint32_t v;
1383         int hwidth, dwidth;
1384
1385
1386         /* extract the field */
1387         v = value >> shift;
1388         v = v & ((1 << width)-1);
1389         if (width <= 16) {
1390                 hwidth = 4;
1391                 dwidth = 5;
1392         } else {
1393                 hwidth = 8;
1394                 dwidth = 12;
1395         }
1396
1397         /* show the basics */
1398         LOG_USER_N("\t%*s: %*" PRId32 " [0x%0*" PRIx32 "] ",
1399                 REG_NAME_WIDTH, regname,
1400                 dwidth, v,
1401                 hwidth, v);
1402         return v;
1403 }
1404
1405 static const char _unknown[] = "unknown";
1406 static const char *const eproc_names[] = {
1407         _unknown,                                       /* 0 */
1408         "arm946es",                                     /* 1 */
1409         "arm7tdmi",                                     /* 2 */
1410         "cortex-m3",                            /* 3 */
1411         "arm920t",                                      /* 4 */
1412         "arm926ejs",                            /* 5 */
1413         "cortex-a5",                            /* 6 */
1414         "cortex-m4",                            /* 7 */
1415         _unknown,                                       /* 8 */
1416         _unknown,                                       /* 9 */
1417         _unknown,                                       /* 10 */
1418         _unknown,                                       /* 11 */
1419         _unknown,                                       /* 12 */
1420         _unknown,                                       /* 13 */
1421         _unknown,                                       /* 14 */
1422         _unknown,                                       /* 15 */
1423 };
1424
1425 #define nvpsize2 nvpsize                /* these two tables are identical */
1426 static const char *const nvpsize[] = {
1427         "none",                                         /*  0 */
1428         "8K bytes",                                     /*  1 */
1429         "16K bytes",                            /*  2 */
1430         "32K bytes",                            /*  3 */
1431         _unknown,                                       /*  4 */
1432         "64K bytes",                            /*  5 */
1433         _unknown,                                       /*  6 */
1434         "128K bytes",                           /*  7 */
1435         _unknown,                                       /*  8 */
1436         "256K bytes",                           /*  9 */
1437         "512K bytes",                           /* 10 */
1438         _unknown,                                       /* 11 */
1439         "1024K bytes",                          /* 12 */
1440         _unknown,                                       /* 13 */
1441         "2048K bytes",                          /* 14 */
1442         _unknown,                                       /* 15 */
1443 };
1444
1445 static const char *const sramsize[] = {
1446         "48K Bytes",                            /*  0 */
1447         "1K Bytes",                                     /*  1 */
1448         "2K Bytes",                                     /*  2 */
1449         "6K Bytes",                                     /*  3 */
1450         "112K Bytes",                           /*  4 */
1451         "4K Bytes",                                     /*  5 */
1452         "80K Bytes",                            /*  6 */
1453         "160K Bytes",                           /*  7 */
1454         "8K Bytes",                                     /*  8 */
1455         "16K Bytes",                            /*  9 */
1456         "32K Bytes",                            /* 10 */
1457         "64K Bytes",                            /* 11 */
1458         "128K Bytes",                           /* 12 */
1459         "256K Bytes",                           /* 13 */
1460         "96K Bytes",                            /* 14 */
1461         "512K Bytes",                           /* 15 */
1462
1463 };
1464
1465 static const struct archnames { unsigned value; const char *name; } archnames[] = {
1466         { 0x19,  "AT91SAM9xx Series"                                            },
1467         { 0x29,  "AT91SAM9XExx Series"                                          },
1468         { 0x34,  "AT91x34 Series"                                                       },
1469         { 0x37,  "CAP7 Series"                                                          },
1470         { 0x39,  "CAP9 Series"                                                          },
1471         { 0x3B,  "CAP11 Series"                                                         },
1472         { 0x3C, "ATSAM4E"                                                               },
1473         { 0x40,  "AT91x40 Series"                                                       },
1474         { 0x42,  "AT91x42 Series"                                                       },
1475         { 0x43,  "SAMG51 Series"
1476         },
1477         { 0x47,  "SAMG53 Series"
1478         },
1479         { 0x55,  "AT91x55 Series"                                                       },
1480         { 0x60,  "AT91SAM7Axx Series"                                           },
1481         { 0x61,  "AT91SAM7AQxx Series"                                          },
1482         { 0x63,  "AT91x63 Series"                                                       },
1483         { 0x70,  "AT91SAM7Sxx Series"                                           },
1484         { 0x71,  "AT91SAM7XCxx Series"                                          },
1485         { 0x72,  "AT91SAM7SExx Series"                                          },
1486         { 0x73,  "AT91SAM7Lxx Series"                                           },
1487         { 0x75,  "AT91SAM7Xxx Series"                                           },
1488         { 0x76,  "AT91SAM7SLxx Series"                                          },
1489         { 0x80,  "ATSAM3UxC Series (100-pin version)"           },
1490         { 0x81,  "ATSAM3UxE Series (144-pin version)"           },
1491         { 0x83,  "ATSAM3A/SAM4A xC Series (100-pin version)"},
1492         { 0x84,  "ATSAM3X/SAM4X xC Series (100-pin version)"},
1493         { 0x85,  "ATSAM3X/SAM4X xE Series (144-pin version)"},
1494         { 0x86,  "ATSAM3X/SAM4X xG Series (208/217-pin version)"        },
1495         { 0x88,  "ATSAM3S/SAM4S xA Series (48-pin version)"     },
1496         { 0x89,  "ATSAM3S/SAM4S xB Series (64-pin version)"     },
1497         { 0x8A,  "ATSAM3S/SAM4S xC Series (100-pin version)"},
1498         { 0x92,  "AT91x92 Series"                                                       },
1499         { 0x93,  "ATSAM3NxA Series (48-pin version)"            },
1500         { 0x94,  "ATSAM3NxB Series (64-pin version)"            },
1501         { 0x95,  "ATSAM3NxC Series (100-pin version)"           },
1502         { 0x98,  "ATSAM3SDxA Series (48-pin version)"           },
1503         { 0x99,  "ATSAM3SDxB Series (64-pin version)"           },
1504         { 0x9A,  "ATSAM3SDxC Series (100-pin version)"          },
1505         { 0xA5,  "ATSAM5A"                                                              },
1506         { 0xF0,  "AT75Cxx Series"                                                       },
1507         { -1, NULL },
1508 };
1509
1510 static const char *const nvptype[] = {
1511         "rom",  /* 0 */
1512         "romless or onchip flash",      /* 1 */
1513         "embedded flash memory",/* 2 */
1514         "rom(nvpsiz) + embedded flash (nvpsiz2)",       /* 3 */
1515         "sram emulating flash", /* 4 */
1516         _unknown,       /* 5 */
1517         _unknown,       /* 6 */
1518         _unknown,       /* 7 */
1519 };
1520
1521 static const char *_yes_or_no(uint32_t v)
1522 {
1523         if (v)
1524                 return "YES";
1525         else
1526                 return "NO";
1527 }
1528
1529 static const char *const _rc_freq[] = {
1530         "4 MHz", "8 MHz", "12 MHz", "reserved"
1531 };
1532
1533 static void sam4_explain_ckgr_mor(struct sam4_chip *pChip)
1534 {
1535         uint32_t v;
1536         uint32_t rcen;
1537
1538         v = sam4_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
1539         LOG_USER("(main xtal enabled: %s)", _yes_or_no(v));
1540         v = sam4_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
1541         LOG_USER("(main osc bypass: %s)", _yes_or_no(v));
1542         rcen = sam4_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 3, 1);
1543         LOG_USER("(onchip RC-OSC enabled: %s)", _yes_or_no(rcen));
1544         v = sam4_reg_fieldname(pChip, "MOSCRCF", pChip->cfg.CKGR_MOR, 4, 3);
1545         LOG_USER("(onchip RC-OSC freq: %s)", _rc_freq[v]);
1546
1547         pChip->cfg.rc_freq = 0;
1548         if (rcen) {
1549                 switch (v) {
1550                         default:
1551                                 pChip->cfg.rc_freq = 0;
1552                                 break;
1553                         case 0:
1554                                 pChip->cfg.rc_freq = 4 * 1000 * 1000;
1555                                 break;
1556                         case 1:
1557                                 pChip->cfg.rc_freq = 8 * 1000 * 1000;
1558                                 break;
1559                         case 2:
1560                                 pChip->cfg.rc_freq = 12 * 1000 * 1000;
1561                                 break;
1562                 }
1563         }
1564
1565         v = sam4_reg_fieldname(pChip, "MOSCXTST", pChip->cfg.CKGR_MOR, 8, 8);
1566         LOG_USER("(startup clks, time= %f uSecs)",
1567                 ((float)(v * 1000000)) / ((float)(pChip->cfg.slow_freq)));
1568         v = sam4_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
1569         LOG_USER("(mainosc source: %s)",
1570                 v ? "external xtal" : "internal RC");
1571
1572         v = sam4_reg_fieldname(pChip, "CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
1573         LOG_USER("(clock failure enabled: %s)",
1574                 _yes_or_no(v));
1575 }
1576
1577 static void sam4_explain_chipid_cidr(struct sam4_chip *pChip)
1578 {
1579         int x;
1580         uint32_t v;
1581         const char *cp;
1582
1583         sam4_reg_fieldname(pChip, "Version", pChip->cfg.CHIPID_CIDR, 0, 5);
1584         LOG_USER_N("\n");
1585
1586         v = sam4_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
1587         LOG_USER("%s", eproc_names[v]);
1588
1589         v = sam4_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
1590         LOG_USER("%s", nvpsize[v]);
1591
1592         v = sam4_reg_fieldname(pChip, "NVPSIZE2", pChip->cfg.CHIPID_CIDR, 12, 4);
1593         LOG_USER("%s", nvpsize2[v]);
1594
1595         v = sam4_reg_fieldname(pChip, "SRAMSIZE", pChip->cfg.CHIPID_CIDR, 16, 4);
1596         LOG_USER("%s", sramsize[v]);
1597
1598         v = sam4_reg_fieldname(pChip, "ARCH", pChip->cfg.CHIPID_CIDR, 20, 8);
1599         cp = _unknown;
1600         for (x = 0; archnames[x].name; x++) {
1601                 if (v == archnames[x].value) {
1602                         cp = archnames[x].name;
1603                         break;
1604                 }
1605         }
1606
1607         LOG_USER("%s", cp);
1608
1609         v = sam4_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
1610         LOG_USER("%s", nvptype[v]);
1611
1612         v = sam4_reg_fieldname(pChip, "EXTID", pChip->cfg.CHIPID_CIDR, 31, 1);
1613         LOG_USER("(exists: %s)", _yes_or_no(v));
1614 }
1615
1616 static void sam4_explain_ckgr_mcfr(struct sam4_chip *pChip)
1617 {
1618         uint32_t v;
1619
1620         v = sam4_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
1621         LOG_USER("(main ready: %s)", _yes_or_no(v));
1622
1623         v = sam4_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
1624
1625         v = (v * pChip->cfg.slow_freq) / 16;
1626         pChip->cfg.mainosc_freq = v;
1627
1628         LOG_USER("(%3.03f Mhz (%" PRIu32 ".%03" PRIu32 "khz slowclk)",
1629                 _tomhz(v),
1630                 (uint32_t)(pChip->cfg.slow_freq / 1000),
1631                 (uint32_t)(pChip->cfg.slow_freq % 1000));
1632 }
1633
1634 static void sam4_explain_ckgr_plla(struct sam4_chip *pChip)
1635 {
1636         uint32_t mula, diva;
1637
1638         diva = sam4_reg_fieldname(pChip, "DIVA", pChip->cfg.CKGR_PLLAR, 0, 8);
1639         LOG_USER_N("\n");
1640         mula = sam4_reg_fieldname(pChip, "MULA", pChip->cfg.CKGR_PLLAR, 16, 11);
1641         LOG_USER_N("\n");
1642         pChip->cfg.plla_freq = 0;
1643         if (mula == 0)
1644                 LOG_USER("\tPLLA Freq: (Disabled,mula = 0)");
1645         else if (diva == 0)
1646                 LOG_USER("\tPLLA Freq: (Disabled,diva = 0)");
1647         else if (diva >= 1) {
1648                 pChip->cfg.plla_freq = (pChip->cfg.mainosc_freq * (mula + 1) / diva);
1649                 LOG_USER("\tPLLA Freq: %3.03f MHz",
1650                         _tomhz(pChip->cfg.plla_freq));
1651         }
1652 }
1653
1654 static void sam4_explain_mckr(struct sam4_chip *pChip)
1655 {
1656         uint32_t css, pres, fin = 0;
1657         int pdiv = 0;
1658         const char *cp = NULL;
1659
1660         css = sam4_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
1661         switch (css & 3) {
1662                 case 0:
1663                         fin = pChip->cfg.slow_freq;
1664                         cp = "slowclk";
1665                         break;
1666                 case 1:
1667                         fin = pChip->cfg.mainosc_freq;
1668                         cp  = "mainosc";
1669                         break;
1670                 case 2:
1671                         fin = pChip->cfg.plla_freq;
1672                         cp  = "plla";
1673                         break;
1674                 case 3:
1675                         if (pChip->cfg.CKGR_UCKR & (1 << 16)) {
1676                                 fin = 480 * 1000 * 1000;
1677                                 cp = "upll";
1678                         } else {
1679                                 fin = 0;
1680                                 cp  = "upll (*ERROR* UPLL is disabled)";
1681                         }
1682                         break;
1683                 default:
1684                         assert(0);
1685                         break;
1686         }
1687
1688         LOG_USER("%s (%3.03f Mhz)",
1689                 cp,
1690                 _tomhz(fin));
1691         pres = sam4_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
1692         switch (pres & 0x07) {
1693                 case 0:
1694                         pdiv = 1;
1695                         cp = "selected clock";
1696                         break;
1697                 case 1:
1698                         pdiv = 2;
1699                         cp = "clock/2";
1700                         break;
1701                 case 2:
1702                         pdiv = 4;
1703                         cp = "clock/4";
1704                         break;
1705                 case 3:
1706                         pdiv = 8;
1707                         cp = "clock/8";
1708                         break;
1709                 case 4:
1710                         pdiv = 16;
1711                         cp = "clock/16";
1712                         break;
1713                 case 5:
1714                         pdiv = 32;
1715                         cp = "clock/32";
1716                         break;
1717                 case 6:
1718                         pdiv = 64;
1719                         cp = "clock/64";
1720                         break;
1721                 case 7:
1722                         pdiv = 6;
1723                         cp = "clock/6";
1724                         break;
1725                 default:
1726                         assert(0);
1727                         break;
1728         }
1729         LOG_USER("(%s)", cp);
1730         fin = fin / pdiv;
1731         /* sam4 has a *SINGLE* clock - */
1732         /* other at91 series parts have divisors for these. */
1733         pChip->cfg.cpu_freq = fin;
1734         pChip->cfg.mclk_freq = fin;
1735         pChip->cfg.fclk_freq = fin;
1736         LOG_USER("\t\tResult CPU Freq: %3.03f",
1737                 _tomhz(fin));
1738 }
1739
1740 #if 0
1741 static struct sam4_chip *target2sam4(struct target *pTarget)
1742 {
1743         struct sam4_chip *pChip;
1744
1745         if (pTarget == NULL)
1746                 return NULL;
1747
1748         pChip = all_sam4_chips;
1749         while (pChip) {
1750                 if (pChip->target == pTarget)
1751                         break;  /* return below */
1752                 else
1753                         pChip = pChip->next;
1754         }
1755         return pChip;
1756 }
1757 #endif
1758
1759 static uint32_t *sam4_get_reg_ptr(struct sam4_cfg *pCfg, const struct sam4_reg_list *pList)
1760 {
1761         /* this function exists to help */
1762         /* keep funky offsetof() errors */
1763         /* and casting from causing bugs */
1764
1765         /* By using prototypes - we can detect what would */
1766         /* be casting errors. */
1767
1768         return (uint32_t *)(void *)(((char *)(pCfg)) + pList->struct_offset);
1769 }
1770
1771
1772 #define SAM4_ENTRY(NAME, FUNC)  { .address = SAM4_ ## NAME, .struct_offset = offsetof( \
1773                                                   struct sam4_cfg, \
1774                                                   NAME), # NAME, FUNC }
1775 static const struct sam4_reg_list sam4_all_regs[] = {
1776         SAM4_ENTRY(CKGR_MOR, sam4_explain_ckgr_mor),
1777         SAM4_ENTRY(CKGR_MCFR, sam4_explain_ckgr_mcfr),
1778         SAM4_ENTRY(CKGR_PLLAR, sam4_explain_ckgr_plla),
1779         SAM4_ENTRY(CKGR_UCKR, NULL),
1780         SAM4_ENTRY(PMC_FSMR, NULL),
1781         SAM4_ENTRY(PMC_FSPR, NULL),
1782         SAM4_ENTRY(PMC_IMR, NULL),
1783         SAM4_ENTRY(PMC_MCKR, sam4_explain_mckr),
1784         SAM4_ENTRY(PMC_PCK0, NULL),
1785         SAM4_ENTRY(PMC_PCK1, NULL),
1786         SAM4_ENTRY(PMC_PCK2, NULL),
1787         SAM4_ENTRY(PMC_PCSR, NULL),
1788         SAM4_ENTRY(PMC_SCSR, NULL),
1789         SAM4_ENTRY(PMC_SR, NULL),
1790         SAM4_ENTRY(CHIPID_CIDR, sam4_explain_chipid_cidr),
1791         SAM4_ENTRY(CHIPID_EXID, NULL),
1792         /* TERMINATE THE LIST */
1793         { .name = NULL }
1794 };
1795 #undef SAM4_ENTRY
1796
1797 static struct sam4_bank_private *get_sam4_bank_private(struct flash_bank *bank)
1798 {
1799         return bank->driver_priv;
1800 }
1801
1802 /**
1803  * Given a pointer to where it goes in the structure,
1804  * determine the register name, address from the all registers table.
1805  */
1806 static const struct sam4_reg_list *sam4_GetReg(struct sam4_chip *pChip, uint32_t *goes_here)
1807 {
1808         const struct sam4_reg_list *pReg;
1809
1810         pReg = &(sam4_all_regs[0]);
1811         while (pReg->name) {
1812                 uint32_t *pPossible;
1813
1814                 /* calculate where this one go.. */
1815                 /* it is "possibly" this register. */
1816
1817                 pPossible = ((uint32_t *)(void *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
1818
1819                 /* well? Is it this register */
1820                 if (pPossible == goes_here) {
1821                         /* Jump for joy! */
1822                         return pReg;
1823                 }
1824
1825                 /* next... */
1826                 pReg++;
1827         }
1828         /* This is *TOTAL*PANIC* - we are totally screwed. */
1829         LOG_ERROR("INVALID SAM4 REGISTER");
1830         return NULL;
1831 }
1832
1833 static int sam4_ReadThisReg(struct sam4_chip *pChip, uint32_t *goes_here)
1834 {
1835         const struct sam4_reg_list *pReg;
1836         int r;
1837
1838         pReg = sam4_GetReg(pChip, goes_here);
1839         if (!pReg)
1840                 return ERROR_FAIL;
1841
1842         r = target_read_u32(pChip->target, pReg->address, goes_here);
1843         if (r != ERROR_OK) {
1844                 LOG_ERROR("Cannot read SAM4 register: %s @ 0x%08x, Err: %d",
1845                         pReg->name, (unsigned)(pReg->address), r);
1846         }
1847         return r;
1848 }
1849
1850 static int sam4_ReadAllRegs(struct sam4_chip *pChip)
1851 {
1852         int r;
1853         const struct sam4_reg_list *pReg;
1854
1855         pReg = &(sam4_all_regs[0]);
1856         while (pReg->name) {
1857                 r = sam4_ReadThisReg(pChip,
1858                                 sam4_get_reg_ptr(&(pChip->cfg), pReg));
1859                 if (r != ERROR_OK) {
1860                         LOG_ERROR("Cannot read SAM4 register: %s @ 0x%08x, Error: %d",
1861                                 pReg->name, ((unsigned)(pReg->address)), r);
1862                         return r;
1863                 }
1864                 pReg++;
1865         }
1866
1867         return ERROR_OK;
1868 }
1869
1870 static int sam4_GetInfo(struct sam4_chip *pChip)
1871 {
1872         const struct sam4_reg_list *pReg;
1873         uint32_t regval;
1874
1875         pReg = &(sam4_all_regs[0]);
1876         while (pReg->name) {
1877                 /* display all regs */
1878                 LOG_DEBUG("Start: %s", pReg->name);
1879                 regval = *sam4_get_reg_ptr(&(pChip->cfg), pReg);
1880                 LOG_USER("%*s: [0x%08" PRIx32 "] -> 0x%08" PRIx32,
1881                         REG_NAME_WIDTH,
1882                         pReg->name,
1883                         pReg->address,
1884                         regval);
1885                 if (pReg->explain_func)
1886                         (*(pReg->explain_func))(pChip);
1887                 LOG_DEBUG("End: %s", pReg->name);
1888                 pReg++;
1889         }
1890         LOG_USER("   rc-osc: %3.03f MHz", _tomhz(pChip->cfg.rc_freq));
1891         LOG_USER("  mainosc: %3.03f MHz", _tomhz(pChip->cfg.mainosc_freq));
1892         LOG_USER("     plla: %3.03f MHz", _tomhz(pChip->cfg.plla_freq));
1893         LOG_USER(" cpu-freq: %3.03f MHz", _tomhz(pChip->cfg.cpu_freq));
1894         LOG_USER("mclk-freq: %3.03f MHz", _tomhz(pChip->cfg.mclk_freq));
1895
1896         LOG_USER(" UniqueId: 0x%08" PRIx32 " 0x%08" PRIx32 " 0x%08" PRIx32 " 0x%08"PRIx32,
1897                 pChip->cfg.unique_id[0],
1898                 pChip->cfg.unique_id[1],
1899                 pChip->cfg.unique_id[2],
1900                 pChip->cfg.unique_id[3]);
1901
1902         return ERROR_OK;
1903 }
1904
1905 static int sam4_protect_check(struct flash_bank *bank)
1906 {
1907         int r;
1908         uint32_t v[4] = {0};
1909         unsigned x;
1910         struct sam4_bank_private *pPrivate;
1911
1912         LOG_DEBUG("Begin");
1913         if (bank->target->state != TARGET_HALTED) {
1914                 LOG_ERROR("Target not halted");
1915                 return ERROR_TARGET_NOT_HALTED;
1916         }
1917
1918         pPrivate = get_sam4_bank_private(bank);
1919         if (!pPrivate) {
1920                 LOG_ERROR("no private for this bank?");
1921                 return ERROR_FAIL;
1922         }
1923         if (!(pPrivate->probed))
1924                 return ERROR_FLASH_BANK_NOT_PROBED;
1925
1926         r = FLASHD_GetLockBits(pPrivate, v);
1927         if (r != ERROR_OK) {
1928                 LOG_DEBUG("Failed: %d", r);
1929                 return r;
1930         }
1931
1932         for (x = 0; x < pPrivate->nsectors; x++)
1933                 bank->sectors[x].is_protected = (!!(v[x >> 5] & (1 << (x % 32))));
1934         LOG_DEBUG("Done");
1935         return ERROR_OK;
1936 }
1937
1938 FLASH_BANK_COMMAND_HANDLER(sam4_flash_bank_command)
1939 {
1940         struct sam4_chip *pChip;
1941
1942         pChip = all_sam4_chips;
1943
1944         /* is this an existing chip? */
1945         while (pChip) {
1946                 if (pChip->target == bank->target)
1947                         break;
1948                 pChip = pChip->next;
1949         }
1950
1951         if (!pChip) {
1952                 /* this is a *NEW* chip */
1953                 pChip = calloc(1, sizeof(struct sam4_chip));
1954                 if (!pChip) {
1955                         LOG_ERROR("NO RAM!");
1956                         return ERROR_FAIL;
1957                 }
1958                 pChip->target = bank->target;
1959                 /* insert at head */
1960                 pChip->next = all_sam4_chips;
1961                 all_sam4_chips = pChip;
1962                 pChip->target = bank->target;
1963                 /* assumption is this runs at 32khz */
1964                 pChip->cfg.slow_freq = 32768;
1965                 pChip->probed = 0;
1966         }
1967
1968         switch (bank->base) {
1969                 default:
1970                         LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x"
1971                                 "[at91sam4s series] )",
1972                                 ((unsigned int)(bank->base)),
1973                                 ((unsigned int)(FLASH_BANK_BASE_S)));
1974                         return ERROR_FAIL;
1975                         break;
1976
1977                 /* at91sam4s series only has bank 0*/
1978                 /* at91sam4sd series has the same address for bank 0 (FLASH_BANK0_BASE_SD)*/
1979                 case FLASH_BANK_BASE_S:
1980                         bank->driver_priv = &(pChip->details.bank[0]);
1981                         bank->bank_number = 0;
1982                         pChip->details.bank[0].pChip = pChip;
1983                         pChip->details.bank[0].pBank = bank;
1984                         break;
1985
1986                 /* Bank 1 of at91sam4sd series */
1987                 case FLASH_BANK1_BASE_1024K_SD:
1988                 case FLASH_BANK1_BASE_2048K_SD:
1989                         bank->driver_priv = &(pChip->details.bank[1]);
1990                         bank->bank_number = 1;
1991                         pChip->details.bank[1].pChip = pChip;
1992                         pChip->details.bank[1].pBank = bank;
1993                         break;
1994         }
1995
1996         /* we initialize after probing. */
1997         return ERROR_OK;
1998 }
1999
2000 static int sam4_GetDetails(struct sam4_bank_private *pPrivate)
2001 {
2002         const struct sam4_chip_details *pDetails;
2003         struct sam4_chip *pChip;
2004         struct flash_bank *saved_banks[SAM4_MAX_FLASH_BANKS];
2005         unsigned x;
2006
2007         LOG_DEBUG("Begin");
2008         pDetails = all_sam4_details;
2009         while (pDetails->name) {
2010                 /* Compare cidr without version bits */
2011                 if (pDetails->chipid_cidr == (pPrivate->pChip->cfg.CHIPID_CIDR & 0xFFFFFFE0))
2012                         break;
2013                 else
2014                         pDetails++;
2015         }
2016         if (pDetails->name == NULL) {
2017                 LOG_ERROR("SAM4 ChipID 0x%08x not found in table (perhaps you can ID this chip?)",
2018                         (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
2019                 /* Help the victim, print details about the chip */
2020                 LOG_INFO("SAM4 CHIPID_CIDR: 0x%08" PRIx32 " decodes as follows",
2021                         pPrivate->pChip->cfg.CHIPID_CIDR);
2022                 sam4_explain_chipid_cidr(pPrivate->pChip);
2023                 return ERROR_FAIL;
2024         }
2025
2026         /* DANGER: THERE ARE DRAGONS HERE */
2027
2028         /* get our pChip - it is going */
2029         /* to be over-written shortly */
2030         pChip = pPrivate->pChip;
2031
2032         /* Note that, in reality: */
2033         /*  */
2034         /*     pPrivate = &(pChip->details.bank[0]) */
2035         /* or  pPrivate = &(pChip->details.bank[1]) */
2036         /*  */
2037
2038         /* save the "bank" pointers */
2039         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++)
2040                 saved_banks[x] = pChip->details.bank[x].pBank;
2041
2042         /* Overwrite the "details" structure. */
2043         memcpy(&(pPrivate->pChip->details),
2044                 pDetails,
2045                 sizeof(pPrivate->pChip->details));
2046
2047         /* now fix the ghosted pointers */
2048         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
2049                 pChip->details.bank[x].pChip = pChip;
2050                 pChip->details.bank[x].pBank = saved_banks[x];
2051         }
2052
2053         /* update the *BANK*SIZE* */
2054
2055         LOG_DEBUG("End");
2056         return ERROR_OK;
2057 }
2058
2059 static int _sam4_probe(struct flash_bank *bank, int noise)
2060 {
2061         unsigned x;
2062         int r;
2063         struct sam4_bank_private *pPrivate;
2064
2065
2066         LOG_DEBUG("Begin: Bank: %d, Noise: %d", bank->bank_number, noise);
2067         if (bank->target->state != TARGET_HALTED) {
2068                 LOG_ERROR("Target not halted");
2069                 return ERROR_TARGET_NOT_HALTED;
2070         }
2071
2072         pPrivate = get_sam4_bank_private(bank);
2073         if (!pPrivate) {
2074                 LOG_ERROR("Invalid/unknown bank number");
2075                 return ERROR_FAIL;
2076         }
2077
2078         r = sam4_ReadAllRegs(pPrivate->pChip);
2079         if (r != ERROR_OK)
2080                 return r;
2081
2082         LOG_DEBUG("Here");
2083         if (pPrivate->pChip->probed)
2084                 r = sam4_GetInfo(pPrivate->pChip);
2085         else
2086                 r = sam4_GetDetails(pPrivate);
2087         if (r != ERROR_OK)
2088                 return r;
2089
2090         /* update the flash bank size */
2091         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
2092                 if (bank->base == pPrivate->pChip->details.bank[x].base_address) {
2093                         bank->size = pPrivate->pChip->details.bank[x].size_bytes;
2094                         break;
2095                 }
2096         }
2097
2098         if (bank->sectors == NULL) {
2099                 bank->sectors = calloc(pPrivate->nsectors, (sizeof((bank->sectors)[0])));
2100                 if (bank->sectors == NULL) {
2101                         LOG_ERROR("No memory!");
2102                         return ERROR_FAIL;
2103                 }
2104                 bank->num_sectors = pPrivate->nsectors;
2105
2106                 for (x = 0; ((int)(x)) < bank->num_sectors; x++) {
2107                         bank->sectors[x].size = pPrivate->sector_size;
2108                         bank->sectors[x].offset = x * (pPrivate->sector_size);
2109                         /* mark as unknown */
2110                         bank->sectors[x].is_erased = -1;
2111                         bank->sectors[x].is_protected = -1;
2112                 }
2113         }
2114
2115         pPrivate->probed = 1;
2116
2117         r = sam4_protect_check(bank);
2118         if (r != ERROR_OK)
2119                 return r;
2120
2121         LOG_DEBUG("Bank = %d, nbanks = %d",
2122                 pPrivate->bank_number, pPrivate->pChip->details.n_banks);
2123         if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
2124                 /* read unique id, */
2125                 /* it appears to be associated with the *last* flash bank. */
2126                 FLASHD_ReadUniqueID(pPrivate);
2127         }
2128
2129         return r;
2130 }
2131
2132 static int sam4_probe(struct flash_bank *bank)
2133 {
2134         return _sam4_probe(bank, 1);
2135 }
2136
2137 static int sam4_auto_probe(struct flash_bank *bank)
2138 {
2139         return _sam4_probe(bank, 0);
2140 }
2141
2142 static int sam4_erase(struct flash_bank *bank, int first, int last)
2143 {
2144         struct sam4_bank_private *pPrivate;
2145         int r;
2146         int i;
2147         int pageCount;
2148         /*16 pages equals 8KB - Same size as a lock region*/
2149         pageCount = 16;
2150         uint32_t status;
2151
2152         LOG_DEBUG("Here");
2153         if (bank->target->state != TARGET_HALTED) {
2154                 LOG_ERROR("Target not halted");
2155                 return ERROR_TARGET_NOT_HALTED;
2156         }
2157
2158         r = sam4_auto_probe(bank);
2159         if (r != ERROR_OK) {
2160                 LOG_DEBUG("Here,r=%d", r);
2161                 return r;
2162         }
2163
2164         pPrivate = get_sam4_bank_private(bank);
2165         if (!(pPrivate->probed))
2166                 return ERROR_FLASH_BANK_NOT_PROBED;
2167
2168         if ((first == 0) && ((last + 1) == ((int)(pPrivate->nsectors)))) {
2169                 /* whole chip */
2170                 LOG_DEBUG("Here");
2171                 return FLASHD_EraseEntireBank(pPrivate);
2172         }
2173         LOG_INFO("sam4 does not auto-erase while programming (Erasing relevant sectors)");
2174         LOG_INFO("sam4 First: 0x%08x Last: 0x%08x", (unsigned int)(first), (unsigned int)(last));
2175         for (i = first; i <= last; i++) {
2176                 /*16 pages equals 8KB - Same size as a lock region*/
2177                 r = FLASHD_ErasePages(pPrivate, (i * pageCount), pageCount, &status);
2178                 LOG_INFO("Erasing sector: 0x%08x", (unsigned int)(i));
2179                 if (r != ERROR_OK)
2180                         LOG_ERROR("SAM4: Error performing Erase page @ lock region number %d",
2181                                 (unsigned int)(i));
2182                 if (status & (1 << 2)) {
2183                         LOG_ERROR("SAM4: Lock Region %d is locked", (unsigned int)(i));
2184                         return ERROR_FAIL;
2185                 }
2186                 if (status & (1 << 1)) {
2187                         LOG_ERROR("SAM4: Flash Command error @lock region %d", (unsigned int)(i));
2188                         return ERROR_FAIL;
2189                 }
2190         }
2191
2192         return ERROR_OK;
2193 }
2194
2195 static int sam4_protect(struct flash_bank *bank, int set, int first, int last)
2196 {
2197         struct sam4_bank_private *pPrivate;
2198         int r;
2199
2200         LOG_DEBUG("Here");
2201         if (bank->target->state != TARGET_HALTED) {
2202                 LOG_ERROR("Target not halted");
2203                 return ERROR_TARGET_NOT_HALTED;
2204         }
2205
2206         pPrivate = get_sam4_bank_private(bank);
2207         if (!(pPrivate->probed))
2208                 return ERROR_FLASH_BANK_NOT_PROBED;
2209
2210         if (set)
2211                 r = FLASHD_Lock(pPrivate, (unsigned)(first), (unsigned)(last));
2212         else
2213                 r = FLASHD_Unlock(pPrivate, (unsigned)(first), (unsigned)(last));
2214         LOG_DEBUG("End: r=%d", r);
2215
2216         return r;
2217
2218 }
2219
2220 static int sam4_page_read(struct sam4_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
2221 {
2222         uint32_t adr;
2223         int r;
2224
2225         adr = pagenum * pPrivate->page_size;
2226         adr = adr + pPrivate->base_address;
2227
2228         r = target_read_memory(pPrivate->pChip->target,
2229                         adr,
2230                         4,                                      /* THIS*MUST*BE* in 32bit values */
2231                         pPrivate->page_size / 4,
2232                         buf);
2233         if (r != ERROR_OK)
2234                 LOG_ERROR("SAM4: Flash program failed to read page phys address: 0x%08x",
2235                         (unsigned int)(adr));
2236         return r;
2237 }
2238
2239 static int sam4_page_write(struct sam4_bank_private *pPrivate, unsigned pagenum, const uint8_t *buf)
2240 {
2241         uint32_t adr;
2242         uint32_t status;
2243         uint32_t fmr;   /* EEFC Flash Mode Register */
2244         int r;
2245
2246         adr = pagenum * pPrivate->page_size;
2247         adr = (adr + pPrivate->base_address);
2248
2249         /* Get flash mode register value */
2250         r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address, &fmr);
2251         if (r != ERROR_OK)
2252                 LOG_DEBUG("Error Read failed: read flash mode register");
2253
2254         /* Clear flash wait state field */
2255         fmr &= 0xfffff0ff;
2256
2257         /* set FWS (flash wait states) field in the FMR (flash mode register) */
2258         fmr |= (pPrivate->flash_wait_states << 8);
2259
2260         LOG_DEBUG("Flash Mode: 0x%08x", ((unsigned int)(fmr)));
2261         r = target_write_u32(pPrivate->pBank->target, pPrivate->controller_address, fmr);
2262         if (r != ERROR_OK)
2263                 LOG_DEBUG("Error Write failed: set flash mode register");
2264
2265         /* 1st sector 8kBytes - page 0 - 15*/
2266         /* 2nd sector 8kBytes - page 16 - 30*/
2267         /* 3rd sector 48kBytes - page 31 - 127*/
2268         LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
2269         r = target_write_memory(pPrivate->pChip->target,
2270                         adr,
2271                         4,                                      /* THIS*MUST*BE* in 32bit values */
2272                         pPrivate->page_size / 4,
2273                         buf);
2274         if (r != ERROR_OK) {
2275                 LOG_ERROR("SAM4: Failed to write (buffer) page at phys address 0x%08x",
2276                         (unsigned int)(adr));
2277                 return r;
2278         }
2279
2280         r = EFC_PerformCommand(pPrivate,
2281                         /* send Erase & Write Page */
2282                         AT91C_EFC_FCMD_WP,      /*AT91C_EFC_FCMD_EWP only works on first two 8kb sectors*/
2283                         pagenum,
2284                         &status);
2285
2286         if (r != ERROR_OK)
2287                 LOG_ERROR("SAM4: Error performing Write page @ phys address 0x%08x",
2288                         (unsigned int)(adr));
2289         if (status & (1 << 2)) {
2290                 LOG_ERROR("SAM4: Page @ Phys address 0x%08x is locked", (unsigned int)(adr));
2291                 return ERROR_FAIL;
2292         }
2293         if (status & (1 << 1)) {
2294                 LOG_ERROR("SAM4: Flash Command error @phys address 0x%08x", (unsigned int)(adr));
2295                 return ERROR_FAIL;
2296         }
2297         return ERROR_OK;
2298 }
2299
2300 static int sam4_write(struct flash_bank *bank,
2301         const uint8_t *buffer,
2302         uint32_t offset,
2303         uint32_t count)
2304 {
2305         int n;
2306         unsigned page_cur;
2307         unsigned page_end;
2308         int r;
2309         unsigned page_offset;
2310         struct sam4_bank_private *pPrivate;
2311         uint8_t *pagebuffer;
2312
2313         /* incase we bail further below, set this to null */
2314         pagebuffer = NULL;
2315
2316         /* ignore dumb requests */
2317         if (count == 0) {
2318                 r = ERROR_OK;
2319                 goto done;
2320         }
2321
2322         if (bank->target->state != TARGET_HALTED) {
2323                 LOG_ERROR("Target not halted");
2324                 r = ERROR_TARGET_NOT_HALTED;
2325                 goto done;
2326         }
2327
2328         pPrivate = get_sam4_bank_private(bank);
2329         if (!(pPrivate->probed)) {
2330                 r = ERROR_FLASH_BANK_NOT_PROBED;
2331                 goto done;
2332         }
2333
2334         if ((offset + count) > pPrivate->size_bytes) {
2335                 LOG_ERROR("Flash write error - past end of bank");
2336                 LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
2337                         (unsigned int)(offset),
2338                         (unsigned int)(count),
2339                         (unsigned int)(pPrivate->size_bytes));
2340                 r = ERROR_FAIL;
2341                 goto done;
2342         }
2343
2344         pagebuffer = malloc(pPrivate->page_size);
2345         if (!pagebuffer) {
2346                 LOG_ERROR("No memory for %d Byte page buffer", (int)(pPrivate->page_size));
2347                 r = ERROR_FAIL;
2348                 goto done;
2349         }
2350
2351         /* what page do we start & end in? */
2352         page_cur = offset / pPrivate->page_size;
2353         page_end = (offset + count - 1) / pPrivate->page_size;
2354
2355         LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
2356         LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
2357
2358         /* Special case: all one page */
2359         /*  */
2360         /* Otherwise: */
2361         /*    (1) non-aligned start */
2362         /*    (2) body pages */
2363         /*    (3) non-aligned end. */
2364
2365         /* Handle special case - all one page. */
2366         if (page_cur == page_end) {
2367                 LOG_DEBUG("Special case, all in one page");
2368                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2369                 if (r != ERROR_OK)
2370                         goto done;
2371
2372                 page_offset = (offset & (pPrivate->page_size-1));
2373                 memcpy(pagebuffer + page_offset,
2374                         buffer,
2375                         count);
2376
2377                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2378                 if (r != ERROR_OK)
2379                         goto done;
2380                 r = ERROR_OK;
2381                 goto done;
2382         }
2383
2384         /* non-aligned start */
2385         page_offset = offset & (pPrivate->page_size - 1);
2386         if (page_offset) {
2387                 LOG_DEBUG("Not-Aligned start");
2388                 /* read the partial */
2389                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2390                 if (r != ERROR_OK)
2391                         goto done;
2392
2393                 /* over-write with new data */
2394                 n = (pPrivate->page_size - page_offset);
2395                 memcpy(pagebuffer + page_offset,
2396                         buffer,
2397                         n);
2398
2399                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2400                 if (r != ERROR_OK)
2401                         goto done;
2402
2403                 count  -= n;
2404                 offset += n;
2405                 buffer += n;
2406                 page_cur++;
2407         }
2408
2409         /* By checking that offset is correct here, we also
2410         fix a clang warning */
2411         assert(offset % pPrivate->page_size == 0);
2412
2413         /* intermediate large pages */
2414         /* also - the final *terminal* */
2415         /* if that terminal page is a full page */
2416         LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
2417                 (int)page_cur, (int)page_end, (unsigned int)(count));
2418
2419         while ((page_cur < page_end) &&
2420                         (count >= pPrivate->page_size)) {
2421                 r = sam4_page_write(pPrivate, page_cur, buffer);
2422                 if (r != ERROR_OK)
2423                         goto done;
2424                 count -= pPrivate->page_size;
2425                 buffer += pPrivate->page_size;
2426                 page_cur += 1;
2427         }
2428
2429         /* terminal partial page? */
2430         if (count) {
2431                 LOG_DEBUG("Terminal partial page, count = 0x%08x", (unsigned int)(count));
2432                 /* we have a partial page */
2433                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2434                 if (r != ERROR_OK)
2435                         goto done;
2436                                         /* data goes at start */
2437                 memcpy(pagebuffer, buffer, count);
2438                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2439                 if (r != ERROR_OK)
2440                         goto done;
2441         }
2442         LOG_DEBUG("Done!");
2443         r = ERROR_OK;
2444 done:
2445         if (pagebuffer)
2446                 free(pagebuffer);
2447         return r;
2448 }
2449
2450 COMMAND_HANDLER(sam4_handle_info_command)
2451 {
2452         struct sam4_chip *pChip;
2453         pChip = get_current_sam4(CMD_CTX);
2454         if (!pChip)
2455                 return ERROR_OK;
2456
2457         unsigned x;
2458         int r;
2459
2460         /* bank0 must exist before we can do anything */
2461         if (pChip->details.bank[0].pBank == NULL) {
2462                 x = 0;
2463 need_define:
2464                 command_print(CMD_CTX,
2465                         "Please define bank %d via command: flash bank %s ... ",
2466                         x,
2467                         at91sam4_flash.name);
2468                 return ERROR_FAIL;
2469         }
2470
2471         /* if bank 0 is not probed, then probe it */
2472         if (!(pChip->details.bank[0].probed)) {
2473                 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2474                 if (r != ERROR_OK)
2475                         return ERROR_FAIL;
2476         }
2477         /* above guarantees the "chip details" structure is valid */
2478         /* and thus, bank private areas are valid */
2479         /* and we have a SAM4 chip, what a concept! */
2480
2481         /* auto-probe other banks, 0 done above */
2482         for (x = 1; x < SAM4_MAX_FLASH_BANKS; x++) {
2483                 /* skip banks not present */
2484                 if (!(pChip->details.bank[x].present))
2485                         continue;
2486
2487                 if (pChip->details.bank[x].pBank == NULL)
2488                         goto need_define;
2489
2490                 if (pChip->details.bank[x].probed)
2491                         continue;
2492
2493                 r = sam4_auto_probe(pChip->details.bank[x].pBank);
2494                 if (r != ERROR_OK)
2495                         return r;
2496         }
2497
2498         r = sam4_GetInfo(pChip);
2499         if (r != ERROR_OK) {
2500                 LOG_DEBUG("Sam4Info, Failed %d", r);
2501                 return r;
2502         }
2503
2504         return ERROR_OK;
2505 }
2506
2507 COMMAND_HANDLER(sam4_handle_gpnvm_command)
2508 {
2509         unsigned x, v;
2510         int r, who;
2511         struct sam4_chip *pChip;
2512
2513         pChip = get_current_sam4(CMD_CTX);
2514         if (!pChip)
2515                 return ERROR_OK;
2516
2517         if (pChip->target->state != TARGET_HALTED) {
2518                 LOG_ERROR("sam4 - target not halted");
2519                 return ERROR_TARGET_NOT_HALTED;
2520         }
2521
2522         if (pChip->details.bank[0].pBank == NULL) {
2523                 command_print(CMD_CTX, "Bank0 must be defined first via: flash bank %s ...",
2524                         at91sam4_flash.name);
2525                 return ERROR_FAIL;
2526         }
2527         if (!pChip->details.bank[0].probed) {
2528                 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2529                 if (r != ERROR_OK)
2530                         return r;
2531         }
2532
2533         switch (CMD_ARGC) {
2534                 default:
2535                         return ERROR_COMMAND_SYNTAX_ERROR;
2536                         break;
2537                 case 0:
2538                         goto showall;
2539                         break;
2540                 case 1:
2541                         who = -1;
2542                         break;
2543                 case 2:
2544                         if ((0 == strcmp(CMD_ARGV[0], "show")) && (0 == strcmp(CMD_ARGV[1], "all")))
2545                                 who = -1;
2546                         else {
2547                                 uint32_t v32;
2548                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], v32);
2549                                 who = v32;
2550                         }
2551                         break;
2552         }
2553
2554         if (0 == strcmp("show", CMD_ARGV[0])) {
2555                 if (who == -1) {
2556 showall:
2557                         r = ERROR_OK;
2558                         for (x = 0; x < pChip->details.n_gpnvms; x++) {
2559                                 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
2560                                 if (r != ERROR_OK)
2561                                         break;
2562                                 command_print(CMD_CTX, "sam4-gpnvm%u: %u", x, v);
2563                         }
2564                         return r;
2565                 }
2566                 if ((who >= 0) && (((unsigned)(who)) < pChip->details.n_gpnvms)) {
2567                         r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), who, &v);
2568                         command_print(CMD_CTX, "sam4-gpnvm%u: %u", who, v);
2569                         return r;
2570                 } else {
2571                         command_print(CMD_CTX, "sam4-gpnvm invalid GPNVM: %u", who);
2572                         return ERROR_COMMAND_SYNTAX_ERROR;
2573                 }
2574         }
2575
2576         if (who == -1) {
2577                 command_print(CMD_CTX, "Missing GPNVM number");
2578                 return ERROR_COMMAND_SYNTAX_ERROR;
2579         }
2580
2581         if (0 == strcmp("set", CMD_ARGV[0]))
2582                 r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
2583         else if ((0 == strcmp("clr", CMD_ARGV[0])) ||
2584                  (0 == strcmp("clear", CMD_ARGV[0])))                   /* quietly accept both */
2585                 r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
2586         else {
2587                 command_print(CMD_CTX, "Unknown command: %s", CMD_ARGV[0]);
2588                 r = ERROR_COMMAND_SYNTAX_ERROR;
2589         }
2590         return r;
2591 }
2592
2593 COMMAND_HANDLER(sam4_handle_slowclk_command)
2594 {
2595         struct sam4_chip *pChip;
2596
2597         pChip = get_current_sam4(CMD_CTX);
2598         if (!pChip)
2599                 return ERROR_OK;
2600
2601         switch (CMD_ARGC) {
2602                 case 0:
2603                         /* show */
2604                         break;
2605                 case 1:
2606                 {
2607                         /* set */
2608                         uint32_t v;
2609                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], v);
2610                         if (v > 200000) {
2611                                 /* absurd slow clock of 200Khz? */
2612                                 command_print(CMD_CTX, "Absurd/illegal slow clock freq: %d\n", (int)(v));
2613                                 return ERROR_COMMAND_SYNTAX_ERROR;
2614                         }
2615                         pChip->cfg.slow_freq = v;
2616                         break;
2617                 }
2618                 default:
2619                         /* error */
2620                         command_print(CMD_CTX, "Too many parameters");
2621                         return ERROR_COMMAND_SYNTAX_ERROR;
2622                         break;
2623         }
2624         command_print(CMD_CTX, "Slowclk freq: %d.%03dkhz",
2625                 (int)(pChip->cfg.slow_freq / 1000),
2626                 (int)(pChip->cfg.slow_freq % 1000));
2627         return ERROR_OK;
2628 }
2629
2630 static const struct command_registration at91sam4_exec_command_handlers[] = {
2631         {
2632                 .name = "gpnvm",
2633                 .handler = sam4_handle_gpnvm_command,
2634                 .mode = COMMAND_EXEC,
2635                 .usage = "[('clr'|'set'|'show') bitnum]",
2636                 .help = "Without arguments, shows all bits in the gpnvm "
2637                         "register.  Otherwise, clears, sets, or shows one "
2638                         "General Purpose Non-Volatile Memory (gpnvm) bit.",
2639         },
2640         {
2641                 .name = "info",
2642                 .handler = sam4_handle_info_command,
2643                 .mode = COMMAND_EXEC,
2644                 .help = "Print information about the current at91sam4 chip"
2645                         "and its flash configuration.",
2646         },
2647         {
2648                 .name = "slowclk",
2649                 .handler = sam4_handle_slowclk_command,
2650                 .mode = COMMAND_EXEC,
2651                 .usage = "[clock_hz]",
2652                 .help = "Display or set the slowclock frequency "
2653                         "(default 32768 Hz).",
2654         },
2655         COMMAND_REGISTRATION_DONE
2656 };
2657 static const struct command_registration at91sam4_command_handlers[] = {
2658         {
2659                 .name = "at91sam4",
2660                 .mode = COMMAND_ANY,
2661                 .help = "at91sam4 flash command group",
2662                 .usage = "",
2663                 .chain = at91sam4_exec_command_handlers,
2664         },
2665         COMMAND_REGISTRATION_DONE
2666 };
2667
2668 struct flash_driver at91sam4_flash = {
2669         .name = "at91sam4",
2670         .commands = at91sam4_command_handlers,
2671         .flash_bank_command = sam4_flash_bank_command,
2672         .erase = sam4_erase,
2673         .protect = sam4_protect,
2674         .write = sam4_write,
2675         .read = default_flash_read,
2676         .probe = sam4_probe,
2677         .auto_probe = sam4_auto_probe,
2678         .erase_check = default_flash_blank_check,
2679         .protect_check = sam4_protect_check,
2680 };