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