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