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