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