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