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