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