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