]> git.sur5r.net Git - openocd/blob - src/flash/nor/at91sam4.c
at91sam4: Adding support for the AT91SAM4S4A.
[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 at91sam4s* series */
300         /*atsam4s16c - LQFP100/BGA100*/
301         {
302                 .chipid_cidr    = 0x28AC0CE0,
303                 .name           = "at91sam4s16c",
304                 .total_flash_size     = 1024 * 1024,
305                 .total_sram_size      = 128 * 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 =  1024 * 1024,
320                         .nsectors   =  128,
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         /*atsam4s16b - LQFP64/QFN64*/
334         {
335                 .chipid_cidr    = 0x289C0CE0,
336                 .name           = "at91sam4s16b",
337                 .total_flash_size     = 1024 * 1024,
338                 .total_sram_size      = 128 * 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 =  1024 * 1024,
353                         .nsectors   =  128,
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         /*atsam4s16a - LQFP48/QFN48*/
367         {
368                 .chipid_cidr    = 0x288C0CE0,
369                 .name           = "at91sam4s16a",
370                 .total_flash_size     = 1024 * 1024,
371                 .total_sram_size      = 128 * 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 =  1024 * 1024,
386                         .nsectors   =  128,
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         /*atsam4s8c - LQFP100/BGA100*/
400         {
401                 .chipid_cidr    = 0x28AC0AE0,
402                 .name           = "at91sam4s8c",
403                 .total_flash_size     = 512 * 1024,
404                 .total_sram_size      = 128 * 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 =  512 * 1024,
419                         .nsectors   =  64,
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         /*atsam4s8b - LQFP64/BGA64*/
433         {
434                 .chipid_cidr    = 0x289C0AE0,
435                 .name           = "at91sam4s8b",
436                 .total_flash_size     = 512 * 1024,
437                 .total_sram_size      = 128 * 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 =  512 * 1024,
452                         .nsectors   =  64,
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         /*atsam4s8a - LQFP48/BGA48*/
466         {
467                 .chipid_cidr    = 0x288C0AE0,
468                 .name           = "at91sam4s8a",
469                 .total_flash_size     = 512 * 1024,
470                 .total_sram_size      = 128 * 1024,
471                 .n_gpnvms       = 2,
472                 .n_banks        = 1,
473                 {
474 /*              .bank[0] = {*/
475                   {
476                         .probed = 0,
477                         .pChip  = NULL,
478                         .pBank  = NULL,
479                         .bank_number = 0,
480                         .base_address = FLASH_BANK_BASE_S,
481                         .controller_address = 0x400e0a00,
482                         .flash_wait_states = 6, /* workaround silicon bug */
483                         .present = 1,
484                         .size_bytes =  512 * 1024,
485                         .nsectors   =  64,
486                         .sector_size = 8192,
487                         .page_size   = 512,
488                   },
489 /*              .bank[1] = {*/
490                   {
491                         .present = 0,
492                         .probed = 0,
493                         .bank_number = 1,
494
495                   },
496                 },
497         },
498
499         /*atsam4s4a - LQFP48/BGA48*/
500         {
501                 .chipid_cidr    = 0x288b09e0,
502                 .name           = "at91sam4s4a",
503                 .total_flash_size     = 256 * 1024,
504                 .total_sram_size      = 64 * 1024,
505                 .n_gpnvms       = 2,
506                 .n_banks        = 1,
507                 {
508 /*              .bank[0] = {*/
509                   {
510                         .probed = 0,
511                         .pChip  = NULL,
512                         .pBank  = NULL,
513                         .bank_number = 0,
514                         .base_address = FLASH_BANK_BASE_S,
515                         .controller_address = 0x400e0a00,
516                         .flash_wait_states = 6, /* workaround silicon bug */
517                         .present = 1,
518                         .size_bytes =  256 * 1024,
519                         .nsectors   =  32,
520                         .sector_size = 8192,
521                         .page_size   = 512,
522                   },
523 /*              .bank[1] = {*/
524                   {
525                         .present = 0,
526                         .probed = 0,
527                         .bank_number = 1,
528
529                   },
530                 },
531         },
532
533         /*at91sam4sd32c*/
534         {
535                 .chipid_cidr    = 0x29a70ee0,
536                 .name           = "at91sam4sd32c",
537                 .total_flash_size     = 2048 * 1024,
538                 .total_sram_size      = 160 * 1024,
539                 .n_gpnvms       = 3,
540                 .n_banks        = 2,
541
542 /*              .bank[0] = { */
543                 {
544                         {
545                                 .probed = 0,
546                                 .pChip  = NULL,
547                                 .pBank  = NULL,
548                                 .bank_number = 0,
549                                 .base_address = FLASH_BANK0_BASE_SD,
550                                 .controller_address = 0x400e0a00,
551                                 .flash_wait_states = 6, /* workaround silicon bug */
552                                 .present = 1,
553                                 .size_bytes =  1024 * 1024,
554                                 .nsectors   =  128,
555                                 .sector_size = 8192,
556                                 .page_size   = 512,
557                         },
558
559 /*              .bank[1] = { */
560                         {
561                                 .probed = 0,
562                                 .pChip  = NULL,
563                                 .pBank  = NULL,
564                                 .bank_number = 1,
565                                 .base_address = FLASH_BANK1_BASE_2048K_SD,
566                                 .controller_address = 0x400e0c00,
567                                 .flash_wait_states = 6, /* workaround silicon bug */
568                                 .present = 1,
569                                 .size_bytes =  1024 * 1024,
570                                 .nsectors   =  128,
571                                 .sector_size = 8192,
572                                 .page_size   = 512,
573                         },
574                 },
575         },
576
577         /* at91samg53n19 */
578         {
579                 .chipid_cidr    = 0x247e0ae0,
580                 .name           = "at91samg53n19",
581                 .total_flash_size     = 512 * 1024,
582                 .total_sram_size      = 96 * 1024,
583                 .n_gpnvms       = 2,
584                 .n_banks        = 1,
585
586 /*              .bank[0] = {*/
587                 {
588                         {
589                                 .probed = 0,
590                                 .pChip  = NULL,
591                                 .pBank  = NULL,
592                                 .bank_number = 0,
593                                 .base_address = FLASH_BANK_BASE_S,
594                                 .controller_address = 0x400e0a00,
595                                 .flash_wait_states = 6, /* workaround silicon bug */
596                                 .present = 1,
597                                 .size_bytes =  512 * 1024,
598                                 .nsectors   =  64,
599                                 .sector_size = 8192,
600                                 .page_size   = 512,
601                         },
602 /*              .bank[1] = {*/
603                   {
604                         .present = 0,
605                         .probed = 0,
606                         .bank_number = 1,
607
608                   },
609                 }
610         },
611
612         /* terminate */
613         {
614                 .chipid_cidr    = 0,
615                 .name                   = NULL,
616         }
617 };
618
619 /* Globals above */
620 /***********************************************************************
621  **********************************************************************
622  **********************************************************************
623  **********************************************************************
624  **********************************************************************
625  **********************************************************************/
626 /* *ATMEL* style code - from the SAM4 driver code */
627
628 /**
629  * Get the current status of the EEFC and
630  * the value of some status bits (LOCKE, PROGE).
631  * @param pPrivate - info about the bank
632  * @param v        - result goes here
633  */
634 static int EFC_GetStatus(struct sam4_bank_private *pPrivate, uint32_t *v)
635 {
636         int r;
637         r = target_read_u32(pPrivate->pChip->target,
638                         pPrivate->controller_address + offset_EFC_FSR,
639                         v);
640         LOG_DEBUG("Status: 0x%08x (lockerror: %d, cmderror: %d, ready: %d)",
641                 (unsigned int)(*v),
642                 ((unsigned int)((*v >> 2) & 1)),
643                 ((unsigned int)((*v >> 1) & 1)),
644                 ((unsigned int)((*v >> 0) & 1)));
645
646         return r;
647 }
648
649 /**
650  * Get the result of the last executed command.
651  * @param pPrivate - info about the bank
652  * @param v        - result goes here
653  */
654 static int EFC_GetResult(struct sam4_bank_private *pPrivate, uint32_t *v)
655 {
656         int r;
657         uint32_t rv;
658         r = target_read_u32(pPrivate->pChip->target,
659                         pPrivate->controller_address + offset_EFC_FRR,
660                         &rv);
661         if (v)
662                 *v = rv;
663         LOG_DEBUG("Result: 0x%08x", ((unsigned int)(rv)));
664         return r;
665 }
666
667 static int EFC_StartCommand(struct sam4_bank_private *pPrivate,
668         unsigned command, unsigned argument)
669 {
670         uint32_t n, v;
671         int r;
672         int retry;
673
674         retry = 0;
675 do_retry:
676
677         /* Check command & argument */
678         switch (command) {
679
680                 case AT91C_EFC_FCMD_WP:
681                 case AT91C_EFC_FCMD_WPL:
682                 case AT91C_EFC_FCMD_EWP:
683                 case AT91C_EFC_FCMD_EWPL:
684                 /* case AT91C_EFC_FCMD_EPL: */
685                 case AT91C_EFC_FCMD_EPA:
686                 case AT91C_EFC_FCMD_SLB:
687                 case AT91C_EFC_FCMD_CLB:
688                         n = (pPrivate->size_bytes / pPrivate->page_size);
689                         if (argument >= n)
690                                 LOG_ERROR("*BUG*: Embedded flash has only %u pages", (unsigned)(n));
691                         break;
692
693                 case AT91C_EFC_FCMD_SFB:
694                 case AT91C_EFC_FCMD_CFB:
695                         if (argument >= pPrivate->pChip->details.n_gpnvms) {
696                                 LOG_ERROR("*BUG*: Embedded flash has only %d GPNVMs",
697                                                 pPrivate->pChip->details.n_gpnvms);
698                         }
699                         break;
700
701                 case AT91C_EFC_FCMD_GETD:
702                 case AT91C_EFC_FCMD_EA:
703                 case AT91C_EFC_FCMD_GLB:
704                 case AT91C_EFC_FCMD_GFB:
705                 case AT91C_EFC_FCMD_STUI:
706                 case AT91C_EFC_FCMD_SPUI:
707                         if (argument != 0)
708                                 LOG_ERROR("Argument is meaningless for cmd: %d", command);
709                         break;
710                 default:
711                         LOG_ERROR("Unknown command %d", command);
712                         break;
713         }
714
715         if (command == AT91C_EFC_FCMD_SPUI) {
716                 /* this is a very special situation. */
717                 /* Situation (1) - error/retry - see below */
718                 /*      And we are being called recursively */
719                 /* Situation (2) - normal, finished reading unique id */
720         } else {
721                 /* it should be "ready" */
722                 EFC_GetStatus(pPrivate, &v);
723                 if (v & 1) {
724                         /* then it is ready */
725                         /* we go on */
726                 } else {
727                         if (retry) {
728                                 /* we have done this before */
729                                 /* the controller is not responding. */
730                                 LOG_ERROR("flash controller(%d) is not ready! Error",
731                                         pPrivate->bank_number);
732                                 return ERROR_FAIL;
733                         } else {
734                                 retry++;
735                                 LOG_ERROR("Flash controller(%d) is not ready, attempting reset",
736                                         pPrivate->bank_number);
737                                 /* we do that by issuing the *STOP* command */
738                                 EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0);
739                                 /* above is recursive, and further recursion is blocked by */
740                                 /* if (command == AT91C_EFC_FCMD_SPUI) above */
741                                 goto do_retry;
742                         }
743                 }
744         }
745
746         v = (0x5A << 24) | (argument << 8) | command;
747         LOG_DEBUG("Command: 0x%08x", ((unsigned int)(v)));
748         r = target_write_u32(pPrivate->pBank->target,
749                         pPrivate->controller_address + offset_EFC_FCR, v);
750         if (r != ERROR_OK)
751                 LOG_DEBUG("Error Write failed");
752         return r;
753 }
754
755 /**
756  * Performs the given command and wait until its completion (or an error).
757  * @param pPrivate - info about the bank
758  * @param command  - Command to perform.
759  * @param argument - Optional command argument.
760  * @param status   - put command status bits here
761  */
762 static int EFC_PerformCommand(struct sam4_bank_private *pPrivate,
763         unsigned command,
764         unsigned argument,
765         uint32_t *status)
766 {
767
768         int r;
769         uint32_t v;
770         long long ms_now, ms_end;
771
772         /* default */
773         if (status)
774                 *status = 0;
775
776         r = EFC_StartCommand(pPrivate, command, argument);
777         if (r != ERROR_OK)
778                 return r;
779
780         ms_end = 10000 + timeval_ms();
781
782         do {
783                 r = EFC_GetStatus(pPrivate, &v);
784                 if (r != ERROR_OK)
785                         return r;
786                 ms_now = timeval_ms();
787                 if (ms_now > ms_end) {
788                         /* error */
789                         LOG_ERROR("Command timeout");
790                         return ERROR_FAIL;
791                 }
792         } while ((v & 1) == 0);
793
794         /* error bits.. */
795         if (status)
796                 *status = (v & 0x6);
797         return ERROR_OK;
798
799 }
800
801 /**
802  * Read the unique ID.
803  * @param pPrivate - info about the bank
804  * The unique ID is stored in the 'pPrivate' structure.
805  */
806 static int FLASHD_ReadUniqueID(struct sam4_bank_private *pPrivate)
807 {
808         int r;
809         uint32_t v;
810         int x;
811         /* assume 0 */
812         pPrivate->pChip->cfg.unique_id[0] = 0;
813         pPrivate->pChip->cfg.unique_id[1] = 0;
814         pPrivate->pChip->cfg.unique_id[2] = 0;
815         pPrivate->pChip->cfg.unique_id[3] = 0;
816
817         LOG_DEBUG("Begin");
818         r = EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_STUI, 0);
819         if (r < 0)
820                 return r;
821
822         for (x = 0; x < 4; x++) {
823                 r = target_read_u32(pPrivate->pChip->target,
824                                 pPrivate->pBank->base + (x * 4),
825                                 &v);
826                 if (r < 0)
827                         return r;
828                 pPrivate->pChip->cfg.unique_id[x] = v;
829         }
830
831         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0, NULL);
832         LOG_DEBUG("End: R=%d, id = 0x%08x, 0x%08x, 0x%08x, 0x%08x",
833                 r,
834                 (unsigned int)(pPrivate->pChip->cfg.unique_id[0]),
835                 (unsigned int)(pPrivate->pChip->cfg.unique_id[1]),
836                 (unsigned int)(pPrivate->pChip->cfg.unique_id[2]),
837                 (unsigned int)(pPrivate->pChip->cfg.unique_id[3]));
838         return r;
839
840 }
841
842 /**
843  * Erases the entire flash.
844  * @param pPrivate - the info about the bank.
845  */
846 static int FLASHD_EraseEntireBank(struct sam4_bank_private *pPrivate)
847 {
848         LOG_DEBUG("Here");
849         return EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_EA, 0, NULL);
850 }
851
852 /**
853  * Erases the entire flash.
854  * @param pPrivate - the info about the bank.
855  */
856 static int FLASHD_ErasePages(struct sam4_bank_private *pPrivate,
857                                                          int firstPage,
858                                                          int numPages,
859                                                          uint32_t *status)
860 {
861         LOG_DEBUG("Here");
862         uint8_t erasePages;
863         switch (numPages)       {
864                 case 4:
865                         erasePages = 0x00;
866                         break;
867                 case 8:
868                         erasePages = 0x01;
869                         break;
870                 case 16:
871                         erasePages = 0x02;
872                         break;
873                 case 32:
874                         erasePages = 0x03;
875                         break;
876                 default:
877                         erasePages = 0x00;
878                         break;
879         }
880
881         /* AT91C_EFC_FCMD_EPA
882          * According to the datasheet FARG[15:2] defines the page from which
883          * the erase will start.This page must be modulo 4, 8, 16 or 32
884          * according to the number of pages to erase. FARG[1:0] defines the
885          * number of pages to be erased. Previously (firstpage << 2) was used
886          * to conform to this, seems it should not be shifted...
887          */
888         return EFC_PerformCommand(pPrivate,
889                 /* send Erase Page */
890                 AT91C_EFC_FCMD_EPA,
891                 (firstPage) | erasePages,
892                 status);
893 }
894
895 /**
896  * Gets current GPNVM state.
897  * @param pPrivate - info about the bank.
898  * @param gpnvm    -  GPNVM bit index.
899  * @param puthere  - result stored here.
900  */
901 /* ------------------------------------------------------------------------------ */
902 static int FLASHD_GetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm, unsigned *puthere)
903 {
904         uint32_t v;
905         int r;
906
907         LOG_DEBUG("Here");
908         if (pPrivate->bank_number != 0) {
909                 LOG_ERROR("GPNVM only works with Bank0");
910                 return ERROR_FAIL;
911         }
912
913         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
914                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
915                         gpnvm, pPrivate->pChip->details.n_gpnvms);
916                 return ERROR_FAIL;
917         }
918
919         /* Get GPNVMs status */
920         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GFB, 0, NULL);
921         if (r != ERROR_OK) {
922                 LOG_ERROR("Failed");
923                 return r;
924         }
925
926         r = EFC_GetResult(pPrivate, &v);
927
928         if (puthere) {
929                 /* Check if GPNVM is set */
930                 /* get the bit and make it a 0/1 */
931                 *puthere = (v >> gpnvm) & 1;
932         }
933
934         return r;
935 }
936
937 /**
938  * Clears the selected GPNVM bit.
939  * @param pPrivate info about the bank
940  * @param gpnvm GPNVM index.
941  * @returns 0 if successful; otherwise returns an error code.
942  */
943 static int FLASHD_ClrGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
944 {
945         int r;
946         unsigned v;
947
948         LOG_DEBUG("Here");
949         if (pPrivate->bank_number != 0) {
950                 LOG_ERROR("GPNVM only works with Bank0");
951                 return ERROR_FAIL;
952         }
953
954         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
955                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
956                         gpnvm, pPrivate->pChip->details.n_gpnvms);
957                 return ERROR_FAIL;
958         }
959
960         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
961         if (r != ERROR_OK) {
962                 LOG_DEBUG("Failed: %d", r);
963                 return r;
964         }
965         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CFB, gpnvm, NULL);
966         LOG_DEBUG("End: %d", r);
967         return r;
968 }
969
970 /**
971  * Sets the selected GPNVM bit.
972  * @param pPrivate info about the bank
973  * @param gpnvm GPNVM index.
974  */
975 static int FLASHD_SetGPNVM(struct sam4_bank_private *pPrivate, unsigned gpnvm)
976 {
977         int r;
978         unsigned v;
979
980         if (pPrivate->bank_number != 0) {
981                 LOG_ERROR("GPNVM only works with Bank0");
982                 return ERROR_FAIL;
983         }
984
985         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
986                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
987                         gpnvm, pPrivate->pChip->details.n_gpnvms);
988                 return ERROR_FAIL;
989         }
990
991         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
992         if (r != ERROR_OK)
993                 return r;
994         if (v) {
995                 /* already set */
996                 r = ERROR_OK;
997         } else {
998                 /* set it */
999                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SFB, gpnvm, NULL);
1000         }
1001         return r;
1002 }
1003
1004 /**
1005  * Returns a bit field (at most 64) of locked regions within a page.
1006  * @param pPrivate info about the bank
1007  * @param v where to store locked bits
1008  */
1009 static int FLASHD_GetLockBits(struct sam4_bank_private *pPrivate, uint32_t *v)
1010 {
1011         int r;
1012         LOG_DEBUG("Here");
1013         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GLB, 0, NULL);
1014         if (r == ERROR_OK)      {
1015                 EFC_GetResult(pPrivate, v);
1016                 EFC_GetResult(pPrivate, v);
1017                 EFC_GetResult(pPrivate, v);
1018                 r = EFC_GetResult(pPrivate, v);
1019         }
1020         LOG_DEBUG("End: %d", r);
1021         return r;
1022 }
1023
1024 /**
1025  * Unlocks all the regions in the given address range.
1026  * @param pPrivate info about the bank
1027  * @param start_sector first sector to unlock
1028  * @param end_sector last (inclusive) to unlock
1029  */
1030
1031 static int FLASHD_Unlock(struct sam4_bank_private *pPrivate,
1032         unsigned start_sector,
1033         unsigned end_sector)
1034 {
1035         int r;
1036         uint32_t status;
1037         uint32_t pg;
1038         uint32_t pages_per_sector;
1039
1040         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
1041
1042         /* Unlock all pages */
1043         while (start_sector <= end_sector) {
1044                 pg = start_sector * pages_per_sector;
1045
1046                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CLB, pg, &status);
1047                 if (r != ERROR_OK)
1048                         return r;
1049                 start_sector++;
1050         }
1051
1052         return ERROR_OK;
1053 }
1054
1055 /**
1056  * Locks regions
1057  * @param pPrivate - info about the bank
1058  * @param start_sector - first sector to lock
1059  * @param end_sector   - last sector (inclusive) to lock
1060  */
1061 static int FLASHD_Lock(struct sam4_bank_private *pPrivate,
1062         unsigned start_sector,
1063         unsigned end_sector)
1064 {
1065         uint32_t status;
1066         uint32_t pg;
1067         uint32_t pages_per_sector;
1068         int r;
1069
1070         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
1071
1072         /* Lock all pages */
1073         while (start_sector <= end_sector) {
1074                 pg = start_sector * pages_per_sector;
1075
1076                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SLB, pg, &status);
1077                 if (r != ERROR_OK)
1078                         return r;
1079                 start_sector++;
1080         }
1081         return ERROR_OK;
1082 }
1083
1084 /****** END SAM4 CODE ********/
1085
1086 /* begin helpful debug code */
1087 /* print the fieldname, the field value, in dec & hex, and return field value */
1088 static uint32_t sam4_reg_fieldname(struct sam4_chip *pChip,
1089         const char *regname,
1090         uint32_t value,
1091         unsigned shift,
1092         unsigned width)
1093 {
1094         uint32_t v;
1095         int hwidth, dwidth;
1096
1097
1098         /* extract the field */
1099         v = value >> shift;
1100         v = v & ((1 << width)-1);
1101         if (width <= 16) {
1102                 hwidth = 4;
1103                 dwidth = 5;
1104         } else {
1105                 hwidth = 8;
1106                 dwidth = 12;
1107         }
1108
1109         /* show the basics */
1110         LOG_USER_N("\t%*s: %*" PRId32 " [0x%0*" PRIx32 "] ",
1111                 REG_NAME_WIDTH, regname,
1112                 dwidth, v,
1113                 hwidth, v);
1114         return v;
1115 }
1116
1117 static const char _unknown[] = "unknown";
1118 static const char *const eproc_names[] = {
1119         _unknown,                                       /* 0 */
1120         "arm946es",                                     /* 1 */
1121         "arm7tdmi",                                     /* 2 */
1122         "cortex-m3",                            /* 3 */
1123         "arm920t",                                      /* 4 */
1124         "arm926ejs",                            /* 5 */
1125         "cortex-a5",                            /* 6 */
1126         "cortex-m4",                            /* 7 */
1127         _unknown,                                       /* 8 */
1128         _unknown,                                       /* 9 */
1129         _unknown,                                       /* 10 */
1130         _unknown,                                       /* 11 */
1131         _unknown,                                       /* 12 */
1132         _unknown,                                       /* 13 */
1133         _unknown,                                       /* 14 */
1134         _unknown,                                       /* 15 */
1135 };
1136
1137 #define nvpsize2 nvpsize                /* these two tables are identical */
1138 static const char *const nvpsize[] = {
1139         "none",                                         /*  0 */
1140         "8K bytes",                                     /*  1 */
1141         "16K bytes",                            /*  2 */
1142         "32K bytes",                            /*  3 */
1143         _unknown,                                       /*  4 */
1144         "64K bytes",                            /*  5 */
1145         _unknown,                                       /*  6 */
1146         "128K bytes",                           /*  7 */
1147         _unknown,                                       /*  8 */
1148         "256K bytes",                           /*  9 */
1149         "512K bytes",                           /* 10 */
1150         _unknown,                                       /* 11 */
1151         "1024K bytes",                          /* 12 */
1152         _unknown,                                       /* 13 */
1153         "2048K bytes",                          /* 14 */
1154         _unknown,                                       /* 15 */
1155 };
1156
1157 static const char *const sramsize[] = {
1158         "48K Bytes",                            /*  0 */
1159         "1K Bytes",                                     /*  1 */
1160         "2K Bytes",                                     /*  2 */
1161         "6K Bytes",                                     /*  3 */
1162         "112K Bytes",                           /*  4 */
1163         "4K Bytes",                                     /*  5 */
1164         "80K Bytes",                            /*  6 */
1165         "160K Bytes",                           /*  7 */
1166         "8K Bytes",                                     /*  8 */
1167         "16K Bytes",                            /*  9 */
1168         "32K Bytes",                            /* 10 */
1169         "64K Bytes",                            /* 11 */
1170         "128K Bytes",                           /* 12 */
1171         "256K Bytes",                           /* 13 */
1172         "96K Bytes",                            /* 14 */
1173         "512K Bytes",                           /* 15 */
1174
1175 };
1176
1177 static const struct archnames { unsigned value; const char *name; } archnames[] = {
1178         { 0x19,  "AT91SAM9xx Series"                                            },
1179         { 0x29,  "AT91SAM9XExx Series"                                          },
1180         { 0x34,  "AT91x34 Series"                                                       },
1181         { 0x37,  "CAP7 Series"                                                          },
1182         { 0x39,  "CAP9 Series"                                                          },
1183         { 0x3B,  "CAP11 Series"                                                         },
1184         { 0x3C, "ATSAM4E"                                                               },
1185         { 0x40,  "AT91x40 Series"                                                       },
1186         { 0x42,  "AT91x42 Series"                                                       },
1187         { 0x43,  "SAMG51 Series"
1188         },
1189         { 0x47,  "SAMG53 Series"
1190         },
1191         { 0x55,  "AT91x55 Series"                                                       },
1192         { 0x60,  "AT91SAM7Axx Series"                                           },
1193         { 0x61,  "AT91SAM7AQxx Series"                                          },
1194         { 0x63,  "AT91x63 Series"                                                       },
1195         { 0x70,  "AT91SAM7Sxx Series"                                           },
1196         { 0x71,  "AT91SAM7XCxx Series"                                          },
1197         { 0x72,  "AT91SAM7SExx Series"                                          },
1198         { 0x73,  "AT91SAM7Lxx Series"                                           },
1199         { 0x75,  "AT91SAM7Xxx Series"                                           },
1200         { 0x76,  "AT91SAM7SLxx Series"                                          },
1201         { 0x80,  "ATSAM3UxC Series (100-pin version)"           },
1202         { 0x81,  "ATSAM3UxE Series (144-pin version)"           },
1203         { 0x83,  "ATSAM3A/SAM4A xC Series (100-pin version)"},
1204         { 0x84,  "ATSAM3X/SAM4X xC Series (100-pin version)"},
1205         { 0x85,  "ATSAM3X/SAM4X xE Series (144-pin version)"},
1206         { 0x86,  "ATSAM3X/SAM4X xG Series (208/217-pin version)"        },
1207         { 0x88,  "ATSAM3S/SAM4S xA Series (48-pin version)"     },
1208         { 0x89,  "ATSAM3S/SAM4S xB Series (64-pin version)"     },
1209         { 0x8A,  "ATSAM3S/SAM4S xC Series (100-pin version)"},
1210         { 0x92,  "AT91x92 Series"                                                       },
1211         { 0x93,  "ATSAM3NxA Series (48-pin version)"            },
1212         { 0x94,  "ATSAM3NxB Series (64-pin version)"            },
1213         { 0x95,  "ATSAM3NxC Series (100-pin version)"           },
1214         { 0x98,  "ATSAM3SDxA Series (48-pin version)"           },
1215         { 0x99,  "ATSAM3SDxB Series (64-pin version)"           },
1216         { 0x9A,  "ATSAM3SDxC Series (100-pin version)"          },
1217         { 0xA5,  "ATSAM5A"                                                              },
1218         { 0xF0,  "AT75Cxx Series"                                                       },
1219         { -1, NULL },
1220 };
1221
1222 static const char *const nvptype[] = {
1223         "rom",  /* 0 */
1224         "romless or onchip flash",      /* 1 */
1225         "embedded flash memory",/* 2 */
1226         "rom(nvpsiz) + embedded flash (nvpsiz2)",       /* 3 */
1227         "sram emulating flash", /* 4 */
1228         _unknown,       /* 5 */
1229         _unknown,       /* 6 */
1230         _unknown,       /* 7 */
1231 };
1232
1233 static const char *_yes_or_no(uint32_t v)
1234 {
1235         if (v)
1236                 return "YES";
1237         else
1238                 return "NO";
1239 }
1240
1241 static const char *const _rc_freq[] = {
1242         "4 MHz", "8 MHz", "12 MHz", "reserved"
1243 };
1244
1245 static void sam4_explain_ckgr_mor(struct sam4_chip *pChip)
1246 {
1247         uint32_t v;
1248         uint32_t rcen;
1249
1250         v = sam4_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
1251         LOG_USER("(main xtal enabled: %s)", _yes_or_no(v));
1252         v = sam4_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
1253         LOG_USER("(main osc bypass: %s)", _yes_or_no(v));
1254         rcen = sam4_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 3, 1);
1255         LOG_USER("(onchip RC-OSC enabled: %s)", _yes_or_no(rcen));
1256         v = sam4_reg_fieldname(pChip, "MOSCRCF", pChip->cfg.CKGR_MOR, 4, 3);
1257         LOG_USER("(onchip RC-OSC freq: %s)", _rc_freq[v]);
1258
1259         pChip->cfg.rc_freq = 0;
1260         if (rcen) {
1261                 switch (v) {
1262                         default:
1263                                 pChip->cfg.rc_freq = 0;
1264                                 break;
1265                         case 0:
1266                                 pChip->cfg.rc_freq = 4 * 1000 * 1000;
1267                                 break;
1268                         case 1:
1269                                 pChip->cfg.rc_freq = 8 * 1000 * 1000;
1270                                 break;
1271                         case 2:
1272                                 pChip->cfg.rc_freq = 12 * 1000 * 1000;
1273                                 break;
1274                 }
1275         }
1276
1277         v = sam4_reg_fieldname(pChip, "MOSCXTST", pChip->cfg.CKGR_MOR, 8, 8);
1278         LOG_USER("(startup clks, time= %f uSecs)",
1279                 ((float)(v * 1000000)) / ((float)(pChip->cfg.slow_freq)));
1280         v = sam4_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
1281         LOG_USER("(mainosc source: %s)",
1282                 v ? "external xtal" : "internal RC");
1283
1284         v = sam4_reg_fieldname(pChip, "CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
1285         LOG_USER("(clock failure enabled: %s)",
1286                 _yes_or_no(v));
1287 }
1288
1289 static void sam4_explain_chipid_cidr(struct sam4_chip *pChip)
1290 {
1291         int x;
1292         uint32_t v;
1293         const char *cp;
1294
1295         sam4_reg_fieldname(pChip, "Version", pChip->cfg.CHIPID_CIDR, 0, 5);
1296         LOG_USER_N("\n");
1297
1298         v = sam4_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
1299         LOG_USER("%s", eproc_names[v]);
1300
1301         v = sam4_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
1302         LOG_USER("%s", nvpsize[v]);
1303
1304         v = sam4_reg_fieldname(pChip, "NVPSIZE2", pChip->cfg.CHIPID_CIDR, 12, 4);
1305         LOG_USER("%s", nvpsize2[v]);
1306
1307         v = sam4_reg_fieldname(pChip, "SRAMSIZE", pChip->cfg.CHIPID_CIDR, 16, 4);
1308         LOG_USER("%s", sramsize[v]);
1309
1310         v = sam4_reg_fieldname(pChip, "ARCH", pChip->cfg.CHIPID_CIDR, 20, 8);
1311         cp = _unknown;
1312         for (x = 0; archnames[x].name; x++) {
1313                 if (v == archnames[x].value) {
1314                         cp = archnames[x].name;
1315                         break;
1316                 }
1317         }
1318
1319         LOG_USER("%s", cp);
1320
1321         v = sam4_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
1322         LOG_USER("%s", nvptype[v]);
1323
1324         v = sam4_reg_fieldname(pChip, "EXTID", pChip->cfg.CHIPID_CIDR, 31, 1);
1325         LOG_USER("(exists: %s)", _yes_or_no(v));
1326 }
1327
1328 static void sam4_explain_ckgr_mcfr(struct sam4_chip *pChip)
1329 {
1330         uint32_t v;
1331
1332         v = sam4_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
1333         LOG_USER("(main ready: %s)", _yes_or_no(v));
1334
1335         v = sam4_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
1336
1337         v = (v * pChip->cfg.slow_freq) / 16;
1338         pChip->cfg.mainosc_freq = v;
1339
1340         LOG_USER("(%3.03f Mhz (%" PRIu32 ".%03" PRIu32 "khz slowclk)",
1341                 _tomhz(v),
1342                 (uint32_t)(pChip->cfg.slow_freq / 1000),
1343                 (uint32_t)(pChip->cfg.slow_freq % 1000));
1344 }
1345
1346 static void sam4_explain_ckgr_plla(struct sam4_chip *pChip)
1347 {
1348         uint32_t mula, diva;
1349
1350         diva = sam4_reg_fieldname(pChip, "DIVA", pChip->cfg.CKGR_PLLAR, 0, 8);
1351         LOG_USER_N("\n");
1352         mula = sam4_reg_fieldname(pChip, "MULA", pChip->cfg.CKGR_PLLAR, 16, 11);
1353         LOG_USER_N("\n");
1354         pChip->cfg.plla_freq = 0;
1355         if (mula == 0)
1356                 LOG_USER("\tPLLA Freq: (Disabled,mula = 0)");
1357         else if (diva == 0)
1358                 LOG_USER("\tPLLA Freq: (Disabled,diva = 0)");
1359         else if (diva >= 1) {
1360                 pChip->cfg.plla_freq = (pChip->cfg.mainosc_freq * (mula + 1) / diva);
1361                 LOG_USER("\tPLLA Freq: %3.03f MHz",
1362                         _tomhz(pChip->cfg.plla_freq));
1363         }
1364 }
1365
1366 static void sam4_explain_mckr(struct sam4_chip *pChip)
1367 {
1368         uint32_t css, pres, fin = 0;
1369         int pdiv = 0;
1370         const char *cp = NULL;
1371
1372         css = sam4_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
1373         switch (css & 3) {
1374                 case 0:
1375                         fin = pChip->cfg.slow_freq;
1376                         cp = "slowclk";
1377                         break;
1378                 case 1:
1379                         fin = pChip->cfg.mainosc_freq;
1380                         cp  = "mainosc";
1381                         break;
1382                 case 2:
1383                         fin = pChip->cfg.plla_freq;
1384                         cp  = "plla";
1385                         break;
1386                 case 3:
1387                         if (pChip->cfg.CKGR_UCKR & (1 << 16)) {
1388                                 fin = 480 * 1000 * 1000;
1389                                 cp = "upll";
1390                         } else {
1391                                 fin = 0;
1392                                 cp  = "upll (*ERROR* UPLL is disabled)";
1393                         }
1394                         break;
1395                 default:
1396                         assert(0);
1397                         break;
1398         }
1399
1400         LOG_USER("%s (%3.03f Mhz)",
1401                 cp,
1402                 _tomhz(fin));
1403         pres = sam4_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
1404         switch (pres & 0x07) {
1405                 case 0:
1406                         pdiv = 1;
1407                         cp = "selected clock";
1408                         break;
1409                 case 1:
1410                         pdiv = 2;
1411                         cp = "clock/2";
1412                         break;
1413                 case 2:
1414                         pdiv = 4;
1415                         cp = "clock/4";
1416                         break;
1417                 case 3:
1418                         pdiv = 8;
1419                         cp = "clock/8";
1420                         break;
1421                 case 4:
1422                         pdiv = 16;
1423                         cp = "clock/16";
1424                         break;
1425                 case 5:
1426                         pdiv = 32;
1427                         cp = "clock/32";
1428                         break;
1429                 case 6:
1430                         pdiv = 64;
1431                         cp = "clock/64";
1432                         break;
1433                 case 7:
1434                         pdiv = 6;
1435                         cp = "clock/6";
1436                         break;
1437                 default:
1438                         assert(0);
1439                         break;
1440         }
1441         LOG_USER("(%s)", cp);
1442         fin = fin / pdiv;
1443         /* sam4 has a *SINGLE* clock - */
1444         /* other at91 series parts have divisors for these. */
1445         pChip->cfg.cpu_freq = fin;
1446         pChip->cfg.mclk_freq = fin;
1447         pChip->cfg.fclk_freq = fin;
1448         LOG_USER("\t\tResult CPU Freq: %3.03f",
1449                 _tomhz(fin));
1450 }
1451
1452 #if 0
1453 static struct sam4_chip *target2sam4(struct target *pTarget)
1454 {
1455         struct sam4_chip *pChip;
1456
1457         if (pTarget == NULL)
1458                 return NULL;
1459
1460         pChip = all_sam4_chips;
1461         while (pChip) {
1462                 if (pChip->target == pTarget)
1463                         break;  /* return below */
1464                 else
1465                         pChip = pChip->next;
1466         }
1467         return pChip;
1468 }
1469 #endif
1470
1471 static uint32_t *sam4_get_reg_ptr(struct sam4_cfg *pCfg, const struct sam4_reg_list *pList)
1472 {
1473         /* this function exists to help */
1474         /* keep funky offsetof() errors */
1475         /* and casting from causing bugs */
1476
1477         /* By using prototypes - we can detect what would */
1478         /* be casting errors. */
1479
1480         return (uint32_t *)(void *)(((char *)(pCfg)) + pList->struct_offset);
1481 }
1482
1483
1484 #define SAM4_ENTRY(NAME, FUNC)  { .address = SAM4_ ## NAME, .struct_offset = offsetof( \
1485                                                   struct sam4_cfg, \
1486                                                   NAME), # NAME, FUNC }
1487 static const struct sam4_reg_list sam4_all_regs[] = {
1488         SAM4_ENTRY(CKGR_MOR, sam4_explain_ckgr_mor),
1489         SAM4_ENTRY(CKGR_MCFR, sam4_explain_ckgr_mcfr),
1490         SAM4_ENTRY(CKGR_PLLAR, sam4_explain_ckgr_plla),
1491         SAM4_ENTRY(CKGR_UCKR, NULL),
1492         SAM4_ENTRY(PMC_FSMR, NULL),
1493         SAM4_ENTRY(PMC_FSPR, NULL),
1494         SAM4_ENTRY(PMC_IMR, NULL),
1495         SAM4_ENTRY(PMC_MCKR, sam4_explain_mckr),
1496         SAM4_ENTRY(PMC_PCK0, NULL),
1497         SAM4_ENTRY(PMC_PCK1, NULL),
1498         SAM4_ENTRY(PMC_PCK2, NULL),
1499         SAM4_ENTRY(PMC_PCSR, NULL),
1500         SAM4_ENTRY(PMC_SCSR, NULL),
1501         SAM4_ENTRY(PMC_SR, NULL),
1502         SAM4_ENTRY(CHIPID_CIDR, sam4_explain_chipid_cidr),
1503         SAM4_ENTRY(CHIPID_EXID, NULL),
1504         /* TERMINATE THE LIST */
1505         { .name = NULL }
1506 };
1507 #undef SAM4_ENTRY
1508
1509 static struct sam4_bank_private *get_sam4_bank_private(struct flash_bank *bank)
1510 {
1511         return bank->driver_priv;
1512 }
1513
1514 /**
1515  * Given a pointer to where it goes in the structure,
1516  * determine the register name, address from the all registers table.
1517  */
1518 static const struct sam4_reg_list *sam4_GetReg(struct sam4_chip *pChip, uint32_t *goes_here)
1519 {
1520         const struct sam4_reg_list *pReg;
1521
1522         pReg = &(sam4_all_regs[0]);
1523         while (pReg->name) {
1524                 uint32_t *pPossible;
1525
1526                 /* calculate where this one go.. */
1527                 /* it is "possibly" this register. */
1528
1529                 pPossible = ((uint32_t *)(void *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
1530
1531                 /* well? Is it this register */
1532                 if (pPossible == goes_here) {
1533                         /* Jump for joy! */
1534                         return pReg;
1535                 }
1536
1537                 /* next... */
1538                 pReg++;
1539         }
1540         /* This is *TOTAL*PANIC* - we are totally screwed. */
1541         LOG_ERROR("INVALID SAM4 REGISTER");
1542         return NULL;
1543 }
1544
1545 static int sam4_ReadThisReg(struct sam4_chip *pChip, uint32_t *goes_here)
1546 {
1547         const struct sam4_reg_list *pReg;
1548         int r;
1549
1550         pReg = sam4_GetReg(pChip, goes_here);
1551         if (!pReg)
1552                 return ERROR_FAIL;
1553
1554         r = target_read_u32(pChip->target, pReg->address, goes_here);
1555         if (r != ERROR_OK) {
1556                 LOG_ERROR("Cannot read SAM4 register: %s @ 0x%08x, Err: %d",
1557                         pReg->name, (unsigned)(pReg->address), r);
1558         }
1559         return r;
1560 }
1561
1562 static int sam4_ReadAllRegs(struct sam4_chip *pChip)
1563 {
1564         int r;
1565         const struct sam4_reg_list *pReg;
1566
1567         pReg = &(sam4_all_regs[0]);
1568         while (pReg->name) {
1569                 r = sam4_ReadThisReg(pChip,
1570                                 sam4_get_reg_ptr(&(pChip->cfg), pReg));
1571                 if (r != ERROR_OK) {
1572                         LOG_ERROR("Cannot read SAM4 register: %s @ 0x%08x, Error: %d",
1573                                 pReg->name, ((unsigned)(pReg->address)), r);
1574                         return r;
1575                 }
1576                 pReg++;
1577         }
1578
1579         return ERROR_OK;
1580 }
1581
1582 static int sam4_GetInfo(struct sam4_chip *pChip)
1583 {
1584         const struct sam4_reg_list *pReg;
1585         uint32_t regval;
1586
1587         pReg = &(sam4_all_regs[0]);
1588         while (pReg->name) {
1589                 /* display all regs */
1590                 LOG_DEBUG("Start: %s", pReg->name);
1591                 regval = *sam4_get_reg_ptr(&(pChip->cfg), pReg);
1592                 LOG_USER("%*s: [0x%08" PRIx32 "] -> 0x%08" PRIx32,
1593                         REG_NAME_WIDTH,
1594                         pReg->name,
1595                         pReg->address,
1596                         regval);
1597                 if (pReg->explain_func)
1598                         (*(pReg->explain_func))(pChip);
1599                 LOG_DEBUG("End: %s", pReg->name);
1600                 pReg++;
1601         }
1602         LOG_USER("   rc-osc: %3.03f MHz", _tomhz(pChip->cfg.rc_freq));
1603         LOG_USER("  mainosc: %3.03f MHz", _tomhz(pChip->cfg.mainosc_freq));
1604         LOG_USER("     plla: %3.03f MHz", _tomhz(pChip->cfg.plla_freq));
1605         LOG_USER(" cpu-freq: %3.03f MHz", _tomhz(pChip->cfg.cpu_freq));
1606         LOG_USER("mclk-freq: %3.03f MHz", _tomhz(pChip->cfg.mclk_freq));
1607
1608         LOG_USER(" UniqueId: 0x%08" PRIx32 " 0x%08" PRIx32 " 0x%08" PRIx32 " 0x%08"PRIx32,
1609                 pChip->cfg.unique_id[0],
1610                 pChip->cfg.unique_id[1],
1611                 pChip->cfg.unique_id[2],
1612                 pChip->cfg.unique_id[3]);
1613
1614         return ERROR_OK;
1615 }
1616
1617 static int sam4_protect_check(struct flash_bank *bank)
1618 {
1619         int r;
1620         uint32_t v[4] = {0};
1621         unsigned x;
1622         struct sam4_bank_private *pPrivate;
1623
1624         LOG_DEBUG("Begin");
1625         if (bank->target->state != TARGET_HALTED) {
1626                 LOG_ERROR("Target not halted");
1627                 return ERROR_TARGET_NOT_HALTED;
1628         }
1629
1630         pPrivate = get_sam4_bank_private(bank);
1631         if (!pPrivate) {
1632                 LOG_ERROR("no private for this bank?");
1633                 return ERROR_FAIL;
1634         }
1635         if (!(pPrivate->probed))
1636                 return ERROR_FLASH_BANK_NOT_PROBED;
1637
1638         r = FLASHD_GetLockBits(pPrivate, v);
1639         if (r != ERROR_OK) {
1640                 LOG_DEBUG("Failed: %d", r);
1641                 return r;
1642         }
1643
1644         for (x = 0; x < pPrivate->nsectors; x++)
1645                 bank->sectors[x].is_protected = (!!(v[x >> 5] & (1 << (x % 32))));
1646         LOG_DEBUG("Done");
1647         return ERROR_OK;
1648 }
1649
1650 FLASH_BANK_COMMAND_HANDLER(sam4_flash_bank_command)
1651 {
1652         struct sam4_chip *pChip;
1653
1654         pChip = all_sam4_chips;
1655
1656         /* is this an existing chip? */
1657         while (pChip) {
1658                 if (pChip->target == bank->target)
1659                         break;
1660                 pChip = pChip->next;
1661         }
1662
1663         if (!pChip) {
1664                 /* this is a *NEW* chip */
1665                 pChip = calloc(1, sizeof(struct sam4_chip));
1666                 if (!pChip) {
1667                         LOG_ERROR("NO RAM!");
1668                         return ERROR_FAIL;
1669                 }
1670                 pChip->target = bank->target;
1671                 /* insert at head */
1672                 pChip->next = all_sam4_chips;
1673                 all_sam4_chips = pChip;
1674                 pChip->target = bank->target;
1675                 /* assumption is this runs at 32khz */
1676                 pChip->cfg.slow_freq = 32768;
1677                 pChip->probed = 0;
1678         }
1679
1680         switch (bank->base) {
1681                 default:
1682                         LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x"
1683                                 "[at91sam4s series] )",
1684                                 ((unsigned int)(bank->base)),
1685                                 ((unsigned int)(FLASH_BANK_BASE_S)));
1686                         return ERROR_FAIL;
1687                         break;
1688
1689                 /* at91sam4s series only has bank 0*/
1690                 /* at91sam4sd series has the same address for bank 0 (FLASH_BANK0_BASE_SD)*/
1691                 case FLASH_BANK_BASE_S:
1692                         bank->driver_priv = &(pChip->details.bank[0]);
1693                         bank->bank_number = 0;
1694                         pChip->details.bank[0].pChip = pChip;
1695                         pChip->details.bank[0].pBank = bank;
1696                         break;
1697
1698                 /* Bank 1 of at91sam4sd series */
1699                 case FLASH_BANK1_BASE_1024K_SD:
1700                 case FLASH_BANK1_BASE_2048K_SD:
1701                         bank->driver_priv = &(pChip->details.bank[1]);
1702                         bank->bank_number = 1;
1703                         pChip->details.bank[1].pChip = pChip;
1704                         pChip->details.bank[1].pBank = bank;
1705                         break;
1706         }
1707
1708         /* we initialize after probing. */
1709         return ERROR_OK;
1710 }
1711
1712 static int sam4_GetDetails(struct sam4_bank_private *pPrivate)
1713 {
1714         const struct sam4_chip_details *pDetails;
1715         struct sam4_chip *pChip;
1716         struct flash_bank *saved_banks[SAM4_MAX_FLASH_BANKS];
1717         unsigned x;
1718
1719         LOG_DEBUG("Begin");
1720         pDetails = all_sam4_details;
1721         while (pDetails->name) {
1722                 /* Compare cidr without version bits */
1723                 if (pDetails->chipid_cidr == (pPrivate->pChip->cfg.CHIPID_CIDR & 0xFFFFFFE0))
1724                         break;
1725                 else
1726                         pDetails++;
1727         }
1728         if (pDetails->name == NULL) {
1729                 LOG_ERROR("SAM4 ChipID 0x%08x not found in table (perhaps you can ID this chip?)",
1730                         (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
1731                 /* Help the victim, print details about the chip */
1732                 LOG_INFO("SAM4 CHIPID_CIDR: 0x%08" PRIx32 " decodes as follows",
1733                         pPrivate->pChip->cfg.CHIPID_CIDR);
1734                 sam4_explain_chipid_cidr(pPrivate->pChip);
1735                 return ERROR_FAIL;
1736         }
1737
1738         /* DANGER: THERE ARE DRAGONS HERE */
1739
1740         /* get our pChip - it is going */
1741         /* to be over-written shortly */
1742         pChip = pPrivate->pChip;
1743
1744         /* Note that, in reality: */
1745         /*  */
1746         /*     pPrivate = &(pChip->details.bank[0]) */
1747         /* or  pPrivate = &(pChip->details.bank[1]) */
1748         /*  */
1749
1750         /* save the "bank" pointers */
1751         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++)
1752                 saved_banks[x] = pChip->details.bank[x].pBank;
1753
1754         /* Overwrite the "details" structure. */
1755         memcpy(&(pPrivate->pChip->details),
1756                 pDetails,
1757                 sizeof(pPrivate->pChip->details));
1758
1759         /* now fix the ghosted pointers */
1760         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
1761                 pChip->details.bank[x].pChip = pChip;
1762                 pChip->details.bank[x].pBank = saved_banks[x];
1763         }
1764
1765         /* update the *BANK*SIZE* */
1766
1767         LOG_DEBUG("End");
1768         return ERROR_OK;
1769 }
1770
1771 static int _sam4_probe(struct flash_bank *bank, int noise)
1772 {
1773         unsigned x;
1774         int r;
1775         struct sam4_bank_private *pPrivate;
1776
1777
1778         LOG_DEBUG("Begin: Bank: %d, Noise: %d", bank->bank_number, noise);
1779         if (bank->target->state != TARGET_HALTED) {
1780                 LOG_ERROR("Target not halted");
1781                 return ERROR_TARGET_NOT_HALTED;
1782         }
1783
1784         pPrivate = get_sam4_bank_private(bank);
1785         if (!pPrivate) {
1786                 LOG_ERROR("Invalid/unknown bank number");
1787                 return ERROR_FAIL;
1788         }
1789
1790         r = sam4_ReadAllRegs(pPrivate->pChip);
1791         if (r != ERROR_OK)
1792                 return r;
1793
1794         LOG_DEBUG("Here");
1795         if (pPrivate->pChip->probed)
1796                 r = sam4_GetInfo(pPrivate->pChip);
1797         else
1798                 r = sam4_GetDetails(pPrivate);
1799         if (r != ERROR_OK)
1800                 return r;
1801
1802         /* update the flash bank size */
1803         for (x = 0; x < SAM4_MAX_FLASH_BANKS; x++) {
1804                 if (bank->base == pPrivate->pChip->details.bank[x].base_address) {
1805                         bank->size = pPrivate->pChip->details.bank[x].size_bytes;
1806                         break;
1807                 }
1808         }
1809
1810         if (bank->sectors == NULL) {
1811                 bank->sectors = calloc(pPrivate->nsectors, (sizeof((bank->sectors)[0])));
1812                 if (bank->sectors == NULL) {
1813                         LOG_ERROR("No memory!");
1814                         return ERROR_FAIL;
1815                 }
1816                 bank->num_sectors = pPrivate->nsectors;
1817
1818                 for (x = 0; ((int)(x)) < bank->num_sectors; x++) {
1819                         bank->sectors[x].size = pPrivate->sector_size;
1820                         bank->sectors[x].offset = x * (pPrivate->sector_size);
1821                         /* mark as unknown */
1822                         bank->sectors[x].is_erased = -1;
1823                         bank->sectors[x].is_protected = -1;
1824                 }
1825         }
1826
1827         pPrivate->probed = 1;
1828
1829         r = sam4_protect_check(bank);
1830         if (r != ERROR_OK)
1831                 return r;
1832
1833         LOG_DEBUG("Bank = %d, nbanks = %d",
1834                 pPrivate->bank_number, pPrivate->pChip->details.n_banks);
1835         if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
1836                 /* read unique id, */
1837                 /* it appears to be associated with the *last* flash bank. */
1838                 FLASHD_ReadUniqueID(pPrivate);
1839         }
1840
1841         return r;
1842 }
1843
1844 static int sam4_probe(struct flash_bank *bank)
1845 {
1846         return _sam4_probe(bank, 1);
1847 }
1848
1849 static int sam4_auto_probe(struct flash_bank *bank)
1850 {
1851         return _sam4_probe(bank, 0);
1852 }
1853
1854 static int sam4_erase(struct flash_bank *bank, int first, int last)
1855 {
1856         struct sam4_bank_private *pPrivate;
1857         int r;
1858         int i;
1859         int pageCount;
1860         /*16 pages equals 8KB - Same size as a lock region*/
1861         pageCount = 16;
1862         uint32_t status;
1863
1864         LOG_DEBUG("Here");
1865         if (bank->target->state != TARGET_HALTED) {
1866                 LOG_ERROR("Target not halted");
1867                 return ERROR_TARGET_NOT_HALTED;
1868         }
1869
1870         r = sam4_auto_probe(bank);
1871         if (r != ERROR_OK) {
1872                 LOG_DEBUG("Here,r=%d", r);
1873                 return r;
1874         }
1875
1876         pPrivate = get_sam4_bank_private(bank);
1877         if (!(pPrivate->probed))
1878                 return ERROR_FLASH_BANK_NOT_PROBED;
1879
1880         if ((first == 0) && ((last + 1) == ((int)(pPrivate->nsectors)))) {
1881                 /* whole chip */
1882                 LOG_DEBUG("Here");
1883                 return FLASHD_EraseEntireBank(pPrivate);
1884         }
1885         LOG_INFO("sam4 does not auto-erase while programming (Erasing relevant sectors)");
1886         LOG_INFO("sam4 First: 0x%08x Last: 0x%08x", (unsigned int)(first), (unsigned int)(last));
1887         for (i = first; i <= last; i++) {
1888                 /*16 pages equals 8KB - Same size as a lock region*/
1889                 r = FLASHD_ErasePages(pPrivate, (i * pageCount), pageCount, &status);
1890                 LOG_INFO("Erasing sector: 0x%08x", (unsigned int)(i));
1891                 if (r != ERROR_OK)
1892                         LOG_ERROR("SAM4: Error performing Erase page @ lock region number %d",
1893                                 (unsigned int)(i));
1894                 if (status & (1 << 2)) {
1895                         LOG_ERROR("SAM4: Lock Region %d is locked", (unsigned int)(i));
1896                         return ERROR_FAIL;
1897                 }
1898                 if (status & (1 << 1)) {
1899                         LOG_ERROR("SAM4: Flash Command error @lock region %d", (unsigned int)(i));
1900                         return ERROR_FAIL;
1901                 }
1902         }
1903
1904         return ERROR_OK;
1905 }
1906
1907 static int sam4_protect(struct flash_bank *bank, int set, int first, int last)
1908 {
1909         struct sam4_bank_private *pPrivate;
1910         int r;
1911
1912         LOG_DEBUG("Here");
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->probed))
1920                 return ERROR_FLASH_BANK_NOT_PROBED;
1921
1922         if (set)
1923                 r = FLASHD_Lock(pPrivate, (unsigned)(first), (unsigned)(last));
1924         else
1925                 r = FLASHD_Unlock(pPrivate, (unsigned)(first), (unsigned)(last));
1926         LOG_DEBUG("End: r=%d", r);
1927
1928         return r;
1929
1930 }
1931
1932 static int sam4_page_read(struct sam4_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
1933 {
1934         uint32_t adr;
1935         int r;
1936
1937         adr = pagenum * pPrivate->page_size;
1938         adr = adr + pPrivate->base_address;
1939
1940         r = target_read_memory(pPrivate->pChip->target,
1941                         adr,
1942                         4,                                      /* THIS*MUST*BE* in 32bit values */
1943                         pPrivate->page_size / 4,
1944                         buf);
1945         if (r != ERROR_OK)
1946                 LOG_ERROR("SAM4: Flash program failed to read page phys address: 0x%08x",
1947                         (unsigned int)(adr));
1948         return r;
1949 }
1950
1951 static int sam4_page_write(struct sam4_bank_private *pPrivate, unsigned pagenum, const uint8_t *buf)
1952 {
1953         uint32_t adr;
1954         uint32_t status;
1955         uint32_t fmr;   /* EEFC Flash Mode Register */
1956         int r;
1957
1958         adr = pagenum * pPrivate->page_size;
1959         adr = (adr + pPrivate->base_address);
1960
1961         /* Get flash mode register value */
1962         r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address, &fmr);
1963         if (r != ERROR_OK)
1964                 LOG_DEBUG("Error Read failed: read flash mode register");
1965
1966         /* Clear flash wait state field */
1967         fmr &= 0xfffff0ff;
1968
1969         /* set FWS (flash wait states) field in the FMR (flash mode register) */
1970         fmr |= (pPrivate->flash_wait_states << 8);
1971
1972         LOG_DEBUG("Flash Mode: 0x%08x", ((unsigned int)(fmr)));
1973         r = target_write_u32(pPrivate->pBank->target, pPrivate->controller_address, fmr);
1974         if (r != ERROR_OK)
1975                 LOG_DEBUG("Error Write failed: set flash mode register");
1976
1977         /* 1st sector 8kBytes - page 0 - 15*/
1978         /* 2nd sector 8kBytes - page 16 - 30*/
1979         /* 3rd sector 48kBytes - page 31 - 127*/
1980         LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
1981         r = target_write_memory(pPrivate->pChip->target,
1982                         adr,
1983                         4,                                      /* THIS*MUST*BE* in 32bit values */
1984                         pPrivate->page_size / 4,
1985                         buf);
1986         if (r != ERROR_OK) {
1987                 LOG_ERROR("SAM4: Failed to write (buffer) page at phys address 0x%08x",
1988                         (unsigned int)(adr));
1989                 return r;
1990         }
1991
1992         r = EFC_PerformCommand(pPrivate,
1993                         /* send Erase & Write Page */
1994                         AT91C_EFC_FCMD_WP,      /*AT91C_EFC_FCMD_EWP only works on first two 8kb sectors*/
1995                         pagenum,
1996                         &status);
1997
1998         if (r != ERROR_OK)
1999                 LOG_ERROR("SAM4: Error performing Write page @ phys address 0x%08x",
2000                         (unsigned int)(adr));
2001         if (status & (1 << 2)) {
2002                 LOG_ERROR("SAM4: Page @ Phys address 0x%08x is locked", (unsigned int)(adr));
2003                 return ERROR_FAIL;
2004         }
2005         if (status & (1 << 1)) {
2006                 LOG_ERROR("SAM4: Flash Command error @phys address 0x%08x", (unsigned int)(adr));
2007                 return ERROR_FAIL;
2008         }
2009         return ERROR_OK;
2010 }
2011
2012 static int sam4_write(struct flash_bank *bank,
2013         const uint8_t *buffer,
2014         uint32_t offset,
2015         uint32_t count)
2016 {
2017         int n;
2018         unsigned page_cur;
2019         unsigned page_end;
2020         int r;
2021         unsigned page_offset;
2022         struct sam4_bank_private *pPrivate;
2023         uint8_t *pagebuffer;
2024
2025         /* incase we bail further below, set this to null */
2026         pagebuffer = NULL;
2027
2028         /* ignore dumb requests */
2029         if (count == 0) {
2030                 r = ERROR_OK;
2031                 goto done;
2032         }
2033
2034         if (bank->target->state != TARGET_HALTED) {
2035                 LOG_ERROR("Target not halted");
2036                 r = ERROR_TARGET_NOT_HALTED;
2037                 goto done;
2038         }
2039
2040         pPrivate = get_sam4_bank_private(bank);
2041         if (!(pPrivate->probed)) {
2042                 r = ERROR_FLASH_BANK_NOT_PROBED;
2043                 goto done;
2044         }
2045
2046         if ((offset + count) > pPrivate->size_bytes) {
2047                 LOG_ERROR("Flash write error - past end of bank");
2048                 LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
2049                         (unsigned int)(offset),
2050                         (unsigned int)(count),
2051                         (unsigned int)(pPrivate->size_bytes));
2052                 r = ERROR_FAIL;
2053                 goto done;
2054         }
2055
2056         pagebuffer = malloc(pPrivate->page_size);
2057         if (!pagebuffer) {
2058                 LOG_ERROR("No memory for %d Byte page buffer", (int)(pPrivate->page_size));
2059                 r = ERROR_FAIL;
2060                 goto done;
2061         }
2062
2063         /* what page do we start & end in? */
2064         page_cur = offset / pPrivate->page_size;
2065         page_end = (offset + count - 1) / pPrivate->page_size;
2066
2067         LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
2068         LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
2069
2070         /* Special case: all one page */
2071         /*  */
2072         /* Otherwise: */
2073         /*    (1) non-aligned start */
2074         /*    (2) body pages */
2075         /*    (3) non-aligned end. */
2076
2077         /* Handle special case - all one page. */
2078         if (page_cur == page_end) {
2079                 LOG_DEBUG("Special case, all in one page");
2080                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2081                 if (r != ERROR_OK)
2082                         goto done;
2083
2084                 page_offset = (offset & (pPrivate->page_size-1));
2085                 memcpy(pagebuffer + page_offset,
2086                         buffer,
2087                         count);
2088
2089                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2090                 if (r != ERROR_OK)
2091                         goto done;
2092                 r = ERROR_OK;
2093                 goto done;
2094         }
2095
2096         /* non-aligned start */
2097         page_offset = offset & (pPrivate->page_size - 1);
2098         if (page_offset) {
2099                 LOG_DEBUG("Not-Aligned start");
2100                 /* read the partial */
2101                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2102                 if (r != ERROR_OK)
2103                         goto done;
2104
2105                 /* over-write with new data */
2106                 n = (pPrivate->page_size - page_offset);
2107                 memcpy(pagebuffer + page_offset,
2108                         buffer,
2109                         n);
2110
2111                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2112                 if (r != ERROR_OK)
2113                         goto done;
2114
2115                 count  -= n;
2116                 offset += n;
2117                 buffer += n;
2118                 page_cur++;
2119         }
2120
2121         /* By checking that offset is correct here, we also
2122         fix a clang warning */
2123         assert(offset % pPrivate->page_size == 0);
2124
2125         /* intermediate large pages */
2126         /* also - the final *terminal* */
2127         /* if that terminal page is a full page */
2128         LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
2129                 (int)page_cur, (int)page_end, (unsigned int)(count));
2130
2131         while ((page_cur < page_end) &&
2132                         (count >= pPrivate->page_size)) {
2133                 r = sam4_page_write(pPrivate, page_cur, buffer);
2134                 if (r != ERROR_OK)
2135                         goto done;
2136                 count -= pPrivate->page_size;
2137                 buffer += pPrivate->page_size;
2138                 page_cur += 1;
2139         }
2140
2141         /* terminal partial page? */
2142         if (count) {
2143                 LOG_DEBUG("Terminal partial page, count = 0x%08x", (unsigned int)(count));
2144                 /* we have a partial page */
2145                 r = sam4_page_read(pPrivate, page_cur, pagebuffer);
2146                 if (r != ERROR_OK)
2147                         goto done;
2148                                         /* data goes at start */
2149                 memcpy(pagebuffer, buffer, count);
2150                 r = sam4_page_write(pPrivate, page_cur, pagebuffer);
2151                 if (r != ERROR_OK)
2152                         goto done;
2153         }
2154         LOG_DEBUG("Done!");
2155         r = ERROR_OK;
2156 done:
2157         if (pagebuffer)
2158                 free(pagebuffer);
2159         return r;
2160 }
2161
2162 COMMAND_HANDLER(sam4_handle_info_command)
2163 {
2164         struct sam4_chip *pChip;
2165         pChip = get_current_sam4(CMD_CTX);
2166         if (!pChip)
2167                 return ERROR_OK;
2168
2169         unsigned x;
2170         int r;
2171
2172         /* bank0 must exist before we can do anything */
2173         if (pChip->details.bank[0].pBank == NULL) {
2174                 x = 0;
2175 need_define:
2176                 command_print(CMD_CTX,
2177                         "Please define bank %d via command: flash bank %s ... ",
2178                         x,
2179                         at91sam4_flash.name);
2180                 return ERROR_FAIL;
2181         }
2182
2183         /* if bank 0 is not probed, then probe it */
2184         if (!(pChip->details.bank[0].probed)) {
2185                 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2186                 if (r != ERROR_OK)
2187                         return ERROR_FAIL;
2188         }
2189         /* above guarantees the "chip details" structure is valid */
2190         /* and thus, bank private areas are valid */
2191         /* and we have a SAM4 chip, what a concept! */
2192
2193         /* auto-probe other banks, 0 done above */
2194         for (x = 1; x < SAM4_MAX_FLASH_BANKS; x++) {
2195                 /* skip banks not present */
2196                 if (!(pChip->details.bank[x].present))
2197                         continue;
2198
2199                 if (pChip->details.bank[x].pBank == NULL)
2200                         goto need_define;
2201
2202                 if (pChip->details.bank[x].probed)
2203                         continue;
2204
2205                 r = sam4_auto_probe(pChip->details.bank[x].pBank);
2206                 if (r != ERROR_OK)
2207                         return r;
2208         }
2209
2210         r = sam4_GetInfo(pChip);
2211         if (r != ERROR_OK) {
2212                 LOG_DEBUG("Sam4Info, Failed %d", r);
2213                 return r;
2214         }
2215
2216         return ERROR_OK;
2217 }
2218
2219 COMMAND_HANDLER(sam4_handle_gpnvm_command)
2220 {
2221         unsigned x, v;
2222         int r, who;
2223         struct sam4_chip *pChip;
2224
2225         pChip = get_current_sam4(CMD_CTX);
2226         if (!pChip)
2227                 return ERROR_OK;
2228
2229         if (pChip->target->state != TARGET_HALTED) {
2230                 LOG_ERROR("sam4 - target not halted");
2231                 return ERROR_TARGET_NOT_HALTED;
2232         }
2233
2234         if (pChip->details.bank[0].pBank == NULL) {
2235                 command_print(CMD_CTX, "Bank0 must be defined first via: flash bank %s ...",
2236                         at91sam4_flash.name);
2237                 return ERROR_FAIL;
2238         }
2239         if (!pChip->details.bank[0].probed) {
2240                 r = sam4_auto_probe(pChip->details.bank[0].pBank);
2241                 if (r != ERROR_OK)
2242                         return r;
2243         }
2244
2245         switch (CMD_ARGC) {
2246                 default:
2247                         return ERROR_COMMAND_SYNTAX_ERROR;
2248                         break;
2249                 case 0:
2250                         goto showall;
2251                         break;
2252                 case 1:
2253                         who = -1;
2254                         break;
2255                 case 2:
2256                         if ((0 == strcmp(CMD_ARGV[0], "show")) && (0 == strcmp(CMD_ARGV[1], "all")))
2257                                 who = -1;
2258                         else {
2259                                 uint32_t v32;
2260                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], v32);
2261                                 who = v32;
2262                         }
2263                         break;
2264         }
2265
2266         if (0 == strcmp("show", CMD_ARGV[0])) {
2267                 if (who == -1) {
2268 showall:
2269                         r = ERROR_OK;
2270                         for (x = 0; x < pChip->details.n_gpnvms; x++) {
2271                                 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
2272                                 if (r != ERROR_OK)
2273                                         break;
2274                                 command_print(CMD_CTX, "sam4-gpnvm%u: %u", x, v);
2275                         }
2276                         return r;
2277                 }
2278                 if ((who >= 0) && (((unsigned)(who)) < pChip->details.n_gpnvms)) {
2279                         r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), who, &v);
2280                         command_print(CMD_CTX, "sam4-gpnvm%u: %u", who, v);
2281                         return r;
2282                 } else {
2283                         command_print(CMD_CTX, "sam4-gpnvm invalid GPNVM: %u", who);
2284                         return ERROR_COMMAND_SYNTAX_ERROR;
2285                 }
2286         }
2287
2288         if (who == -1) {
2289                 command_print(CMD_CTX, "Missing GPNVM number");
2290                 return ERROR_COMMAND_SYNTAX_ERROR;
2291         }
2292
2293         if (0 == strcmp("set", CMD_ARGV[0]))
2294                 r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
2295         else if ((0 == strcmp("clr", CMD_ARGV[0])) ||
2296                  (0 == strcmp("clear", CMD_ARGV[0])))                   /* quietly accept both */
2297                 r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
2298         else {
2299                 command_print(CMD_CTX, "Unknown command: %s", CMD_ARGV[0]);
2300                 r = ERROR_COMMAND_SYNTAX_ERROR;
2301         }
2302         return r;
2303 }
2304
2305 COMMAND_HANDLER(sam4_handle_slowclk_command)
2306 {
2307         struct sam4_chip *pChip;
2308
2309         pChip = get_current_sam4(CMD_CTX);
2310         if (!pChip)
2311                 return ERROR_OK;
2312
2313         switch (CMD_ARGC) {
2314                 case 0:
2315                         /* show */
2316                         break;
2317                 case 1:
2318                 {
2319                         /* set */
2320                         uint32_t v;
2321                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], v);
2322                         if (v > 200000) {
2323                                 /* absurd slow clock of 200Khz? */
2324                                 command_print(CMD_CTX, "Absurd/illegal slow clock freq: %d\n", (int)(v));
2325                                 return ERROR_COMMAND_SYNTAX_ERROR;
2326                         }
2327                         pChip->cfg.slow_freq = v;
2328                         break;
2329                 }
2330                 default:
2331                         /* error */
2332                         command_print(CMD_CTX, "Too many parameters");
2333                         return ERROR_COMMAND_SYNTAX_ERROR;
2334                         break;
2335         }
2336         command_print(CMD_CTX, "Slowclk freq: %d.%03dkhz",
2337                 (int)(pChip->cfg.slow_freq / 1000),
2338                 (int)(pChip->cfg.slow_freq % 1000));
2339         return ERROR_OK;
2340 }
2341
2342 static const struct command_registration at91sam4_exec_command_handlers[] = {
2343         {
2344                 .name = "gpnvm",
2345                 .handler = sam4_handle_gpnvm_command,
2346                 .mode = COMMAND_EXEC,
2347                 .usage = "[('clr'|'set'|'show') bitnum]",
2348                 .help = "Without arguments, shows all bits in the gpnvm "
2349                         "register.  Otherwise, clears, sets, or shows one "
2350                         "General Purpose Non-Volatile Memory (gpnvm) bit.",
2351         },
2352         {
2353                 .name = "info",
2354                 .handler = sam4_handle_info_command,
2355                 .mode = COMMAND_EXEC,
2356                 .help = "Print information about the current at91sam4 chip"
2357                         "and its flash configuration.",
2358         },
2359         {
2360                 .name = "slowclk",
2361                 .handler = sam4_handle_slowclk_command,
2362                 .mode = COMMAND_EXEC,
2363                 .usage = "[clock_hz]",
2364                 .help = "Display or set the slowclock frequency "
2365                         "(default 32768 Hz).",
2366         },
2367         COMMAND_REGISTRATION_DONE
2368 };
2369 static const struct command_registration at91sam4_command_handlers[] = {
2370         {
2371                 .name = "at91sam4",
2372                 .mode = COMMAND_ANY,
2373                 .help = "at91sam4 flash command group",
2374                 .usage = "",
2375                 .chain = at91sam4_exec_command_handlers,
2376         },
2377         COMMAND_REGISTRATION_DONE
2378 };
2379
2380 struct flash_driver at91sam4_flash = {
2381         .name = "at91sam4",
2382         .commands = at91sam4_command_handlers,
2383         .flash_bank_command = sam4_flash_bank_command,
2384         .erase = sam4_erase,
2385         .protect = sam4_protect,
2386         .write = sam4_write,
2387         .read = default_flash_read,
2388         .probe = sam4_probe,
2389         .auto_probe = sam4_auto_probe,
2390         .erase_check = default_flash_blank_check,
2391         .protect_check = sam4_protect_check,
2392 };