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