Fixes from Oleksandr Tymoshenko "gonzo@bluezbox.com"
[fw/openocd] / src / flash / at91sam3.c
1 /***************************************************************************
2  *   Copyright (C) 2009 by Duane Ellis                                     *
3  *   openocd@duaneellis.com                                                *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS for A PARTICULAR PURPOSE.  See the         *
13  *   GNU General public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19 ****************************************************************************/
20
21 /* Some of the the lower level code was based on code supplied by
22  * ATMEL under this copyright. */
23
24 /* BEGIN ATMEL COPYRIGHT */
25 /* ----------------------------------------------------------------------------
26  *         ATMEL Microcontroller Software Support
27  * ----------------------------------------------------------------------------
28  * Copyright (c) 2009, Atmel Corporation
29  *
30  * All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions are met:
34  *
35  * - Redistributions of source code must retain the above copyright notice,
36  * this list of conditions and the disclaimer below.
37  *
38  * Atmel's name may not be used to endorse or promote products derived from
39  * this software without specific prior written permission.
40  *
41  * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
42  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
43  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
44  * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
45  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
46  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
47  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
48  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
49  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
50  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ----------------------------------------------------------------------------
52  */
53 /* END ATMEL COPYRIGHT */
54
55 #ifdef HAVE_CONFIG_H
56 #include "config.h"
57 #endif
58
59
60 #include <stdio.h>
61 #include <string.h>
62 #include <stddef.h>
63 #include "log.h"
64 #include "types.h"
65 #include "flash.h"
66 #include "target.h"
67 #include "membuf.h"
68 #include "at91sam3.h"
69 #include "time_support.h"
70
71 #define REG_NAME_WIDTH  (12)
72
73
74 #define FLASH_BANK0_BASE   0x00080000
75 #define FLASH_BANK1_BASE   0x00100000
76
77 #define         AT91C_EFC_FCMD_GETD                 (0x0) // (EFC) Get Flash Descriptor
78 #define         AT91C_EFC_FCMD_WP                   (0x1) // (EFC) Write Page
79 #define         AT91C_EFC_FCMD_WPL                  (0x2) // (EFC) Write Page and Lock
80 #define         AT91C_EFC_FCMD_EWP                  (0x3) // (EFC) Erase Page and Write Page
81 #define         AT91C_EFC_FCMD_EWPL                 (0x4) // (EFC) Erase Page and Write Page then Lock
82 #define         AT91C_EFC_FCMD_EA                   (0x5) // (EFC) Erase All
83 // cmd6 is not present int he at91sam3u4/2/1 data sheet table 17-2
84 // #define      AT91C_EFC_FCMD_EPL                  (0x6) // (EFC) Erase plane?
85 // cmd7 is not present int he at91sam3u4/2/1 data sheet table 17-2
86 // #define      AT91C_EFC_FCMD_EPA                  (0x7) // (EFC) Erase pages?
87 #define         AT91C_EFC_FCMD_SLB                  (0x8) // (EFC) Set Lock Bit
88 #define         AT91C_EFC_FCMD_CLB                  (0x9) // (EFC) Clear Lock Bit
89 #define         AT91C_EFC_FCMD_GLB                  (0xA) // (EFC) Get Lock Bit
90 #define         AT91C_EFC_FCMD_SFB                  (0xB) // (EFC) Set Fuse Bit
91 #define         AT91C_EFC_FCMD_CFB                  (0xC) // (EFC) Clear Fuse Bit
92 #define         AT91C_EFC_FCMD_GFB                  (0xD) // (EFC) Get Fuse Bit
93 #define         AT91C_EFC_FCMD_STUI                 (0xE) // (EFC) Start Read Unique ID
94 #define         AT91C_EFC_FCMD_SPUI                 (0xF) // (EFC) Stop Read Unique ID
95
96 #define  offset_EFC_FMR   0
97 #define  offset_EFC_FCR   4
98 #define  offset_EFC_FSR   8
99 #define  offset_EFC_FRR   12
100
101
102 static float
103 _tomhz(uint32_t freq_hz)
104 {
105         float f;
106
107         f = ((float)(freq_hz)) / 1000000.0;
108         return f;
109 }
110
111 // How the chip is configured.
112 struct sam3_cfg {
113         uint32_t unique_id[4];
114
115         uint32_t slow_freq;
116         uint32_t rc_freq;
117         uint32_t mainosc_freq;
118         uint32_t plla_freq;
119         uint32_t mclk_freq;
120         uint32_t cpu_freq;
121         uint32_t fclk_freq;
122         uint32_t pclk0_freq;
123         uint32_t pclk1_freq;
124         uint32_t pclk2_freq;
125
126
127 #define SAM3_CHIPID_CIDR          (0x400E0740)
128         uint32_t CHIPID_CIDR;
129 #define SAM3_CHIPID_EXID          (0x400E0744)
130         uint32_t CHIPID_EXID;
131
132 #define SAM3_SUPC_CR              (0x400E1210)
133         uint32_t SUPC_CR;
134
135 #define SAM3_PMC_BASE             (0x400E0400)
136 #define SAM3_PMC_SCSR             (SAM3_PMC_BASE + 0x0008)
137         uint32_t PMC_SCSR;
138 #define SAM3_PMC_PCSR             (SAM3_PMC_BASE + 0x0018)
139         uint32_t PMC_PCSR;
140 #define SAM3_CKGR_UCKR            (SAM3_PMC_BASE + 0x001c)
141         uint32_t CKGR_UCKR;
142 #define SAM3_CKGR_MOR             (SAM3_PMC_BASE + 0x0020)
143         uint32_t CKGR_MOR;
144 #define SAM3_CKGR_MCFR            (SAM3_PMC_BASE + 0x0024)
145         uint32_t CKGR_MCFR;
146 #define SAM3_CKGR_PLLAR           (SAM3_PMC_BASE + 0x0028)
147         uint32_t CKGR_PLLAR;
148 #define SAM3_PMC_MCKR             (SAM3_PMC_BASE + 0x0030)
149         uint32_t PMC_MCKR;
150 #define SAM3_PMC_PCK0             (SAM3_PMC_BASE + 0x0040)
151         uint32_t PMC_PCK0;
152 #define SAM3_PMC_PCK1             (SAM3_PMC_BASE + 0x0044)
153         uint32_t PMC_PCK1;
154 #define SAM3_PMC_PCK2             (SAM3_PMC_BASE + 0x0048)
155         uint32_t PMC_PCK2;
156 #define SAM3_PMC_SR               (SAM3_PMC_BASE + 0x0068)
157         uint32_t PMC_SR;
158 #define SAM3_PMC_IMR              (SAM3_PMC_BASE + 0x006c)
159         uint32_t PMC_IMR;
160 #define SAM3_PMC_FSMR             (SAM3_PMC_BASE + 0x0070)
161         uint32_t PMC_FSMR;
162 #define SAM3_PMC_FSPR             (SAM3_PMC_BASE + 0x0074)
163         uint32_t PMC_FSPR;
164 };
165
166
167 struct sam3_bank_private {
168         int probed;
169         // DANGER: THERE ARE DRAGONS HERE..
170         // NOTE: If you add more 'ghost' pointers
171         // be aware that you must *manually* update
172         // these pointers in the function sam3_GetDetails()
173         // See the comment "Here there be dragons"
174
175         // so we can find the chip we belong to
176         struct sam3_chip *pChip;
177         // so we can find the orginal bank pointer
178         flash_bank_t *pBank;
179         unsigned bank_number;
180         uint32_t controller_address;
181         uint32_t base_address;
182         bool present;
183         unsigned size_bytes;
184         unsigned nsectors;
185         unsigned sector_size;
186         unsigned page_size;
187 };
188
189 struct sam3_chip_details {
190         // THERE ARE DRAGONS HERE..
191         // note: If you add pointers here
192         // becareful about them as they
193         // may need to be updated inside
194         // the function: "sam3_GetDetails()
195         // which copy/overwrites the
196         // 'runtime' copy of this structure
197         uint32_t chipid_cidr;
198         const char *name;
199
200         unsigned n_gpnvms;
201 #define SAM3_N_NVM_BITS 3
202         unsigned  gpnvm[SAM3_N_NVM_BITS];
203         unsigned  total_flash_size;
204         unsigned  total_sram_size;
205         unsigned  n_banks;
206 #define SAM3_MAX_FLASH_BANKS 2
207         // these are "initialized" from the global const data
208         struct sam3_bank_private bank[SAM3_MAX_FLASH_BANKS];
209 };
210
211
212 struct sam3_chip {
213         struct sam3_chip *next;
214         int    probed;
215
216         // this is "initialized" from the global const structure
217         struct sam3_chip_details details;
218         target_t *target;
219         struct sam3_cfg cfg;
220
221         struct membuf *mbuf;
222 };
223
224
225 struct sam3_reg_list {
226         uint32_t address;  size_t struct_offset; const char *name;
227         void (*explain_func)(struct sam3_chip *pInfo);
228 };
229
230
231 static struct sam3_chip *all_sam3_chips;
232
233 static struct sam3_chip *
234 get_current_sam3(struct command_context_s *cmd_ctx)
235 {
236         target_t *t;
237         static struct sam3_chip *p;
238
239         t = get_current_target(cmd_ctx);
240         if (!t) {
241                 command_print(cmd_ctx, "No current target?");
242                 return NULL;
243         }
244
245         p = all_sam3_chips;
246         if (!p) {
247                 // this should not happen
248                 // the command is not registered until the chip is created?
249                 command_print(cmd_ctx, "No SAM3 chips exist?");
250                 return NULL;
251         }
252
253         while (p) {
254                 if (p->target == t) {
255                         return p;
256                 }
257                 p = p->next;
258         }
259         command_print(cmd_ctx, "Cannot find SAM3 chip?");
260         return NULL;
261 }
262
263
264 // these are used to *initialize* the "pChip->details" structure.
265 static const struct sam3_chip_details all_sam3_details[] = {
266         {
267                 .chipid_cidr    = 0x28100960,
268                 .name           = "at91sam3u4e",
269                 .total_flash_size     = 256 * 1024,
270                 .total_sram_size      = 52 * 1024,
271                 .n_gpnvms       = 3,
272                 .n_banks        = 2,
273
274                 // System boots at address 0x0
275                 // gpnvm[1] = selects boot code
276                 //     if gpnvm[1] == 0
277                 //         boot is via "SAMBA" (rom)
278                 //     else
279                 //         boot is via FLASH
280                 //         Selection is via gpnvm[2]
281                 //     endif
282                 //
283                 // NOTE: banks 0 & 1 switch places
284                 //     if gpnvm[2] == 0
285                 //         Bank0 is the boot rom
286                 //      else
287                 //         Bank1 is the boot rom
288                 //      endif
289 //              .bank[0] = {
290                 {
291                   {
292                         .probed = 0,
293                         .pChip  = NULL,
294                         .pBank  = NULL,
295                         .bank_number = 0,
296                         .base_address = FLASH_BANK0_BASE,
297                         .controller_address = 0x400e0800,
298                         .present = 1,
299                         .size_bytes = 128 * 1024,
300                         .nsectors   = 16,
301                         .sector_size = 8192,
302                         .page_size   = 256,
303                   },
304
305 //              .bank[1] = {
306                   {
307                         .probed = 0,
308                         .pChip  = NULL,
309                         .pBank  = NULL,
310                         .bank_number = 1,
311                         .base_address = FLASH_BANK1_BASE,
312                         .controller_address = 0x400e0a00,
313                         .present = 1,
314                         .size_bytes = 128 * 1024,
315                         .nsectors   = 16,
316                         .sector_size = 8192,
317                         .page_size   = 256,
318                   },
319                 },
320         },
321
322         {
323                 .chipid_cidr    = 0x281a0760,
324                 .name           = "at91sam3u2e",
325                 .total_flash_size     = 128 * 1024,
326                 .total_sram_size      =  36 * 1024,
327                 .n_gpnvms       = 2,
328                 .n_banks        = 1,
329
330                 // System boots at address 0x0
331                 // gpnvm[1] = selects boot code
332                 //     if gpnvm[1] == 0
333                 //         boot is via "SAMBA" (rom)
334                 //     else
335                 //         boot is via FLASH
336                 //         Selection is via gpnvm[2]
337                 //     endif
338 //              .bank[0] = {
339                 {
340                   {
341                         .probed = 0,
342                         .pChip  = NULL,
343                         .pBank  = NULL,
344                         .bank_number = 0,
345                         .base_address = FLASH_BANK0_BASE,
346                         .controller_address = 0x400e0800,
347                         .present = 1,
348                         .size_bytes = 128 * 1024,
349                         .nsectors   = 16,
350                         .sector_size = 8192,
351                         .page_size   = 256,
352                   },
353 //                .bank[1] = {
354                   {
355                         .present = 0,
356                         .probed = 0,
357                         .bank_number = 1,
358                   },
359                 },
360         },
361         {
362                 .chipid_cidr    = 0x28190560,
363                 .name           = "at91sam3u1e",
364                 .total_flash_size     = 64 * 1024,
365                 .total_sram_size      = 20 * 1024,
366                 .n_gpnvms       = 2,
367                 .n_banks        = 1,
368
369                 // System boots at address 0x0
370                 // gpnvm[1] = selects boot code
371                 //     if gpnvm[1] == 0
372                 //         boot is via "SAMBA" (rom)
373                 //     else
374                 //         boot is via FLASH
375                 //         Selection is via gpnvm[2]
376                 //     endif
377                 //
378
379 //              .bank[0] = {
380                 {
381                   {
382                         .probed = 0,
383                         .pChip  = NULL,
384                         .pBank  = NULL,
385                         .bank_number = 0,
386                         .base_address = FLASH_BANK0_BASE,
387                         .controller_address = 0x400e0800,
388                         .present = 1,
389                         .size_bytes =  64 * 1024,
390                         .nsectors   =  8,
391                         .sector_size = 8192,
392                         .page_size   = 256,
393                   },
394
395 //              .bank[1] = {
396                   {
397                         .present = 0,
398                         .probed = 0,
399                         .bank_number = 1,
400                   },
401                 },
402         },
403
404         {
405                 .chipid_cidr    = 0x28000960,
406                 .name           = "at91sam3u4c",
407                 .total_flash_size     = 256 * 1024,
408                 .total_sram_size      = 52 * 1024,
409                 .n_gpnvms       = 3,
410                 .n_banks        = 2,
411
412                 // System boots at address 0x0
413                 // gpnvm[1] = selects boot code
414                 //     if gpnvm[1] == 0
415                 //         boot is via "SAMBA" (rom)
416                 //     else
417                 //         boot is via FLASH
418                 //         Selection is via gpnvm[2]
419                 //     endif
420                 //
421                 // NOTE: banks 0 & 1 switch places
422                 //     if gpnvm[2] == 0
423                 //         Bank0 is the boot rom
424                 //      else
425                 //         Bank1 is the boot rom
426                 //      endif
427                 {
428                   {
429 //              .bank[0] = {
430                         .probed = 0,
431                         .pChip  = NULL,
432                         .pBank  = NULL,
433                         .bank_number = 0,
434                         .base_address = FLASH_BANK0_BASE,
435                         .controller_address = 0x400e0800,
436                         .present = 1,
437                         .size_bytes = 128 * 1024,
438                         .nsectors   = 16,
439                         .sector_size = 8192,
440                         .page_size   = 256,
441                   },
442 //              .bank[1] = {
443                   {
444                         .probed = 0,
445                         .pChip  = NULL,
446                         .pBank  = NULL,
447                         .bank_number = 1,
448                         .base_address = FLASH_BANK1_BASE,
449                         .controller_address = 0x400e0a00,
450                         .present = 1,
451                         .size_bytes = 128 * 1024,
452                         .nsectors   = 16,
453                         .sector_size = 8192,
454                         .page_size   = 256,
455                   },
456                 },
457         },
458
459         {
460                 .chipid_cidr    = 0x280a0760,
461                 .name           = "at91sam3u2c",
462                 .total_flash_size     = 128 * 1024,
463                 .total_sram_size      = 36 * 1024,
464                 .n_gpnvms       = 2,
465                 .n_banks        = 1,
466
467                 // System boots at address 0x0
468                 // gpnvm[1] = selects boot code
469                 //     if gpnvm[1] == 0
470                 //         boot is via "SAMBA" (rom)
471                 //     else
472                 //         boot is via FLASH
473                 //         Selection is via gpnvm[2]
474                 //     endif
475                 {
476 //              .bank[0] = {
477                   {
478                         .probed = 0,
479                         .pChip  = NULL,
480                         .pBank  = NULL,
481                         .bank_number = 0,
482                         .base_address = FLASH_BANK0_BASE,
483                         .controller_address = 0x400e0800,
484                         .present = 1,
485                         .size_bytes = 128 * 1024,
486                         .nsectors   = 16,
487                         .sector_size = 8192,
488                         .page_size   = 256,
489                   },
490 //              .bank[1] = {
491                   {
492                         .present = 0,
493                         .probed = 0,
494                         .bank_number = 1,
495                   },
496                 },
497         },
498         {
499                 .chipid_cidr    = 0x28090560,
500                 .name           = "at91sam3u1c",
501                 .total_flash_size     = 64 * 1024,
502                 .total_sram_size      = 20 * 1024,
503                 .n_gpnvms       = 2,
504                 .n_banks        = 1,
505
506                 // System boots at address 0x0
507                 // gpnvm[1] = selects boot code
508                 //     if gpnvm[1] == 0
509                 //         boot is via "SAMBA" (rom)
510                 //     else
511                 //         boot is via FLASH
512                 //         Selection is via gpnvm[2]
513                 //     endif
514                 //
515
516                 {
517 //              .bank[0] = {
518                   {
519                         .probed = 0,
520                         .pChip  = NULL,
521                         .pBank  = NULL,
522                         .bank_number = 0,
523                         .base_address = FLASH_BANK0_BASE,
524                         .controller_address = 0x400e0800,
525                         .present = 1,
526                         .size_bytes =  64 * 1024,
527                         .nsectors   =  8,
528                         .sector_size = 8192,
529                         .page_size   = 256,
530                   },
531 //              .bank[1] = {
532                   {
533                         .present = 0,
534                         .probed = 0,
535                         .bank_number = 1,
536
537                   },
538                 },
539         },
540
541         // terminate
542         {
543                 .chipid_cidr    = 0,
544                 .name                   = NULL,
545         }
546 };
547
548 /* Globals above */
549 /***********************************************************************
550  **********************************************************************
551  **********************************************************************
552  **********************************************************************
553  **********************************************************************
554  **********************************************************************/
555 /* *ATMEL* style code - from the SAM3 driver code */
556
557 /** Get the current status of the EEFC
558  *
559  * the value of some status bits (LOCKE, PROGE).
560  * @param pPrivate - info about the bank
561  * @param v        - result goes here
562  */
563 static int
564 EFC_GetStatus(struct sam3_bank_private *pPrivate, uint32_t *v)
565 {
566         int r;
567         r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address + offset_EFC_FSR, v);
568         LOG_DEBUG("Status: 0x%08x (lockerror: %d, cmderror: %d, ready: %d)",
569                           (unsigned int)(*v),
570                           ((unsigned int)((*v >> 2) & 1)),
571                           ((unsigned int)((*v >> 1) & 1)),
572                           ((unsigned int)((*v >> 0) & 1)));
573
574         return r;
575 }
576
577 /** Get the result of the last executed command.
578  * @param pPrivate - info about the bank
579  * @param v        - result goes here
580  */
581 static int
582 EFC_GetResult(struct sam3_bank_private *pPrivate, uint32_t *v)
583 {
584         int r;
585         uint32_t rv;
586         r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address + offset_EFC_FRR, &rv);
587         if (v) {
588                 *v = rv;
589         }
590         LOG_DEBUG("Result: 0x%08x", ((unsigned int)(rv)));
591         return r;
592 }
593
594 static int
595 EFC_StartCommand(struct sam3_bank_private *pPrivate,
596                                  unsigned command, unsigned argument)
597 {
598         uint32_t n,v;
599         int r;
600         int retry;
601
602         retry = 0;
603  do_retry:
604
605     // Check command & argument
606     switch (command) {
607
608         case AT91C_EFC_FCMD_WP:
609         case AT91C_EFC_FCMD_WPL:
610         case AT91C_EFC_FCMD_EWP:
611         case AT91C_EFC_FCMD_EWPL:
612                 // case AT91C_EFC_FCMD_EPL:
613                 // case AT91C_EFC_FCMD_EPA:
614         case AT91C_EFC_FCMD_SLB:
615         case AT91C_EFC_FCMD_CLB:
616                 n = (pPrivate->size_bytes / pPrivate->page_size);
617                 if (argument >= n) {
618                         LOG_ERROR("*BUG*: Embedded flash has only %u pages", (unsigned)(n));
619                 }
620                 break;
621
622         case AT91C_EFC_FCMD_SFB:
623         case AT91C_EFC_FCMD_CFB:
624                 if (argument >= pPrivate->pChip->details.n_gpnvms) {
625                         LOG_ERROR("*BUG*: Embedded flash has only %d GPNVMs",
626                                           pPrivate->pChip->details.n_gpnvms);
627                 }
628                 break;
629
630         case AT91C_EFC_FCMD_GETD:
631         case AT91C_EFC_FCMD_EA:
632         case AT91C_EFC_FCMD_GLB:
633         case AT91C_EFC_FCMD_GFB:
634         case AT91C_EFC_FCMD_STUI:
635         case AT91C_EFC_FCMD_SPUI:
636                 if (argument != 0) {
637                         LOG_ERROR("Argument is meaningless for cmd: %d", command);
638                 }
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", pPrivate->bank_number);
661                                 return ERROR_FAIL;
662                         } else {
663                                 retry++;
664                                 LOG_ERROR("Flash controller(%d) is not ready, attempting reset",
665                                                   pPrivate->bank_number);
666                                 // we do that by issuing the *STOP* command
667                                 EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0);
668                                 // above is recursive, and further recursion is blocked by
669                                 // if (command == AT91C_EFC_FCMD_SPUI) above
670                                 goto do_retry;
671                         }
672                 }
673         }
674
675         v = (0x5A << 24) | (argument << 8) | command;
676         LOG_DEBUG("Command: 0x%08x", ((unsigned int)(v)));
677         r = target_write_u32(pPrivate->pBank->target,
678                                                   pPrivate->controller_address + offset_EFC_FCR,
679                                                   v);
680         if (r != ERROR_OK) {
681                 LOG_DEBUG("Error Write failed");
682         }
683         return r;
684 }
685
686 /** Performs the given command and wait until its completion (or an error).
687  *
688  * @param pPrivate - info about the bank
689  * @param command  - Command to perform.
690  * @param argument - Optional command argument.
691  * @param status   - put command status bits here
692  */
693 static int
694 EFC_PerformCommand(struct sam3_bank_private *pPrivate,
695                                         unsigned command,
696                                         unsigned argument,
697                                         uint32_t *status)
698 {
699
700         int r;
701         uint32_t v;
702         long long ms_now, ms_end;
703
704         // default
705         if (status) {
706                 *status = 0;
707         }
708
709         r = EFC_StartCommand(pPrivate, command, argument);
710         if (r != ERROR_OK) {
711                 return r;
712         }
713
714         ms_end = 500 + timeval_ms();
715
716
717     do {
718                 r = EFC_GetStatus(pPrivate, &v);
719                 if (r != ERROR_OK) {
720                         return r;
721                 }
722                 ms_now = timeval_ms();
723                 if (ms_now > ms_end) {
724                         // error
725                         LOG_ERROR("Command timeout");
726                         return ERROR_FAIL;
727                 }
728     }
729     while ((v & 1) == 0)
730                 ;
731
732         // error bits..
733         if (status) {
734                 *status = (v & 0x6);
735         }
736         return ERROR_OK;
737
738 }
739
740
741
742
743
744 /** Read the unique ID.
745  *
746  * \param pPrivate - info about the bank
747  *
748  * The unique ID is stored in the 'pPrivate' structure.
749  */
750
751 static int
752 FLASHD_ReadUniqueID (struct sam3_bank_private *pPrivate)
753 {
754         int r;
755         uint32_t v;
756         int x;
757         // assume 0
758     pPrivate->pChip->cfg.unique_id[0] = 0;
759     pPrivate->pChip->cfg.unique_id[1] = 0;
760     pPrivate->pChip->cfg.unique_id[2] = 0;
761     pPrivate->pChip->cfg.unique_id[3] = 0;
762
763         LOG_DEBUG("Begin");
764         r = EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_STUI, 0);
765         if (r < 0) {
766                 return r;
767         }
768
769         for (x = 0 ; x < 4 ; x++) {
770                 r = target_read_u32(pPrivate->pChip->target,
771                                                          pPrivate->pBank->base + (x * 4),
772                                                          &v);
773                 if (r < 0) {
774                         return r;
775                 }
776                 pPrivate->pChip->cfg.unique_id[x] = v;
777         }
778
779     r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0, NULL);
780         LOG_DEBUG("End: R=%d, id = 0x%08x, 0x%08x, 0x%08x, 0x%08x",
781                           r,
782                           (unsigned int)(pPrivate->pChip->cfg.unique_id[0]),
783                           (unsigned int)(pPrivate->pChip->cfg.unique_id[1]),
784                           (unsigned int)(pPrivate->pChip->cfg.unique_id[2]),
785                           (unsigned int)(pPrivate->pChip->cfg.unique_id[3]));
786         return r;
787
788 }
789
790 /** Erases the entire flash.
791  * @param pPrivate - the info about the bank.
792  */
793 static int
794 FLASHD_EraseEntireBank(struct sam3_bank_private *pPrivate)
795 {
796         LOG_DEBUG("Here");
797         return EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_EA, 0, NULL);
798 }
799
800
801
802 /** Gets current GPNVM state.
803  * @param pPrivate - info about the bank.
804  * @param gpnvm    -  GPNVM bit index.
805  * @param puthere  - result stored here.
806  *
807  */
808 //------------------------------------------------------------------------------
809 static int
810 FLASHD_GetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm, unsigned *puthere)
811 {
812         uint32_t v;
813         int r;
814
815         LOG_DEBUG("Here");
816         if (pPrivate->bank_number != 0) {
817                 LOG_ERROR("GPNVM only works with Bank0");
818                 return ERROR_FAIL;
819         }
820
821         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
822                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
823                                   gpnvm,pPrivate->pChip->details.n_gpnvms);
824                 return ERROR_FAIL;
825         }
826
827     // Get GPNVMs status
828         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GFB, 0, NULL);
829         if (r != ERROR_OK) {
830                 LOG_ERROR("Failed");
831                 return r;
832         }
833
834     r = EFC_GetResult(pPrivate, &v);
835
836         if (puthere) {
837                 // Check if GPNVM is set
838                 // get the bit and make it a 0/1
839                 *puthere = (v >> gpnvm) & 1;
840         }
841
842         return r;
843 }
844
845
846
847
848 /** Clears the selected GPNVM bit.
849  * @param gpnvm  GPNVM index.
850  *
851  * Returns 0 if successful; otherwise returns an error code.
852  */
853 static int
854 FLASHD_ClrGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm)
855 {
856         int r;
857         unsigned v;
858
859         LOG_DEBUG("Here");
860         if (pPrivate->bank_number != 0) {
861                 LOG_ERROR("GPNVM only works with Bank0");
862                 return ERROR_FAIL;
863         }
864
865         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
866                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
867                                   gpnvm,pPrivate->pChip->details.n_gpnvms);
868                 return ERROR_FAIL;
869         }
870
871         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
872         if (r != ERROR_OK) {
873                 LOG_DEBUG("Failed: %d",r);
874                 return r;
875         }
876         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CFB, gpnvm, NULL);
877         LOG_DEBUG("End: %d",r);
878         return r;
879 }
880
881
882
883 /** Sets the selected GPNVM bit.
884  *  @param gpnvm  GPNVM index.
885  *
886  */
887 static int
888 FLASHD_SetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm)
889 {
890         int r;
891         unsigned v;
892
893         if (pPrivate->bank_number != 0) {
894                 LOG_ERROR("GPNVM only works with Bank0");
895                 return ERROR_FAIL;
896         }
897
898         if (gpnvm >= pPrivate->pChip->details.n_gpnvms) {
899                 LOG_ERROR("Invalid GPNVM %d, max: %d, ignored",
900                                   gpnvm,pPrivate->pChip->details.n_gpnvms);
901                 return ERROR_FAIL;
902         }
903
904         r = FLASHD_GetGPNVM(pPrivate, gpnvm, &v);
905         if (r != ERROR_OK) {
906                 return r;
907         }
908         if (v) {
909                 // already set
910                 r = ERROR_OK;
911         } else {
912                 // set it
913                 r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SFB, gpnvm, NULL);
914         }
915         return r;
916 }
917
918
919 /** Returns a bit field (at most 64) of locked regions within a page.
920  * @param pPrivate - info about the bank
921  * @param v        - where to store locked bits
922  * \param end  End address of range.
923  */
924
925 static int
926 FLASHD_GetLockBits(struct sam3_bank_private *pPrivate, uint32_t *v)
927 {
928         int r;
929         LOG_DEBUG("Here");
930     r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_GLB, 0, NULL);
931         if (r == ERROR_OK) {
932                 r = EFC_GetResult(pPrivate, v);
933         }
934         LOG_DEBUG("End: %d",r);
935         return r;
936 }
937
938
939 /**Unlocks all the regions in the given address range.
940  *
941  * \param start_sector - first sector to unlock
942  * \param end_sector   - last (inclusive) to unlock
943  */
944
945 static int
946 FLASHD_Unlock(struct sam3_bank_private *pPrivate,
947                            unsigned start_sector,
948                            unsigned end_sector)
949 {
950         int r;
951         uint32_t status;
952         uint32_t pg;
953         uint32_t pages_per_sector;
954
955         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
956
957     /* Unlock all pages */
958     while (start_sector <= end_sector) {
959                 pg = start_sector * pages_per_sector;
960
961         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_CLB, pg, &status);
962         if (r != ERROR_OK) {
963             return r;
964         }
965         start_sector++;
966     }
967
968     return ERROR_OK;
969 }
970
971
972 /** Locks regions
973  *
974  * @param start_sector - first sector to lock
975  * @param end_sector   - last sector (inclusive) to lock
976  */
977
978
979 static int
980 FLASHD_Lock(struct sam3_bank_private *pPrivate,
981                          unsigned start_sector,
982                          unsigned end_sector)
983 {
984         uint32_t status;
985         uint32_t pg;
986         uint32_t pages_per_sector;
987         int r;
988
989         pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
990
991     /* Lock all pages */
992     while (start_sector <= end_sector) {
993                 pg = start_sector * pages_per_sector;
994
995         r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SLB, pg, &status);
996         if (r != ERROR_OK) {
997             return r;
998         }
999         start_sector++;
1000     }
1001     return ERROR_OK;
1002 }
1003
1004
1005 /****** END SAM3 CODE ********/
1006
1007 /* begin helpful debug code */
1008
1009 static void
1010 sam3_sprintf(struct sam3_chip *pChip , const char *fmt, ...)
1011 {
1012         va_list ap;
1013         va_start(ap,fmt);
1014         if (pChip->mbuf == NULL) {
1015                 return;
1016         }
1017
1018         membuf_vsprintf(pChip->mbuf, fmt, ap);
1019         va_end(ap);
1020 }
1021
1022 // print the fieldname, the field value, in dec & hex, and return field value
1023 static uint32_t
1024 sam3_reg_fieldname(struct sam3_chip *pChip,
1025                                         const char *regname,
1026                                         uint32_t value,
1027                                         unsigned shift,
1028                                         unsigned width)
1029 {
1030         uint32_t v;
1031         int hwidth, dwidth;
1032
1033
1034         // extract the field
1035         v = value >> shift;
1036         v = v & ((1 << width)-1);
1037         if (width <= 16) {
1038                 hwidth = 4;
1039                 dwidth = 5;
1040         } else {
1041                 hwidth = 8;
1042                 dwidth = 12;
1043         }
1044
1045         // show the basics
1046         sam3_sprintf(pChip, "\t%*s: %*d [0x%0*x] ",
1047                                   REG_NAME_WIDTH, regname,
1048                                   dwidth, v,
1049                                   hwidth, v);
1050         return v;
1051 }
1052
1053
1054 static const char _unknown[] = "unknown";
1055 static const char * const eproc_names[] = {
1056         _unknown,                                       // 0
1057         "arm946es",                                     // 1
1058         "arm7tdmi",                                     // 2
1059         "cortex-m3",                            // 3
1060         "arm920t",                                      // 4
1061         "arm926ejs",                            // 5
1062         _unknown,                                       // 6
1063         _unknown,                                       // 7
1064         _unknown,                                       // 8
1065         _unknown,                                       // 9
1066         _unknown,                                       // 10
1067         _unknown,                                       // 11
1068         _unknown,                                       // 12
1069         _unknown,                                       // 13
1070         _unknown,                                       // 14
1071         _unknown,                                       // 15
1072 };
1073
1074 #define nvpsize2 nvpsize                // these two tables are identical
1075 static const char * const nvpsize[] = {
1076         "none",                                         //  0
1077         "8K bytes",                                     //  1
1078         "16K bytes",                            //  2
1079         "32K bytes",                            //  3
1080         _unknown,                                       //  4
1081         "64K bytes",                            //  5
1082         _unknown,                                       //  6
1083         "128K bytes",                           //  7
1084         _unknown,                                       //  8
1085         "256K bytes",                           //  9
1086         "512K bytes",                           // 10
1087         _unknown,                                       // 11
1088         "1024K bytes",                          // 12
1089         _unknown,                                       // 13
1090         "2048K bytes",                          // 14
1091         _unknown,                                       // 15
1092 };
1093
1094
1095 static const char * const sramsize[] = {
1096         "48K Bytes",                            //  0
1097         "1K Bytes",                                     //  1
1098         "2K Bytes",                                     //  2
1099         "6K Bytes",                                     //  3
1100         "112K Bytes",                           //  4
1101         "4K Bytes",                                     //  5
1102         "80K Bytes",                            //  6
1103         "160K Bytes",                           //  7
1104         "8K Bytes",                                     //  8
1105         "16K Bytes",                            //  9
1106         "32K Bytes",                            // 10
1107         "64K Bytes",                            // 11
1108         "128K Bytes",                           // 12
1109         "256K Bytes",                           // 13
1110         "96K Bytes",                            // 14
1111         "512K Bytes",                           // 15
1112
1113 };
1114
1115 static const struct archnames { unsigned value; const char *name; } archnames[] = {
1116         { 0x19,  "AT91SAM9xx Series"                                            },
1117         { 0x29,  "AT91SAM9XExx Series"                                          },
1118         { 0x34,  "AT91x34 Series"                                                       },
1119         { 0x37,  "CAP7 Series"                                                          },
1120         { 0x39,  "CAP9 Series"                                                          },
1121         { 0x3B,  "CAP11 Series"                                                         },
1122         { 0x40,  "AT91x40 Series"                                                       },
1123         { 0x42,  "AT91x42 Series"                                                       },
1124         { 0x55,  "AT91x55 Series"                                                       },
1125         { 0x60,  "AT91SAM7Axx Series"                                           },
1126         { 0x61,  "AT91SAM7AQxx Series"                                          },
1127         { 0x63,  "AT91x63 Series"                                                       },
1128         { 0x70,  "AT91SAM7Sxx Series"                                           },
1129         { 0x71,  "AT91SAM7XCxx Series"                                          },
1130         { 0x72,  "AT91SAM7SExx Series"                                          },
1131         { 0x73,  "AT91SAM7Lxx Series"                                           },
1132         { 0x75,  "AT91SAM7Xxx Series"                                           },
1133         { 0x76,  "AT91SAM7SLxx Series"                                          },
1134         { 0x80,  "ATSAM3UxC Series (100-pin version)"           },
1135         { 0x81,  "ATSAM3UxE Series (144-pin version)"           },
1136         { 0x83,  "ATSAM3AxC Series (100-pin version)"           },
1137         { 0x84,  "ATSAM3XxC Series (100-pin version)"           },
1138         { 0x85,  "ATSAM3XxE Series (144-pin version)"           },
1139         { 0x86,  "ATSAM3XxG Series (208/217-pin version)"       },
1140         { 0x88,  "ATSAM3SxA Series (48-pin version)"            },
1141         { 0x89,  "ATSAM3SxB Series (64-pin version)"            },
1142         { 0x8A,  "ATSAM3SxC Series (100-pin version)"           },
1143         { 0x92,  "AT91x92 Series"                                                       },
1144         { 0xF0,  "AT75Cxx Series"                                                       },
1145         { -1, NULL },
1146
1147 };
1148
1149 static const char * const nvptype[] = {
1150         "rom", // 0
1151         "romless or onchip flash", // 1
1152         "embedded flash memory", // 2
1153         "rom(nvpsiz) + embedded flash (nvpsiz2)", //3
1154         "sram emulating flash", // 4
1155         _unknown, // 5
1156         _unknown, // 6
1157         _unknown, // 7
1158
1159 };
1160
1161 static const char *_yes_or_no(uint32_t v)
1162 {
1163         if (v) {
1164                 return "YES";
1165         } else {
1166                 return "NO";
1167         }
1168 }
1169
1170 static const char * const _rc_freq[] = {
1171         "4 MHz", "8 MHz", "12 MHz", "reserved"
1172 };
1173
1174 static void
1175 sam3_explain_ckgr_mor(struct sam3_chip *pChip)
1176 {
1177         uint32_t v;
1178         uint32_t rcen;
1179
1180         v = sam3_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
1181         sam3_sprintf(pChip, "(main xtal enabled: %s)\n",
1182                                   _yes_or_no(v));
1183         v = sam3_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
1184         sam3_sprintf(pChip, "(main osc bypass: %s)\n",
1185                                   _yes_or_no(v));
1186         rcen = sam3_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 2, 1);
1187         sam3_sprintf(pChip, "(onchip RC-OSC enabled: %s)\n",
1188                                   _yes_or_no(rcen));
1189         v = sam3_reg_fieldname(pChip, "MOSCRCF", pChip->cfg.CKGR_MOR, 4, 3);
1190         sam3_sprintf(pChip, "(onchip RC-OSC freq: %s)\n",
1191                                   _rc_freq[v]);
1192
1193         pChip->cfg.rc_freq = 0;
1194         if (rcen) {
1195                 switch (v) {
1196                 default:
1197                         pChip->cfg.rc_freq = 0;
1198                 case 0:
1199                         pChip->cfg.rc_freq = 4 * 1000 * 1000;
1200                         break;
1201                 case 1:
1202                         pChip->cfg.rc_freq = 8 * 1000 * 1000;
1203                         break;
1204                 case 2:
1205                         pChip->cfg.rc_freq = 12* 1000 * 1000;
1206                         break;
1207                 }
1208         }
1209
1210         v = sam3_reg_fieldname(pChip,"MOSCXTST", pChip->cfg.CKGR_MOR, 8, 8);
1211         sam3_sprintf(pChip, "(startup clks, time= %f uSecs)\n",
1212                                   ((float)(v * 1000000)) / ((float)(pChip->cfg.slow_freq)));
1213         v = sam3_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
1214         sam3_sprintf(pChip, "(mainosc source: %s)\n",
1215                                   v ? "external xtal" : "internal RC");
1216
1217         v = sam3_reg_fieldname(pChip,"CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
1218         sam3_sprintf(pChip, "(clock failure enabled: %s)\n",
1219                                  _yes_or_no(v));
1220 }
1221
1222
1223
1224 static void
1225 sam3_explain_chipid_cidr(struct sam3_chip *pChip)
1226 {
1227         int x;
1228         uint32_t v;
1229         const char *cp;
1230
1231         sam3_reg_fieldname(pChip, "Version", pChip->cfg.CHIPID_CIDR, 0, 5);
1232         sam3_sprintf(pChip,"\n");
1233
1234         v = sam3_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
1235         sam3_sprintf(pChip, "%s\n", eproc_names[v]);
1236
1237         v = sam3_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
1238         sam3_sprintf(pChip, "%s\n", nvpsize[v]);
1239
1240         v = sam3_reg_fieldname(pChip, "NVPSIZE2", pChip->cfg.CHIPID_CIDR, 12, 4);
1241         sam3_sprintf(pChip, "%s\n", nvpsize2[v]);
1242
1243         v = sam3_reg_fieldname(pChip, "SRAMSIZE", pChip->cfg.CHIPID_CIDR, 16,4);
1244         sam3_sprintf(pChip, "%s\n", sramsize[ v ]);
1245
1246         v = sam3_reg_fieldname(pChip, "ARCH", pChip->cfg.CHIPID_CIDR, 20, 8);
1247         cp = _unknown;
1248         for (x = 0 ; archnames[x].name ; x++) {
1249                 if (v == archnames[x].value) {
1250                         cp = archnames[x].name;
1251                         break;
1252                 }
1253         }
1254
1255         sam3_sprintf(pChip, "%s\n", cp);
1256
1257         v = sam3_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
1258         sam3_sprintf(pChip, "%s\n", nvptype[ v ]);
1259
1260         v = sam3_reg_fieldname(pChip, "EXTID", pChip->cfg.CHIPID_CIDR, 31, 1);
1261         sam3_sprintf(pChip, "(exists: %s)\n", _yes_or_no(v));
1262 }
1263
1264 static void
1265 sam3_explain_ckgr_mcfr(struct sam3_chip *pChip)
1266 {
1267         uint32_t v;
1268
1269
1270         v = sam3_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
1271         sam3_sprintf(pChip, "(main ready: %s)\n", _yes_or_no(v));
1272
1273         v = sam3_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
1274
1275         v = (v * pChip->cfg.slow_freq) / 16;
1276         pChip->cfg.mainosc_freq = v;
1277
1278         sam3_sprintf(pChip, "(%3.03f Mhz (%d.%03dkhz slowclk)\n",
1279                                  _tomhz(v),
1280                                  pChip->cfg.slow_freq / 1000,
1281                                  pChip->cfg.slow_freq % 1000);
1282
1283 }
1284
1285 static void
1286 sam3_explain_ckgr_plla(struct sam3_chip *pChip)
1287 {
1288         uint32_t mula,diva;
1289
1290         diva = sam3_reg_fieldname(pChip, "DIVA", pChip->cfg.CKGR_PLLAR, 0, 8);
1291         sam3_sprintf(pChip,"\n");
1292         mula = sam3_reg_fieldname(pChip, "MULA", pChip->cfg.CKGR_PLLAR, 16, 11);
1293         sam3_sprintf(pChip,"\n");
1294         pChip->cfg.plla_freq = 0;
1295         if (mula == 0) {
1296                 sam3_sprintf(pChip,"\tPLLA Freq: (Disabled,mula = 0)\n");
1297         } else if (diva == 0) {
1298                 sam3_sprintf(pChip,"\tPLLA Freq: (Disabled,diva = 0)\n");
1299         } else if (diva == 1) {
1300                 pChip->cfg.plla_freq = (pChip->cfg.mainosc_freq * (mula + 1));
1301                 sam3_sprintf(pChip,"\tPLLA Freq: %3.03f MHz\n",
1302                                          _tomhz(pChip->cfg.plla_freq));
1303         }
1304 }
1305
1306
1307 static void
1308 sam3_explain_mckr(struct sam3_chip *pChip)
1309 {
1310         uint32_t css, pres,fin;
1311         int pdiv;
1312         const char *cp;
1313
1314         css = sam3_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
1315         switch (css & 3) {
1316         case 0:
1317                 fin = pChip->cfg.slow_freq;
1318                 cp = "slowclk";
1319                 break;
1320         case 1:
1321                 fin = pChip->cfg.mainosc_freq;
1322                 cp  = "mainosc";
1323                 break;
1324         case 2:
1325                 fin = pChip->cfg.plla_freq;
1326                 cp  = "plla";
1327                 break;
1328         case 3:
1329                 if (pChip->cfg.CKGR_UCKR & (1 << 16)) {
1330                         fin = 480 * 1000 * 1000;
1331                         cp = "upll";
1332                 } else {
1333                         fin = 0;
1334                         cp  = "upll (*ERROR* UPLL is disabled)";
1335                 }
1336                 break;
1337         default:
1338                 assert(0);
1339                 break;
1340         }
1341
1342         sam3_sprintf(pChip, "%s (%3.03f Mhz)\n",
1343                                   cp,
1344                                   _tomhz(fin));
1345         pres = sam3_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
1346         switch (pres & 0x07) {
1347         case 0:
1348                 pdiv = 1;
1349                 cp = "selected clock";
1350         case 1:
1351                 pdiv = 2;
1352                 cp = "clock/2";
1353                 break;
1354         case 2:
1355                 pdiv = 4;
1356                 cp = "clock/4";
1357                 break;
1358         case 3:
1359                 pdiv = 8;
1360                 cp = "clock/8";
1361                 break;
1362         case 4:
1363                 pdiv = 16;
1364                 cp = "clock/16";
1365                 break;
1366         case 5:
1367                 pdiv = 32;
1368                 cp = "clock/32";
1369                 break;
1370         case 6:
1371                 pdiv = 64;
1372                 cp = "clock/64";
1373                 break;
1374         case 7:
1375                 pdiv = 6;
1376                 cp = "clock/6";
1377                 break;
1378         default:
1379                 assert(0);
1380                 break;
1381         }
1382         sam3_sprintf(pChip, "(%s)\n", cp);
1383         fin = fin / pdiv;
1384         // sam3 has a *SINGLE* clock -
1385         // other at91 series parts have divisors for these.
1386         pChip->cfg.cpu_freq = fin;
1387         pChip->cfg.mclk_freq = fin;
1388         pChip->cfg.fclk_freq = fin;
1389         sam3_sprintf(pChip, "\t\tResult CPU Freq: %3.03f\n",
1390                                   _tomhz(fin));
1391 }
1392
1393 #if 0
1394 static struct sam3_chip *
1395 target2sam3(target_t *pTarget)
1396 {
1397         struct sam3_chip *pChip;
1398
1399         if (pTarget == NULL) {
1400                 return NULL;
1401         }
1402
1403         pChip = all_sam3_chips;
1404         while (pChip) {
1405                 if (pChip->target == pTarget) {
1406                         break; // return below
1407                 } else {
1408                         pChip = pChip->next;
1409                 }
1410         }
1411         return pChip;
1412 }
1413 #endif
1414
1415 static uint32_t *
1416 sam3_get_reg_ptr(struct sam3_cfg *pCfg, const struct sam3_reg_list *pList)
1417 {
1418         // this function exists to help
1419         // keep funky offsetof() errors
1420         // and casting from causing bugs
1421
1422         // By using prototypes - we can detect what would
1423         // be casting errors.
1424
1425         return ((uint32_t *)(((char *)(pCfg)) + pList->struct_offset));
1426 }
1427
1428
1429 #define SAM3_ENTRY(NAME, FUNC)  { .address = SAM3_ ## NAME, .struct_offset = offsetof(struct sam3_cfg, NAME), #NAME, FUNC }
1430 static const struct sam3_reg_list sam3_all_regs[] = {
1431         SAM3_ENTRY(CKGR_MOR , sam3_explain_ckgr_mor),
1432         SAM3_ENTRY(CKGR_MCFR , sam3_explain_ckgr_mcfr),
1433         SAM3_ENTRY(CKGR_PLLAR , sam3_explain_ckgr_plla),
1434         SAM3_ENTRY(CKGR_UCKR , NULL),
1435         SAM3_ENTRY(PMC_FSMR , NULL),
1436         SAM3_ENTRY(PMC_FSPR , NULL),
1437         SAM3_ENTRY(PMC_IMR , NULL),
1438         SAM3_ENTRY(PMC_MCKR , sam3_explain_mckr),
1439         SAM3_ENTRY(PMC_PCK0 , NULL),
1440         SAM3_ENTRY(PMC_PCK1 , NULL),
1441         SAM3_ENTRY(PMC_PCK2 , NULL),
1442         SAM3_ENTRY(PMC_PCSR , NULL),
1443         SAM3_ENTRY(PMC_SCSR , NULL),
1444         SAM3_ENTRY(PMC_SR , NULL),
1445         SAM3_ENTRY(CHIPID_CIDR , sam3_explain_chipid_cidr),
1446         SAM3_ENTRY(CHIPID_EXID , NULL),
1447         SAM3_ENTRY(SUPC_CR, NULL),
1448
1449         // TERMINATE THE LIST
1450         { .name = NULL }
1451 };
1452 #undef SAM3_ENTRY
1453
1454
1455
1456
1457 static struct sam3_bank_private *
1458 get_sam3_bank_private(flash_bank_t *bank)
1459 {
1460         return (struct sam3_bank_private *)(bank->driver_priv);
1461 }
1462
1463 /*
1464  * Given a pointer to where it goes in the structure..
1465  *    Determine the register name, address from the all registers table.
1466  */
1467 static const struct sam3_reg_list *
1468 sam3_GetReg(struct sam3_chip *pChip, uint32_t *goes_here)
1469 {
1470         const struct sam3_reg_list *pReg;
1471
1472         pReg = &(sam3_all_regs[0]);
1473         while (pReg->name) {
1474                 uint32_t *pPossible;
1475
1476                 // calculate where this one go..
1477                 // it is "possibly" this register.
1478
1479                 pPossible = ((uint32_t *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
1480
1481                 // well? Is it this register
1482                 if (pPossible == goes_here) {
1483                         // Jump for joy!
1484                         return pReg;
1485                 }
1486
1487                 // next...
1488                 pReg++;
1489         }
1490         // This is *TOTAL*PANIC* - we are totally screwed.
1491         LOG_ERROR("INVALID SAM3 REGISTER");
1492         return NULL;
1493 }
1494
1495
1496 static int
1497 sam3_ReadThisReg(struct sam3_chip *pChip, uint32_t *goes_here)
1498 {
1499         const struct sam3_reg_list *pReg;
1500         int r;
1501
1502         pReg = sam3_GetReg(pChip, goes_here);
1503         if (!pReg) {
1504                 return ERROR_FAIL;
1505         }
1506
1507         r = target_read_u32(pChip->target, pReg->address, goes_here);
1508         if (r != ERROR_OK) {
1509                 LOG_ERROR("Cannot read SAM3 register: %s @ 0x%08x, Err: %d\n",
1510                                   pReg->name, (unsigned)(pReg->address), r);
1511         }
1512         return r;
1513 }
1514
1515
1516
1517 static int
1518 sam3_ReadAllRegs(struct sam3_chip *pChip)
1519 {
1520         int r;
1521         const struct sam3_reg_list *pReg;
1522
1523         pReg = &(sam3_all_regs[0]);
1524         while (pReg->name) {
1525                 r = sam3_ReadThisReg(pChip,
1526                                                                   sam3_get_reg_ptr(&(pChip->cfg), pReg));
1527                 if (r != ERROR_OK) {
1528                         LOG_ERROR("Cannot read SAM3 registere: %s @ 0x%08x, Error: %d\n",
1529                                           pReg->name, ((unsigned)(pReg->address)), r);
1530                         return r;
1531                 }
1532
1533                 pReg++;
1534         }
1535
1536         return ERROR_OK;
1537 }
1538
1539
1540 static int
1541 sam3_GetInfo(struct sam3_chip *pChip)
1542 {
1543         const struct sam3_reg_list *pReg;
1544         uint32_t regval;
1545
1546         membuf_reset(pChip->mbuf);
1547
1548
1549         pReg = &(sam3_all_regs[0]);
1550         while (pReg->name) {
1551                 // display all regs
1552                 LOG_DEBUG("Start: %s", pReg->name);
1553                 regval = *sam3_get_reg_ptr(&(pChip->cfg), pReg);
1554                 sam3_sprintf(pChip, "%*s: [0x%08x] -> 0x%08x\n",
1555                                          REG_NAME_WIDTH,
1556                                          pReg->name,
1557                                          pReg->address,
1558                                          regval);
1559                 if (pReg->explain_func) {
1560                         (*(pReg->explain_func))(pChip);
1561                 }
1562                 LOG_DEBUG("End: %s", pReg->name);
1563                 pReg++;
1564         }
1565         sam3_sprintf(pChip,"   rc-osc: %3.03f MHz\n", _tomhz(pChip->cfg.rc_freq));
1566         sam3_sprintf(pChip,"  mainosc: %3.03f MHz\n", _tomhz(pChip->cfg.mainosc_freq));
1567         sam3_sprintf(pChip,"     plla: %3.03f MHz\n", _tomhz(pChip->cfg.plla_freq));
1568         sam3_sprintf(pChip," cpu-freq: %3.03f MHz\n", _tomhz(pChip->cfg.cpu_freq));
1569         sam3_sprintf(pChip,"mclk-freq: %3.03f MHz\n", _tomhz(pChip->cfg.mclk_freq));
1570
1571
1572         sam3_sprintf(pChip, " UniqueId: 0x%08x 0x%08x 0x%08x 0x%08x\n",
1573                                   pChip->cfg.unique_id[0],
1574                                   pChip->cfg.unique_id[1],
1575                                   pChip->cfg.unique_id[2],
1576                                   pChip->cfg.unique_id[3]);
1577
1578
1579         return ERROR_OK;
1580 }
1581
1582
1583 static int
1584 sam3_erase_check(struct flash_bank_s *bank)
1585 {
1586         int x;
1587
1588         LOG_DEBUG("Here");
1589         if (bank->target->state != TARGET_HALTED) {
1590                 LOG_ERROR("Target not halted");
1591                 return ERROR_TARGET_NOT_HALTED;
1592         }
1593         if (0 == bank->num_sectors) {
1594                 LOG_ERROR("Target: not supported/not probed\n");
1595                 return ERROR_FAIL;
1596         }
1597
1598         LOG_INFO("sam3 - supports auto-erase, erase_check ignored");
1599         for (x = 0 ; x < bank->num_sectors ; x++) {
1600                 bank->sectors[x].is_erased = 1;
1601         }
1602
1603         LOG_DEBUG("Done");
1604         return ERROR_OK;
1605 }
1606
1607 static int
1608 sam3_protect_check(struct flash_bank_s *bank)
1609 {
1610         int r;
1611         uint32_t v;
1612         unsigned x;
1613         struct sam3_bank_private *pPrivate;
1614
1615         LOG_DEBUG("Begin");
1616         if (bank->target->state != TARGET_HALTED) {
1617                 LOG_ERROR("Target not halted");
1618                 return ERROR_TARGET_NOT_HALTED;
1619         }
1620
1621         pPrivate = get_sam3_bank_private(bank);
1622         if (!pPrivate) {
1623                 LOG_ERROR("no private for this bank?");
1624                 return ERROR_FAIL;
1625         }
1626         if (!(pPrivate->probed)) {
1627                 return ERROR_FLASH_BANK_NOT_PROBED;
1628         }
1629
1630         r = FLASHD_GetLockBits(pPrivate , &v);
1631         if (r != ERROR_OK) {
1632                 LOG_DEBUG("Failed: %d",r);
1633                 return r;
1634         }
1635
1636         for (x = 0 ; x < pPrivate->nsectors ; x++) {
1637                 bank->sectors[x].is_protected = (!!(v & (1 << x)));
1638         }
1639         LOG_DEBUG("Done");
1640         return ERROR_OK;
1641 }
1642
1643 static int
1644 sam3_flash_bank_command(struct command_context_s *cmd_ctx,
1645                             char *cmd,
1646                             char **args,
1647                             int argc,
1648                             struct flash_bank_s *bank)
1649 {
1650         struct sam3_chip *pChip;
1651
1652         pChip = all_sam3_chips;
1653
1654         // is this an existing chip?
1655         while (pChip) {
1656                 if (pChip->target == bank->target) {
1657                         break;
1658                 }
1659                 pChip = pChip->next;
1660         }
1661
1662         if (!pChip) {
1663                 // this is a *NEW* chip
1664                 pChip = calloc(1, sizeof(struct sam3_chip));
1665                 if (!pChip) {
1666                         LOG_ERROR("NO RAM!");
1667                         return ERROR_FAIL;
1668                 }
1669                 pChip->target = bank->target;
1670                 // insert at head
1671                 pChip->next = all_sam3_chips;
1672                 all_sam3_chips = pChip;
1673                 pChip->target = bank->target;
1674                 // assumption is this runs at 32khz
1675                 pChip->cfg.slow_freq = 32768;
1676                 pChip->probed = 0;
1677                 pChip->mbuf = membuf_new();
1678                 if (!(pChip->mbuf)) {
1679                         LOG_ERROR("no memory");
1680                         return ERROR_FAIL;
1681                 }
1682         }
1683
1684         switch (bank->base) {
1685         default:
1686                 LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x or 0x%08x)",
1687                                   ((unsigned int)(bank->base)),
1688                                   ((unsigned int)(FLASH_BANK0_BASE)),
1689                                   ((unsigned int)(FLASH_BANK1_BASE)));
1690                 return ERROR_FAIL;
1691                 break;
1692         case FLASH_BANK0_BASE:
1693                 bank->driver_priv = &(pChip->details.bank[0]);
1694                 bank->bank_number = 0;
1695                 pChip->details.bank[0].pChip = pChip;
1696                 pChip->details.bank[0].pBank = bank;
1697                 break;
1698         case FLASH_BANK1_BASE:
1699                 bank->driver_priv = &(pChip->details.bank[1]);
1700                 bank->bank_number = 1;
1701                 pChip->details.bank[1].pChip = pChip;
1702                 pChip->details.bank[1].pBank = bank;
1703                 break;
1704         }
1705
1706         // we initialize after probing.
1707         return ERROR_OK;
1708 }
1709
1710 static int
1711 sam3_GetDetails(struct sam3_bank_private *pPrivate)
1712 {
1713         const struct sam3_chip_details *pDetails;
1714         struct sam3_chip *pChip;
1715         void *vp;
1716         flash_bank_t *saved_banks[SAM3_MAX_FLASH_BANKS];
1717
1718         unsigned x;
1719         const char *cp;
1720
1721         LOG_DEBUG("Begin");
1722         pDetails = all_sam3_details;
1723         while (pDetails->name) {
1724                 if (pDetails->chipid_cidr == pPrivate->pChip->cfg.CHIPID_CIDR) {
1725                         break;
1726                 } else {
1727                         pDetails++;
1728                 }
1729         }
1730         if (pDetails->name == NULL) {
1731                 LOG_ERROR("SAM3 ChipID 0x%08x not found in table (perhaps you can this chip?)",
1732                                   (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
1733                 // Help the victim, print details about the chip
1734                 membuf_reset(pPrivate->pChip->mbuf);
1735                 membuf_sprintf(pPrivate->pChip->mbuf,
1736                                                 "SAM3 CHIPID_CIDR: 0x%08x decodes as follows\n",
1737                                                 pPrivate->pChip->cfg.CHIPID_CIDR);
1738                 sam3_explain_chipid_cidr(pPrivate->pChip);
1739                 cp = membuf_strtok(pPrivate->pChip->mbuf, "\n", &vp);
1740                 while (cp) {
1741                         LOG_INFO("%s", cp);
1742                         cp = membuf_strtok(NULL, "\n", &vp);
1743                 }
1744                 return ERROR_FAIL;
1745         }
1746
1747         // DANGER: THERE ARE DRAGONS HERE
1748
1749         // get our pChip - it is going
1750         // to be over-written shortly
1751         pChip = pPrivate->pChip;
1752
1753         // Note that, in reality:
1754         //
1755         //     pPrivate = &(pChip->details.bank[0])
1756         // or  pPrivate = &(pChip->details.bank[1])
1757         //
1758
1759         // save the "bank" pointers
1760         for (x = 0 ; x < SAM3_MAX_FLASH_BANKS ; x++) {
1761                 saved_banks[ x ] = pChip->details.bank[x].pBank;
1762         }
1763
1764         // Overwrite the "details" structure.
1765         memcpy(&(pPrivate->pChip->details),
1766                         pDetails,
1767                         sizeof(pPrivate->pChip->details));
1768
1769         // now fix the ghosted pointers
1770         for (x = 0 ; x < SAM3_MAX_FLASH_BANKS ; x++) {
1771                 pChip->details.bank[x].pChip = pChip;
1772                 pChip->details.bank[x].pBank = saved_banks[x];
1773         }
1774
1775         // update the *BANK*SIZE*
1776
1777         LOG_DEBUG("End");
1778         return ERROR_OK;
1779 }
1780
1781
1782
1783 static int
1784 _sam3_probe(struct flash_bank_s *bank, int noise)
1785 {
1786         unsigned x;
1787         int r;
1788         struct sam3_bank_private *pPrivate;
1789
1790
1791         LOG_DEBUG("Begin: Bank: %d, Noise: %d", bank->bank_number, noise);
1792         if (bank->target->state != TARGET_HALTED)
1793         {
1794                 LOG_ERROR("Target not halted");
1795                 return ERROR_TARGET_NOT_HALTED;
1796         }
1797
1798         pPrivate = get_sam3_bank_private(bank);
1799         if (!pPrivate) {
1800                 LOG_ERROR("Invalid/unknown bank number\n");
1801                 return ERROR_FAIL;
1802         }
1803
1804         r = sam3_ReadAllRegs(pPrivate->pChip);
1805         if (r != ERROR_OK) {
1806                 return r;
1807         }
1808
1809
1810         LOG_DEBUG("Here");
1811         r = sam3_GetInfo(pPrivate->pChip);
1812         if (r != ERROR_OK) {
1813                 return r;
1814         }
1815         if (!(pPrivate->pChip->probed)) {
1816                 pPrivate->pChip->probed = 1;
1817                 LOG_DEBUG("Here");
1818                 r = sam3_GetDetails(pPrivate);
1819                 if (r != ERROR_OK) {
1820                         return r;
1821                 }
1822         }
1823
1824         // update the flash bank size
1825         for (x = 0 ; x < SAM3_MAX_FLASH_BANKS ; x++) {
1826                 if (bank->base == pPrivate->pChip->details.bank[0].base_address) {
1827                         bank->size =  pPrivate->pChip->details.bank[0].size_bytes;
1828                         break;
1829                 }
1830         }
1831
1832         if (bank->sectors == NULL) {
1833                 bank->sectors     = calloc(pPrivate->nsectors, (sizeof((bank->sectors)[0])));
1834                 if (bank->sectors == NULL) {
1835                         LOG_ERROR("No memory!");
1836                         return ERROR_FAIL;
1837                 }
1838                 bank->num_sectors = pPrivate->nsectors;
1839
1840                 for (x = 0 ; ((int)(x)) < bank->num_sectors ; x++) {
1841                         bank->sectors[x].size         = pPrivate->sector_size;
1842                         bank->sectors[x].offset       = x * (pPrivate->sector_size);
1843                         // mark as unknown
1844                         bank->sectors[x].is_erased    = -1;
1845                         bank->sectors[x].is_protected = -1;
1846                 }
1847         }
1848
1849         pPrivate->probed = 1;
1850
1851         r = sam3_protect_check(bank);
1852         if (r != ERROR_OK) {
1853                 return r;
1854         }
1855
1856         LOG_DEBUG("Bank = %d, nbanks = %d",
1857                           pPrivate->bank_number , pPrivate->pChip->details.n_banks);
1858         if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
1859                 // read unique id,
1860                 // it appears to be associated with the *last* flash bank.
1861                 FLASHD_ReadUniqueID(pPrivate);
1862         }
1863
1864         return r;
1865 }
1866
1867 static int
1868 sam3_probe(struct flash_bank_s *bank)
1869 {
1870         return _sam3_probe(bank, 1);
1871 }
1872
1873 static int
1874 sam3_auto_probe(struct flash_bank_s *bank)
1875 {
1876         return _sam3_probe(bank, 0);
1877 }
1878
1879
1880
1881 static int
1882 sam3_erase(struct flash_bank_s *bank, int first, int last)
1883 {
1884         struct sam3_bank_private *pPrivate;
1885         int r;
1886
1887         LOG_DEBUG("Here");
1888         if (bank->target->state != TARGET_HALTED) {
1889                 LOG_ERROR("Target not halted");
1890                 return ERROR_TARGET_NOT_HALTED;
1891         }
1892
1893         r = sam3_auto_probe(bank);
1894         if (r != ERROR_OK) {
1895                 LOG_DEBUG("Here,r=%d",r);
1896                 return r;
1897         }
1898
1899         pPrivate = get_sam3_bank_private(bank);
1900         if (!(pPrivate->probed)) {
1901                 return ERROR_FLASH_BANK_NOT_PROBED;
1902         }
1903
1904         if ((first == 0) && ((last + 1)== ((int)(pPrivate->nsectors)))) {
1905                 // whole chip
1906                 LOG_DEBUG("Here");
1907                 return FLASHD_EraseEntireBank(pPrivate);
1908         }
1909         LOG_INFO("sam3 auto-erases while programing (request ignored)");
1910         return ERROR_OK;
1911 }
1912
1913 static int
1914 sam3_protect(struct flash_bank_s *bank, int set, int first, int last)
1915 {
1916         struct sam3_bank_private *pPrivate;
1917         int r;
1918
1919         LOG_DEBUG("Here");
1920         if (bank->target->state != TARGET_HALTED) {
1921                 LOG_ERROR("Target not halted");
1922                 return ERROR_TARGET_NOT_HALTED;
1923         }
1924
1925         pPrivate = get_sam3_bank_private(bank);
1926         if (!(pPrivate->probed)) {
1927                 return ERROR_FLASH_BANK_NOT_PROBED;
1928         }
1929
1930         if (set) {
1931                 r = FLASHD_Lock(pPrivate, (unsigned)(first), (unsigned)(last));
1932         } else {
1933                 r = FLASHD_Unlock(pPrivate, (unsigned)(first), (unsigned)(last));
1934         }
1935         LOG_DEBUG("End: r=%d",r);
1936
1937         return r;
1938
1939 }
1940
1941
1942 static int
1943 sam3_info(flash_bank_t *bank, char *buf, int buf_size)
1944 {
1945         if (bank->target->state != TARGET_HALTED) {
1946                 LOG_ERROR("Target not halted");
1947                 return ERROR_TARGET_NOT_HALTED;
1948         }
1949         buf[ 0 ] = 0;
1950         return ERROR_OK;
1951 }
1952
1953 static int
1954 sam3_page_read(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
1955 {
1956         uint32_t adr;
1957         int r;
1958
1959         adr = pagenum * pPrivate->page_size;
1960         adr += adr + pPrivate->base_address;
1961
1962         r = target_read_memory(pPrivate->pChip->target,
1963                                                         adr,
1964                                                         4, /* THIS*MUST*BE* in 32bit values */
1965                                                         pPrivate->page_size / 4,
1966                                                         buf);
1967         if (r != ERROR_OK) {
1968                 LOG_ERROR("SAM3: Flash program failed to read page phys address: 0x%08x", (unsigned int)(adr));
1969         }
1970         return r;
1971 }
1972
1973 // The code below is basically this:
1974 // compiled with
1975 // arm-none-eabi-gcc -mthumb -mcpu = cortex-m3 -O9 -S ./foobar.c -o foobar.s
1976 //
1977 // Only the *CPU* can write to the flash buffer.
1978 // the DAP cannot... so - we download this 28byte thing
1979 // Run the algorithm - (below)
1980 // to program the device
1981 //
1982 // ========================================
1983 // #include <stdint.h>
1984 //
1985 // struct foo {
1986 //   uint32_t *dst;
1987 //   const uint32_t *src;
1988 //   int   n;
1989 //   volatile uint32_t *base;
1990 //   uint32_t   cmd;
1991 // };
1992 //
1993 //
1994 // uint32_t sam3_function(struct foo *p)
1995 // {
1996 //   volatile uint32_t *v;
1997 //   uint32_t *d;
1998 //   const uint32_t *s;
1999 //   int   n;
2000 //   uint32_t r;
2001 //
2002 //   d = p->dst;
2003 //   s = p->src;
2004 //   n = p->n;
2005 //
2006 //   do {
2007 //     *d++ = *s++;
2008 //   } while (--n)
2009 //     ;
2010 //
2011 //   v = p->base;
2012 //
2013 //   v[ 1 ] = p->cmd;
2014 //   do {
2015 //     r = v[8/4];
2016 //   } while (!(r&1))
2017 //     ;
2018 //   return r;
2019 // }
2020 // ========================================
2021
2022
2023
2024 static const uint8_t
2025 sam3_page_write_opcodes[] = {
2026         //  24 0000 0446                mov     r4, r0
2027         0x04,0x46,
2028         //  25 0002 6168                ldr     r1, [r4, #4]
2029         0x61,0x68,
2030         //  26 0004 0068                ldr     r0, [r0, #0]
2031         0x00,0x68,
2032         //  27 0006 A268                ldr     r2, [r4, #8]
2033         0xa2,0x68,
2034         //  28                          @ lr needed for prologue
2035         //  29                  .L2:
2036         //  30 0008 51F8043B            ldr     r3, [r1], #4
2037         0x51,0xf8,0x04,0x3b,
2038         //  31 000c 12F1FF32            adds    r2, r2, #-1
2039         0x12,0xf1,0xff,0x32,
2040         //  32 0010 40F8043B            str     r3, [r0], #4
2041         0x40,0xf8,0x04,0x3b,
2042         //  33 0014 F8D1                bne     .L2
2043         0xf8,0xd1,
2044         //  34 0016 E268                ldr     r2, [r4, #12]
2045         0xe2,0x68,
2046         //  35 0018 2369                ldr     r3, [r4, #16]
2047         0x23,0x69,
2048         //  36 001a 5360                str     r3, [r2, #4]
2049         0x53,0x60,
2050         //  37 001c 0832                adds    r2, r2, #8
2051         0x08,0x32,
2052         //  38                  .L4:
2053         //  39 001e 1068                ldr     r0, [r2, #0]
2054         0x10,0x68,
2055         //  40 0020 10F0010F            tst     r0, #1
2056         0x10,0xf0,0x01,0x0f,
2057         //  41 0024 FBD0                beq     .L4
2058         0xfb,0xd0,
2059         //  42                  .done:
2060         //  43 0026 FEE7                b       .done
2061         0xfe,0xe7
2062 };
2063
2064
2065 static int
2066 sam3_page_write(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *buf)
2067 {
2068         uint32_t adr;
2069         uint32_t status;
2070         int r;
2071
2072         adr = pagenum * pPrivate->page_size;
2073         adr += (adr + pPrivate->base_address);
2074
2075         LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
2076         r = target_write_memory(pPrivate->pChip->target,
2077                                                          adr,
2078                                                          4, /* THIS*MUST*BE* in 32bit values */
2079                                                          pPrivate->page_size / 4,
2080                                                          buf);
2081         if (r != ERROR_OK) {
2082                 LOG_ERROR("SAM3: Failed to write (buffer) page at phys address 0x%08x", (unsigned int)(adr));
2083                 return r;
2084         }
2085
2086         r = EFC_PerformCommand(pPrivate,
2087                                                         // send Erase & Write Page
2088                                                         AT91C_EFC_FCMD_EWP,
2089                                                         pagenum,
2090                                                         &status);
2091
2092         if (r != ERROR_OK) {
2093                 LOG_ERROR("SAM3: Error performing Erase & Write page @ phys address 0x%08x", (unsigned int)(adr));
2094         }
2095         if (status & (1 << 2)) {
2096                 LOG_ERROR("SAM3: Page @ Phys address 0x%08x is locked", (unsigned int)(adr));
2097                 return ERROR_FAIL;
2098         }
2099         if (status & (1 << 1)) {
2100                 LOG_ERROR("SAM3: Flash Command error @phys address 0x%08x", (unsigned int)(adr));
2101                 return ERROR_FAIL;
2102         }
2103         return ERROR_OK;
2104 }
2105
2106
2107
2108
2109
2110 static int
2111 sam3_write(struct flash_bank_s *bank,
2112                    uint8_t *buffer,
2113                    uint32_t offset,
2114                    uint32_t count)
2115 {
2116         int n;
2117         unsigned page_cur;
2118         unsigned page_end;
2119         int r;
2120         unsigned page_offset;
2121         struct sam3_bank_private *pPrivate;
2122         uint8_t *pagebuffer;
2123
2124         // ignore dumb requests
2125         if (count == 0) {
2126                 return ERROR_OK;
2127         }
2128
2129         if (bank->target->state != TARGET_HALTED) {
2130                 LOG_ERROR("Target not halted");
2131                 return ERROR_TARGET_NOT_HALTED;
2132         }
2133
2134         pPrivate = get_sam3_bank_private(bank);
2135         if (!(pPrivate->probed)) {
2136                 return ERROR_FLASH_BANK_NOT_PROBED;
2137         }
2138
2139
2140         if ((offset + count) > pPrivate->size_bytes) {
2141                 LOG_ERROR("Flash write error - past end of bank");
2142                 LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
2143                                   (unsigned int)(offset),
2144                                   (unsigned int)(count),
2145                                   (unsigned int)(pPrivate->size_bytes));
2146                 return ERROR_FAIL;
2147         }
2148
2149         pagebuffer = alloca(pPrivate->page_size);
2150
2151         // what page do we start & end in?
2152         page_cur = offset / pPrivate->page_size;
2153         page_end = (offset + count - 1) / pPrivate->page_size;
2154
2155         LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
2156         LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
2157
2158         // Special case: all one page
2159         //
2160         // Otherwise:
2161         //    (1) non-aligned start
2162         //    (2) body pages
2163         //    (3) non-aligned end.
2164
2165         // Handle special case - all one page.
2166         if (page_cur == page_end) {
2167                 LOG_DEBUG("Special case, all in one page");
2168                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2169                 if (r != ERROR_OK) {
2170                         return r;
2171                 }
2172
2173                 page_offset = (offset & (pPrivate->page_size-1));
2174                 memcpy(pagebuffer + page_offset,
2175                                 buffer,
2176                                 count);
2177
2178                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2179                 if (r != ERROR_OK) {
2180                         return r;
2181                 }
2182                 return ERROR_OK;
2183         }
2184
2185         // non-aligned start
2186         page_offset = offset & (pPrivate->page_size - 1);
2187         if (page_offset) {
2188                 LOG_DEBUG("Not-Aligned start");
2189                 // read the partial
2190                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2191                 if (r != ERROR_OK) {
2192                         return r;
2193                 }
2194
2195                 // over-write with new data
2196                 n = (pPrivate->page_size - page_offset);
2197                 memcpy(pagebuffer + page_offset,
2198                                 buffer,
2199                                 n);
2200
2201                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2202                 if (r != ERROR_OK) {
2203                         return r;
2204                 }
2205
2206                 count  -= n;
2207                 offset += n;
2208                 buffer += n;
2209                 page_cur++;
2210         }
2211
2212         // intermediate large pages
2213         // also - the final *terminal*
2214         // if that terminal page is a full page
2215         LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
2216                           (int)page_cur, (int)page_end, (unsigned int)(count));
2217
2218         while ((page_cur < page_end) &&
2219                    (count >= pPrivate->page_size)) {
2220                 r = sam3_page_write(pPrivate, page_cur, buffer);
2221                 if (r != ERROR_OK) {
2222                         return r;
2223                 }
2224                 count    -= pPrivate->page_size;
2225                 buffer   += pPrivate->page_size;
2226                 page_cur += 1;
2227         }
2228
2229         // terminal partial page?
2230         if (count) {
2231                 LOG_DEBUG("Terminal partial page, count = 0x%08x", (unsigned int)(count));
2232                 // we have a partial page
2233                 r = sam3_page_read(pPrivate, page_cur, pagebuffer);
2234                 if (r != ERROR_OK) {
2235                         return r;
2236                 }
2237                 // data goes at start
2238                 memcpy(pagebuffer, buffer, count);
2239                 r = sam3_page_write(pPrivate, page_cur, pagebuffer);
2240                 if (r != ERROR_OK) {
2241                         return r;
2242                 }
2243                 buffer += count;
2244                 count  -= count;
2245         }
2246         LOG_DEBUG("Done!");
2247         return ERROR_OK;
2248 }
2249
2250 static int
2251 sam3_handle_info_command(struct command_context_s *cmd_ctx, char *cmd, char **argv, int argc)
2252 {
2253         struct sam3_chip *pChip;
2254         void *vp;
2255         const char *cp;
2256         unsigned x;
2257         int r;
2258
2259         pChip = get_current_sam3(cmd_ctx);
2260         if (!pChip) {
2261                 return ERROR_OK;
2262         }
2263
2264         r = 0;
2265
2266         // bank0 must exist before we can do anything
2267         if (pChip->details.bank[0].pBank == NULL) {
2268                 x = 0;
2269         need_define:
2270                 command_print(cmd_ctx,
2271                                            "Please define bank %d via command: flash bank %s ... ",
2272                                            x,
2273                                            at91sam3_flash.name);
2274                 return ERROR_FAIL;
2275         }
2276
2277         // if bank 0 is not probed, then probe it
2278         if (!(pChip->details.bank[0].probed)) {
2279                 r = sam3_auto_probe(pChip->details.bank[0].pBank);
2280                 if (r != ERROR_OK) {
2281                         return ERROR_FAIL;
2282                 }
2283         }
2284         // above garentees the "chip details" structure is valid
2285         // and thus, bank private areas are valid
2286         // and we have a SAM3 chip, what a concept!
2287
2288
2289         // auto-probe other banks, 0 done above
2290     for (x = 1 ; x < SAM3_MAX_FLASH_BANKS ; x++) {
2291                 // skip banks not present
2292                 if (!(pChip->details.bank[x].present)) {
2293                         continue;
2294                 }
2295
2296                 if (pChip->details.bank[x].pBank == NULL) {
2297                         goto need_define;
2298                 }
2299
2300                 if (pChip->details.bank[x].probed) {
2301                         continue;
2302                 }
2303
2304                 r = sam3_auto_probe(pChip->details.bank[x].pBank);
2305                 if (r != ERROR_OK) {
2306                         return r;
2307                 }
2308         }
2309
2310
2311         r = sam3_GetInfo(pChip);
2312         if (r != ERROR_OK) {
2313                 LOG_DEBUG("Sam3Info, Failed %d\n",r);
2314                 return r;
2315         }
2316
2317
2318         // print results
2319         cp = membuf_strtok(pChip->mbuf, "\n", &vp);
2320         while (cp) {
2321                 command_print(cmd_ctx,"%s", cp);
2322                 cp = membuf_strtok(NULL, "\n", &vp);
2323         }
2324         return ERROR_OK;
2325 }
2326
2327 static int
2328 sam3_handle_gpnvm_command(struct command_context_s *cmd_ctx, char *cmd, char **argv, int argc)
2329 {
2330         unsigned x,v;
2331         uint32_t v32;
2332         int r,who;
2333         struct sam3_chip *pChip;
2334
2335         pChip = get_current_sam3(cmd_ctx);
2336         if (!pChip) {
2337                 return ERROR_OK;
2338         }
2339
2340         if (pChip->target->state != TARGET_HALTED) {
2341                 LOG_ERROR("sam3 - target not halted");
2342                 return ERROR_TARGET_NOT_HALTED;
2343         }
2344
2345
2346         if (pChip->details.bank[0].pBank == NULL) {
2347                 command_print(cmd_ctx, "Bank0 must be defined first via: flash bank %s ...",
2348                                            at91sam3_flash.name);
2349                 return ERROR_FAIL;
2350         }
2351         if (!pChip->details.bank[0].probed) {
2352                 r = sam3_auto_probe(pChip->details.bank[0].pBank);
2353                 if (r != ERROR_OK) {
2354                         return r;
2355                 }
2356         }
2357
2358
2359         switch (argc) {
2360         default:
2361                 command_print(cmd_ctx,"Too many parameters\n");
2362                 return ERROR_COMMAND_SYNTAX_ERROR;
2363                 break;
2364         case 0:
2365                 who = -1;
2366                 goto showall;
2367                 break;
2368         case 1:
2369                 who = -1;
2370                 break;
2371         case 2:
2372                 if ((0 == strcmp(argv[0], "show")) && (0 == strcmp(argv[1], "all"))) {
2373                         who = -1;
2374                 } else {
2375                         r = parse_u32(argv[1], &v32);
2376                         if (r != ERROR_OK) {
2377                                 command_print(cmd_ctx, "Not a number: %s", argv[1]);
2378                                 return r;
2379                         }
2380                         who = v32;
2381                 }
2382                 break;
2383         }
2384
2385         if (0 == strcmp("show", argv[0])) {
2386                 if (who == -1) {
2387                 showall:
2388                         r = ERROR_OK;
2389                         for (x = 0 ; x < pChip->details.n_gpnvms ; x++) {
2390                                 r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
2391                                 if (r != ERROR_OK) {
2392                                         break;
2393                                 }
2394                                 command_print(cmd_ctx, "sam3-gpnvm%u: %u", x, v);
2395                         }
2396                         return r;
2397                 }
2398                 if ((who >= 0) && (((unsigned)(who)) < pChip->details.n_gpnvms)) {
2399                         r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), who, &v);
2400                         command_print(cmd_ctx, "sam3-gpnvm%u: %u", who, v);
2401                         return r;
2402                 } else {
2403                         command_print(cmd_ctx, "sam3-gpnvm invalid GPNVM: %u", who);
2404                         return ERROR_COMMAND_SYNTAX_ERROR;
2405                 }
2406         }
2407
2408         if (who == -1) {
2409                 command_print(cmd_ctx, "Missing GPNVM number");
2410                 return ERROR_COMMAND_SYNTAX_ERROR;
2411         }
2412
2413         if (0 == strcmp("set", argv[0])) {
2414                 r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
2415         } else if ((0 == strcmp("clr", argv[0])) ||
2416                            (0 == strcmp("clear", argv[0]))) { // quietly accept both
2417                 r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
2418         } else {
2419                 command_print(cmd_ctx, "Unkown command: %s", argv[0]);
2420                 r = ERROR_COMMAND_SYNTAX_ERROR;
2421         }
2422         return r;
2423 }
2424
2425 static int
2426 sam3_handle_slowclk_command(struct command_context_s *cmd_ctx, char *cmd, char **argv, int argc)
2427 {
2428         uint32_t v;
2429         int r;
2430
2431         struct sam3_chip *pChip;
2432
2433         pChip = get_current_sam3(cmd_ctx);
2434         if (!pChip) {
2435                 return ERROR_OK;
2436         }
2437
2438
2439         switch (argc) {
2440         case 0:
2441                 // show
2442                 break;
2443         case 1:
2444                 // set
2445                 r = parse_u32(argv[0], &v);
2446                 if (v > 200000) {
2447                         // absurd slow clock of 200Khz?
2448                         command_print(cmd_ctx,"Absurd/illegal slow clock freq: %d\n", (int)(v));
2449                         return ERROR_COMMAND_SYNTAX_ERROR;
2450                 }
2451                 pChip->cfg.slow_freq = v;
2452                 break;
2453
2454         default:
2455                 // error
2456                 command_print(cmd_ctx,"Too many parameters");
2457                 return ERROR_COMMAND_SYNTAX_ERROR;
2458                 break;
2459         }
2460         command_print(cmd_ctx, "Slowclk freq: %d.%03dkhz",
2461                                    (int)(pChip->cfg.slow_freq/ 1000),
2462                                    (int)(pChip->cfg.slow_freq% 1000));
2463         return ERROR_OK;
2464 }
2465
2466
2467 static int sam3_registered;
2468 static int
2469 sam3_register_commands(struct command_context_s *cmd_ctx)
2470 {
2471         command_t *pCmd;
2472
2473         // only register once
2474         if (!sam3_registered) {
2475                 sam3_registered++;
2476
2477                 pCmd = register_command(cmd_ctx, NULL, "at91sam3", NULL, COMMAND_ANY, NULL);
2478                 register_command(cmd_ctx, pCmd,
2479                                                   "gpnvm",
2480                                                   sam3_handle_gpnvm_command,
2481                                                   COMMAND_EXEC,
2482                                                   "at91sam3 gpnvm [action [<BIT>], by default 'show', otherwise set | clear BIT");
2483                 register_command(cmd_ctx, pCmd,
2484                                                   "info",
2485                                                   sam3_handle_info_command,
2486                                                   COMMAND_EXEC,
2487                                                   "at91sam3 info - print information about the current sam3 chip");
2488                 register_command(cmd_ctx, pCmd,
2489                                                   "slowclk",
2490                                                   sam3_handle_slowclk_command,
2491                                                   COMMAND_EXEC,
2492                                                   "at91sam3 slowclk [VALUE] set the slowclock frequency (default 32768hz)");
2493         }
2494         return ERROR_OK;
2495 }
2496
2497
2498 flash_driver_t at91sam3_flash =
2499 {
2500         .name                                           = "at91sam3",
2501         .register_commands                      = sam3_register_commands,
2502
2503         .flash_bank_command                     = sam3_flash_bank_command,
2504         .erase                                          = sam3_erase,
2505         .protect                                        = sam3_protect,
2506         .write                                          = sam3_write,
2507         .probe                                          = sam3_probe,
2508         .auto_probe                                     = sam3_auto_probe,
2509         .erase_check                            = sam3_erase_check,
2510         .protect_check                          = sam3_protect_check,
2511         .info                                           = sam3_info
2512 };
2513
2514
2515
2516 /**
2517  * Local Variables: **
2518  * mode: c **
2519  * c-basic-offset: 4 **
2520  * tab-width: 4 **
2521  * End: **
2522  */