#include "target.h" less wildly
[fw/openocd] / src / flash / at91sam3.c
index a92032d7e98eb11c6af38bcdf3a40ef145833c2b..4507888fcbe797d3306fc05dd7cb6333dd83cc9f 100644 (file)
@@ -23,7 +23,7 @@
 
 /* BEGIN ATMEL COPYRIGHT */
 /* ----------------------------------------------------------------------------
- *         ATMEL Microcontroller Software Support 
+ *         ATMEL Microcontroller Software Support
  * ----------------------------------------------------------------------------
  * Copyright (c) 2009, Atmel Corporation
  *
 #include <stdio.h>
 #include <string.h>
 #include <stddef.h>
-#include "log.h"
 #include "types.h"
 #include "flash.h"
-#include "target.h"
 #include "membuf.h"
 #include "at91sam3.h"
 #include "time_support.h"
@@ -130,7 +128,7 @@ struct sam3_cfg {
        uint32_t CHIPID_EXID;
 
 #define SAM3_SUPC_CR              (0x400E1210)
-       uint32_t SUPC_CR;             
+       uint32_t SUPC_CR;
 
 #define SAM3_PMC_BASE             (0x400E0400)
 #define SAM3_PMC_SCSR             (SAM3_PMC_BASE + 0x0008)
@@ -168,14 +166,14 @@ struct sam3_bank_private {
        int probed;
        // DANGER: THERE ARE DRAGONS HERE..
        // NOTE: If you add more 'ghost' pointers
-       // be aware that you must *manually* update 
+       // be aware that you must *manually* update
        // these pointers in the function sam3_GetDetails()
        // See the comment "Here there be dragons"
 
        // so we can find the chip we belong to
        struct sam3_chip *pChip;
-       // so we can find the orginal bank pointer 
-       flash_bank_t *pBank;
+       // so we can find the orginal bank pointer
+       struct flash_bank *pBank;
        unsigned bank_number;
        uint32_t controller_address;
        uint32_t base_address;
@@ -215,7 +213,7 @@ struct sam3_chip {
 
        // this is "initialized" from the global const structure
        struct sam3_chip_details details;
-       target_t *target;
+       struct target *target;
        struct sam3_cfg cfg;
 
        struct membuf *mbuf;
@@ -231,9 +229,9 @@ struct sam3_reg_list {
 static struct sam3_chip *all_sam3_chips;
 
 static struct sam3_chip *
-get_current_sam3(struct command_context_s *cmd_ctx)
+get_current_sam3(struct command_context *cmd_ctx)
 {
-       target_t *t;
+       struct target *t;
        static struct sam3_chip *p;
 
        t = get_current_target(cmd_ctx);
@@ -268,14 +266,14 @@ static const struct sam3_chip_details all_sam3_details[] = {
                .name           = "at91sam3u4e",
                .total_flash_size     = 256 * 1024,
                .total_sram_size      = 52 * 1024,
-               .n_gpnvms       = 3, 
+               .n_gpnvms       = 3,
                .n_banks        = 2,
 
                // System boots at address 0x0
                // gpnvm[1] = selects boot code
                //     if gpnvm[1] == 0
                //         boot is via "SAMBA" (rom)
-               //     else 
+               //     else
                //         boot is via FLASH
                //         Selection is via gpnvm[2]
                //     endif
@@ -286,21 +284,24 @@ static const struct sam3_chip_details all_sam3_details[] = {
                //      else
                //         Bank1 is the boot rom
                //      endif
-               .bank[0] = { 
+//             .bank[0] = {
+               {
+                 {
                        .probed = 0,
                        .pChip  = NULL,
                        .pBank  = NULL,
                        .bank_number = 0,
-                       .base_address = FLASH_BANK0_BASE, 
+                       .base_address = FLASH_BANK0_BASE,
                        .controller_address = 0x400e0800,
                        .present = 1,
                        .size_bytes = 128 * 1024,
                        .nsectors   = 16,
                        .sector_size = 8192,
                        .page_size   = 256,
-               },
+                 },
 
-               .bank[1] = {
+//             .bank[1] = {
+                 {
                        .probed = 0,
                        .pChip  = NULL,
                        .pBank  = NULL,
@@ -312,6 +313,7 @@ static const struct sam3_chip_details all_sam3_details[] = {
                        .nsectors   = 16,
                        .sector_size = 8192,
                        .page_size   = 256,
+                 },
                },
        },
 
@@ -320,35 +322,38 @@ static const struct sam3_chip_details all_sam3_details[] = {
                .name           = "at91sam3u2e",
                .total_flash_size     = 128 * 1024,
                .total_sram_size      =  36 * 1024,
-               .n_gpnvms       = 2, 
+               .n_gpnvms       = 2,
                .n_banks        = 1,
 
                // System boots at address 0x0
                // gpnvm[1] = selects boot code
                //     if gpnvm[1] == 0
                //         boot is via "SAMBA" (rom)
-               //     else 
+               //     else
                //         boot is via FLASH
                //         Selection is via gpnvm[2]
                //     endif
-               .bank[0] = { 
+//             .bank[0] = {
+               {
+                 {
                        .probed = 0,
                        .pChip  = NULL,
                        .pBank  = NULL,
                        .bank_number = 0,
-                       .base_address = FLASH_BANK0_BASE, 
+                       .base_address = FLASH_BANK0_BASE,
                        .controller_address = 0x400e0800,
                        .present = 1,
                        .size_bytes = 128 * 1024,
                        .nsectors   = 16,
                        .sector_size = 8192,
                        .page_size   = 256,
-               },
-
-               .bank[1] = {
+                 },
+//               .bank[1] = {
+                 {
                        .present = 0,
                        .probed = 0,
                        .bank_number = 1,
+                 },
                },
        },
        {
@@ -356,53 +361,57 @@ static const struct sam3_chip_details all_sam3_details[] = {
                .name           = "at91sam3u1e",
                .total_flash_size     = 64 * 1024,
                .total_sram_size      = 20 * 1024,
-               .n_gpnvms       = 2, 
+               .n_gpnvms       = 2,
                .n_banks        = 1,
 
                // System boots at address 0x0
                // gpnvm[1] = selects boot code
                //     if gpnvm[1] == 0
                //         boot is via "SAMBA" (rom)
-               //     else 
+               //     else
                //         boot is via FLASH
                //         Selection is via gpnvm[2]
                //     endif
                //
-       
-               .bank[0] = { 
+
+//             .bank[0] = {
+               {
+                 {
                        .probed = 0,
                        .pChip  = NULL,
                        .pBank  = NULL,
                        .bank_number = 0,
-                       .base_address = FLASH_BANK0_BASE, 
+                       .base_address = FLASH_BANK0_BASE,
                        .controller_address = 0x400e0800,
                        .present = 1,
                        .size_bytes =  64 * 1024,
                        .nsectors   =  8,
                        .sector_size = 8192,
                        .page_size   = 256,
-               },
+                 },
 
-               .bank[1] = {
+//             .bank[1] = {
+                 {
                        .present = 0,
                        .probed = 0,
                        .bank_number = 1,
+                 },
                },
        },
-               
+
        {
                .chipid_cidr    = 0x28000960,
                .name           = "at91sam3u4c",
                .total_flash_size     = 256 * 1024,
                .total_sram_size      = 52 * 1024,
-               .n_gpnvms       = 3, 
+               .n_gpnvms       = 3,
                .n_banks        = 2,
 
                // System boots at address 0x0
                // gpnvm[1] = selects boot code
                //     if gpnvm[1] == 0
                //         boot is via "SAMBA" (rom)
-               //     else 
+               //     else
                //         boot is via FLASH
                //         Selection is via gpnvm[2]
                //     endif
@@ -413,21 +422,23 @@ static const struct sam3_chip_details all_sam3_details[] = {
                //      else
                //         Bank1 is the boot rom
                //      endif
-               .bank[0] = { 
+               {
+                 {
+//             .bank[0] = {
                        .probed = 0,
                        .pChip  = NULL,
                        .pBank  = NULL,
                        .bank_number = 0,
-                       .base_address = FLASH_BANK0_BASE, 
+                       .base_address = FLASH_BANK0_BASE,
                        .controller_address = 0x400e0800,
                        .present = 1,
                        .size_bytes = 128 * 1024,
                        .nsectors   = 16,
                        .sector_size = 8192,
                        .page_size   = 256,
-               },
-
-               .bank[1] = {
+                 },
+//             .bank[1] = {
+                 {
                        .probed = 0,
                        .pChip  = NULL,
                        .pBank  = NULL,
@@ -439,6 +450,7 @@ static const struct sam3_chip_details all_sam3_details[] = {
                        .nsectors   = 16,
                        .sector_size = 8192,
                        .page_size   = 256,
+                 },
                },
        },
 
@@ -447,35 +459,38 @@ static const struct sam3_chip_details all_sam3_details[] = {
                .name           = "at91sam3u2c",
                .total_flash_size     = 128 * 1024,
                .total_sram_size      = 36 * 1024,
-               .n_gpnvms       = 2, 
+               .n_gpnvms       = 2,
                .n_banks        = 1,
 
                // System boots at address 0x0
                // gpnvm[1] = selects boot code
                //     if gpnvm[1] == 0
                //         boot is via "SAMBA" (rom)
-               //     else 
+               //     else
                //         boot is via FLASH
                //         Selection is via gpnvm[2]
                //     endif
-               .bank[0] = { 
+               {
+//             .bank[0] = {
+                 {
                        .probed = 0,
                        .pChip  = NULL,
                        .pBank  = NULL,
                        .bank_number = 0,
-                       .base_address = FLASH_BANK0_BASE, 
+                       .base_address = FLASH_BANK0_BASE,
                        .controller_address = 0x400e0800,
                        .present = 1,
                        .size_bytes = 128 * 1024,
                        .nsectors   = 16,
                        .sector_size = 8192,
                        .page_size   = 256,
-               },
-
-               .bank[1] = {
+                 },
+//             .bank[1] = {
+                 {
                        .present = 0,
                        .probed = 0,
                        .bank_number = 1,
+                 },
                },
        },
        {
@@ -483,42 +498,46 @@ static const struct sam3_chip_details all_sam3_details[] = {
                .name           = "at91sam3u1c",
                .total_flash_size     = 64 * 1024,
                .total_sram_size      = 20 * 1024,
-               .n_gpnvms       = 2, 
+               .n_gpnvms       = 2,
                .n_banks        = 1,
 
                // System boots at address 0x0
                // gpnvm[1] = selects boot code
                //     if gpnvm[1] == 0
                //         boot is via "SAMBA" (rom)
-               //     else 
+               //     else
                //         boot is via FLASH
                //         Selection is via gpnvm[2]
                //     endif
                //
-       
-               .bank[0] = { 
+
+               {
+//             .bank[0] = {
+                 {
                        .probed = 0,
                        .pChip  = NULL,
                        .pBank  = NULL,
                        .bank_number = 0,
-                       .base_address = FLASH_BANK0_BASE, 
+                       .base_address = FLASH_BANK0_BASE,
                        .controller_address = 0x400e0800,
                        .present = 1,
                        .size_bytes =  64 * 1024,
                        .nsectors   =  8,
                        .sector_size = 8192,
                        .page_size   = 256,
-               },
-
-               .bank[1] = {
+                 },
+//             .bank[1] = {
+                 {
                        .present = 0,
                        .probed = 0,
                        .bank_number = 1,
+
+                 },
                },
        },
 
        // terminate
-       { 
+       {
                .chipid_cidr    = 0,
                .name                   = NULL,
        }
@@ -533,31 +552,32 @@ static const struct sam3_chip_details all_sam3_details[] = {
  **********************************************************************/
 /* *ATMEL* style code - from the SAM3 driver code */
 
-/** Get the current status of the EEFC
- *
+/**
+ * Get the current status of the EEFC and
  * the value of some status bits (LOCKE, PROGE).
  * @param pPrivate - info about the bank
  * @param v        - result goes here
  */
-static int 
+static int
 EFC_GetStatus(struct sam3_bank_private *pPrivate, uint32_t *v)
 {
        int r;
        r = target_read_u32(pPrivate->pChip->target, pPrivate->controller_address + offset_EFC_FSR, v);
-       LOG_DEBUG("Status: 0x%08x (lockerror: %d, cmderror: %d, ready: %d)", 
+       LOG_DEBUG("Status: 0x%08x (lockerror: %d, cmderror: %d, ready: %d)",
                          (unsigned int)(*v),
                          ((unsigned int)((*v >> 2) & 1)),
                          ((unsigned int)((*v >> 1) & 1)),
                          ((unsigned int)((*v >> 0) & 1)));
-                         
+
        return r;
 }
 
-/** Get the result of the last executed command.
+/**
+ * Get the result of the last executed command.
  * @param pPrivate - info about the bank
  * @param v        - result goes here
  */
-static int 
+static int
 EFC_GetResult(struct sam3_bank_private *pPrivate, uint32_t *v)
 {
        int r;
@@ -586,7 +606,7 @@ EFC_StartCommand(struct sam3_bank_private *pPrivate,
 
        case AT91C_EFC_FCMD_WP:
        case AT91C_EFC_FCMD_WPL:
-       case AT91C_EFC_FCMD_EWP: 
+       case AT91C_EFC_FCMD_EWP:
        case AT91C_EFC_FCMD_EWPL:
                // case AT91C_EFC_FCMD_EPL:
                // case AT91C_EFC_FCMD_EPA:
@@ -597,15 +617,15 @@ EFC_StartCommand(struct sam3_bank_private *pPrivate,
                        LOG_ERROR("*BUG*: Embedded flash has only %u pages", (unsigned)(n));
                }
                break;
-               
+
        case AT91C_EFC_FCMD_SFB:
        case AT91C_EFC_FCMD_CFB:
                if (argument >= pPrivate->pChip->details.n_gpnvms) {
-                       LOG_ERROR("*BUG*: Embedded flash has only %d GPNVMs", 
+                       LOG_ERROR("*BUG*: Embedded flash has only %d GPNVMs",
                                          pPrivate->pChip->details.n_gpnvms);
                }
                break;
-               
+
        case AT91C_EFC_FCMD_GETD:
        case AT91C_EFC_FCMD_EA:
        case AT91C_EFC_FCMD_GLB:
@@ -640,11 +660,11 @@ EFC_StartCommand(struct sam3_bank_private *pPrivate,
                                return ERROR_FAIL;
                        } else {
                                retry++;
-                               LOG_ERROR("Flash controller(%d) is not ready, attempting reset", 
+                               LOG_ERROR("Flash controller(%d) is not ready, attempting reset",
                                                  pPrivate->bank_number);
                                // we do that by issuing the *STOP* command
                                EFC_StartCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0);
-                               // above is recursive, and further recursion is blocked by 
+                               // above is recursive, and further recursion is blocked by
                                // if (command == AT91C_EFC_FCMD_SPUI) above
                                goto do_retry;
                        }
@@ -653,7 +673,7 @@ EFC_StartCommand(struct sam3_bank_private *pPrivate,
 
        v = (0x5A << 24) | (argument << 8) | command;
        LOG_DEBUG("Command: 0x%08x", ((unsigned int)(v)));
-       r = target_write_u32(pPrivate->pBank->target, 
+       r = target_write_u32(pPrivate->pBank->target,
                                                  pPrivate->controller_address + offset_EFC_FCR,
                                                  v);
        if (r != ERROR_OK) {
@@ -662,17 +682,17 @@ EFC_StartCommand(struct sam3_bank_private *pPrivate,
        return r;
 }
 
-/** Performs the given command and wait until its completion (or an error).
- *
+/**
+ * Performs the given command and wait until its completion (or an error).
  * @param pPrivate - info about the bank
  * @param command  - Command to perform.
  * @param argument - Optional command argument.
  * @param status   - put command status bits here
  */
-static int 
-EFC_PerformCommand(struct sam3_bank_private *pPrivate, 
-                                       unsigned command, 
-                                       unsigned argument, 
+static int
+EFC_PerformCommand(struct sam3_bank_private *pPrivate,
+                                       unsigned command,
+                                       unsigned argument,
                                        uint32_t *status)
 {
 
@@ -680,7 +700,7 @@ EFC_PerformCommand(struct sam3_bank_private *pPrivate,
        uint32_t v;
        long long ms_now, ms_end;
 
-       // default 
+       // default
        if (status) {
                *status = 0;
        }
@@ -720,13 +740,11 @@ EFC_PerformCommand(struct sam3_bank_private *pPrivate,
 
 
 
-/** Read the unique ID.
- * 
- * \param pPrivate - info about the bank
- *
+/**
+ * Read the unique ID.
+ * @param pPrivate - info about the bank
  * The unique ID is stored in the 'pPrivate' structure.
  */
-
 static int
 FLASHD_ReadUniqueID (struct sam3_bank_private *pPrivate)
 {
@@ -746,7 +764,7 @@ FLASHD_ReadUniqueID (struct sam3_bank_private *pPrivate)
        }
 
        for (x = 0 ; x < 4 ; x++) {
-               r = target_read_u32(pPrivate->pChip->target, 
+               r = target_read_u32(pPrivate->pChip->target,
                                                         pPrivate->pBank->base + (x * 4),
                                                         &v);
                if (r < 0) {
@@ -757,16 +775,17 @@ FLASHD_ReadUniqueID (struct sam3_bank_private *pPrivate)
 
     r = EFC_PerformCommand(pPrivate, AT91C_EFC_FCMD_SPUI, 0, NULL);
        LOG_DEBUG("End: R=%d, id = 0x%08x, 0x%08x, 0x%08x, 0x%08x",
-                         r, 
+                         r,
                          (unsigned int)(pPrivate->pChip->cfg.unique_id[0]),
                          (unsigned int)(pPrivate->pChip->cfg.unique_id[1]),
                          (unsigned int)(pPrivate->pChip->cfg.unique_id[2]),
                          (unsigned int)(pPrivate->pChip->cfg.unique_id[3]));
        return r;
-       
+
 }
 
-/** Erases the entire flash.
+/**
+ * Erases the entire flash.
  * @param pPrivate - the info about the bank.
  */
 static int
@@ -778,14 +797,14 @@ FLASHD_EraseEntireBank(struct sam3_bank_private *pPrivate)
 
 
 
-/** Gets current GPNVM state.
+/**
+ * Gets current GPNVM state.
  * @param pPrivate - info about the bank.
  * @param gpnvm    -  GPNVM bit index.
  * @param puthere  - result stored here.
- *
  */
 //------------------------------------------------------------------------------
-static int 
+static int
 FLASHD_GetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm, unsigned *puthere)
 {
        uint32_t v;
@@ -814,7 +833,7 @@ FLASHD_GetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm, unsigned *pu
 
        if (puthere) {
                // Check if GPNVM is set
-               // get the bit and make it a 0/1 
+               // get the bit and make it a 0/1
                *puthere = (v >> gpnvm) & 1;
        }
 
@@ -824,12 +843,13 @@ FLASHD_GetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm, unsigned *pu
 
 
 
-/** Clears the selected GPNVM bit.
- * @param gpnvm  GPNVM index.
- *
- * Returns 0 if successful; otherwise returns an error code.
+/**
+ * Clears the selected GPNVM bit.
+ * @param pPrivate info about the bank
+ * @param gpnvm GPNVM index.
+ * @returns 0 if successful; otherwise returns an error code.
  */
-static int 
+static int
 FLASHD_ClrGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm)
 {
        int r;
@@ -859,11 +879,12 @@ FLASHD_ClrGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm)
 
 
 
-/** Sets the selected GPNVM bit.
- *  @param gpnvm  GPNVM index.
- *
+/**
+ * Sets the selected GPNVM bit.
+ * @param pPrivate info about the bank
+ * @param gpnvm GPNVM index.
  */
-static int 
+static int
 FLASHD_SetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm)
 {
        int r;
@@ -895,13 +916,12 @@ FLASHD_SetGPNVM(struct sam3_bank_private *pPrivate, unsigned gpnvm)
 }
 
 
-/** Returns a bit field (at most 64) of locked regions within a page.
- * @param pPrivate - info about the bank
- * @param v        - where to store locked bits
- * \param end  End address of range.
+/**
+ * Returns a bit field (at most 64) of locked regions within a page.
+ * @param pPrivate info about the bank
+ * @param v where to store locked bits
  */
-
-static int 
+static int
 FLASHD_GetLockBits(struct sam3_bank_private *pPrivate, uint32_t *v)
 {
        int r;
@@ -915,10 +935,11 @@ FLASHD_GetLockBits(struct sam3_bank_private *pPrivate, uint32_t *v)
 }
 
 
-/**Unlocks all the regions in the given address range. 
- *
- * \param start_sector - first sector to unlock
- * \param end_sector   - last (inclusive) to unlock
+/**
+ * Unlocks all the regions in the given address range.
+ * @param pPrivate info about the bank
+ * @param start_sector first sector to unlock
+ * @param end_sector last (inclusive) to unlock
  */
 
 static int
@@ -948,14 +969,13 @@ FLASHD_Unlock(struct sam3_bank_private *pPrivate,
 }
 
 
-/** Locks regions
- *
+/**
+ * Locks regions
+ * @param pPrivate - info about the bank
  * @param start_sector - first sector to lock
  * @param end_sector   - last sector (inclusive) to lock
  */
-
-
-static int 
+static int
 FLASHD_Lock(struct sam3_bank_private *pPrivate,
                         unsigned start_sector,
                         unsigned end_sector)
@@ -966,7 +986,7 @@ FLASHD_Lock(struct sam3_bank_private *pPrivate,
        int r;
 
        pages_per_sector = pPrivate->sector_size / pPrivate->page_size;
-       
+
     /* Lock all pages */
     while (start_sector <= end_sector) {
                pg = start_sector * pages_per_sector;
@@ -999,8 +1019,8 @@ sam3_sprintf(struct sam3_chip *pChip , const char *fmt, ...)
 }
 
 // print the fieldname, the field value, in dec & hex, and return field value
-static uint32_t 
-sam3_reg_fieldname(struct sam3_chip *pChip, 
+static uint32_t
+sam3_reg_fieldname(struct sam3_chip *pChip,
                                        const char *regname,
                                        uint32_t value,
                                        unsigned shift,
@@ -1020,9 +1040,9 @@ sam3_reg_fieldname(struct sam3_chip *pChip,
                hwidth = 8;
                dwidth = 12;
        }
-       
+
        // show the basics
-       sam3_sprintf(pChip, "\t%*s: %*d [0x%0*x] ", 
+       sam3_sprintf(pChip, "\t%*s: %*d [0x%0*x] ",
                                  REG_NAME_WIDTH, regname,
                                  dwidth, v,
                                  hwidth, v);
@@ -1034,7 +1054,7 @@ static const char _unknown[] = "unknown";
 static const char * const eproc_names[] = {
        _unknown,                                       // 0
        "arm946es",                                     // 1
-       "arm7tdmi",                                     // 2 
+       "arm7tdmi",                                     // 2
        "cortex-m3",                            // 3
        "arm920t",                                      // 4
        "arm926ejs",                            // 5
@@ -1075,13 +1095,13 @@ static const char * const sramsize[] = {
        "48K Bytes",                            //  0
        "1K Bytes",                                     //  1
        "2K Bytes",                                     //  2
-       "6K Bytes",                                     //  3 
+       "6K Bytes",                                     //  3
        "112K Bytes",                           //  4
        "4K Bytes",                                     //  5
        "80K Bytes",                            //  6
        "160K Bytes",                           //  7
-       "8K Bytes",                                     //  8 
-       "16K Bytes",                            //  9 
+       "8K Bytes",                                     //  8
+       "16K Bytes",                            //  9
        "32K Bytes",                            // 10
        "64K Bytes",                            // 11
        "128K Bytes",                           // 12
@@ -1133,8 +1153,8 @@ static const char * const nvptype[] = {
        "sram emulating flash", // 4
        _unknown, // 5
        _unknown, // 6
-       _unknown, // 7  
-       
+       _unknown, // 7
+
 };
 
 static const char *_yes_or_no(uint32_t v)
@@ -1150,7 +1170,7 @@ static const char * const _rc_freq[] = {
        "4 MHz", "8 MHz", "12 MHz", "reserved"
 };
 
-static void 
+static void
 sam3_explain_ckgr_mor(struct sam3_chip *pChip)
 {
        uint32_t v;
@@ -1159,7 +1179,7 @@ sam3_explain_ckgr_mor(struct sam3_chip *pChip)
        v = sam3_reg_fieldname(pChip, "MOSCXTEN", pChip->cfg.CKGR_MOR, 0, 1);
        sam3_sprintf(pChip, "(main xtal enabled: %s)\n",
                                  _yes_or_no(v));
-       v = sam3_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1); 
+       v = sam3_reg_fieldname(pChip, "MOSCXTBY", pChip->cfg.CKGR_MOR, 1, 1);
        sam3_sprintf(pChip, "(main osc bypass: %s)\n",
                                  _yes_or_no(v));
        rcen = sam3_reg_fieldname(pChip, "MOSCRCEN", pChip->cfg.CKGR_MOR, 2, 1);
@@ -1192,15 +1212,15 @@ sam3_explain_ckgr_mor(struct sam3_chip *pChip)
        v = sam3_reg_fieldname(pChip, "MOSCSEL", pChip->cfg.CKGR_MOR, 24, 1);
        sam3_sprintf(pChip, "(mainosc source: %s)\n",
                                  v ? "external xtal" : "internal RC");
-       
+
        v = sam3_reg_fieldname(pChip,"CFDEN", pChip->cfg.CKGR_MOR, 25, 1);
        sam3_sprintf(pChip, "(clock failure enabled: %s)\n",
                                 _yes_or_no(v));
 }
 
-       
 
-static void 
+
+static void
 sam3_explain_chipid_cidr(struct sam3_chip *pChip)
 {
        int x;
@@ -1212,7 +1232,7 @@ sam3_explain_chipid_cidr(struct sam3_chip *pChip)
 
        v = sam3_reg_fieldname(pChip, "EPROC", pChip->cfg.CHIPID_CIDR, 5, 3);
        sam3_sprintf(pChip, "%s\n", eproc_names[v]);
-       
+
        v = sam3_reg_fieldname(pChip, "NVPSIZE", pChip->cfg.CHIPID_CIDR, 8, 4);
        sam3_sprintf(pChip, "%s\n", nvpsize[v]);
 
@@ -1230,7 +1250,7 @@ sam3_explain_chipid_cidr(struct sam3_chip *pChip)
                        break;
                }
        }
-       
+
        sam3_sprintf(pChip, "%s\n", cp);
 
        v = sam3_reg_fieldname(pChip, "NVPTYP", pChip->cfg.CHIPID_CIDR, 28, 3);
@@ -1240,17 +1260,17 @@ sam3_explain_chipid_cidr(struct sam3_chip *pChip)
        sam3_sprintf(pChip, "(exists: %s)\n", _yes_or_no(v));
 }
 
-static void 
+static void
 sam3_explain_ckgr_mcfr(struct sam3_chip *pChip)
 {
        uint32_t v;
 
-       
+
        v = sam3_reg_fieldname(pChip, "MAINFRDY", pChip->cfg.CKGR_MCFR, 16, 1);
        sam3_sprintf(pChip, "(main ready: %s)\n", _yes_or_no(v));
 
        v = sam3_reg_fieldname(pChip, "MAINF", pChip->cfg.CKGR_MCFR, 0, 16);
-       
+
        v = (v * pChip->cfg.slow_freq) / 16;
        pChip->cfg.mainosc_freq = v;
 
@@ -1281,14 +1301,14 @@ sam3_explain_ckgr_plla(struct sam3_chip *pChip)
                                         _tomhz(pChip->cfg.plla_freq));
        }
 }
-               
-               
+
+
 static void
 sam3_explain_mckr(struct sam3_chip *pChip)
 {
-       uint32_t css, pres,fin;
-       int pdiv;
-       const char *cp;
+       uint32_t css, pres, fin = 0;
+       int pdiv = 0;
+       const char *cp = NULL;
 
        css = sam3_reg_fieldname(pChip, "CSS", pChip->cfg.PMC_MCKR, 0, 2);
        switch (css & 3) {
@@ -1313,10 +1333,13 @@ sam3_explain_mckr(struct sam3_chip *pChip)
                        cp  = "upll (*ERROR* UPLL is disabled)";
                }
                break;
+       default:
+               assert(0);
+               break;
        }
 
        sam3_sprintf(pChip, "%s (%3.03f Mhz)\n",
-                                 cp, 
+                                 cp,
                                  _tomhz(fin));
        pres = sam3_reg_fieldname(pChip, "PRES", pChip->cfg.PMC_MCKR, 4, 3);
        switch (pres & 0x07) {
@@ -1351,10 +1374,13 @@ sam3_explain_mckr(struct sam3_chip *pChip)
                pdiv = 6;
                cp = "clock/6";
                break;
+       default:
+               assert(0);
+               break;
        }
        sam3_sprintf(pChip, "(%s)\n", cp);
        fin = fin / pdiv;
-       // sam3 has a *SINGLE* clock - 
+       // sam3 has a *SINGLE* clock -
        // other at91 series parts have divisors for these.
        pChip->cfg.cpu_freq = fin;
        pChip->cfg.mclk_freq = fin;
@@ -1362,10 +1388,10 @@ sam3_explain_mckr(struct sam3_chip *pChip)
        sam3_sprintf(pChip, "\t\tResult CPU Freq: %3.03f\n",
                                  _tomhz(fin));
 }
-       
+
 #if 0
 static struct sam3_chip *
-target2sam3(target_t *pTarget)
+target2sam3(struct target *pTarget)
 {
        struct sam3_chip *pChip;
 
@@ -1388,7 +1414,7 @@ target2sam3(target_t *pTarget)
 static uint32_t *
 sam3_get_reg_ptr(struct sam3_cfg *pCfg, const struct sam3_reg_list *pList)
 {
-       // this function exists to help 
+       // this function exists to help
        // keep funky offsetof() errors
        // and casting from causing bugs
 
@@ -1397,8 +1423,8 @@ sam3_get_reg_ptr(struct sam3_cfg *pCfg, const struct sam3_reg_list *pList)
 
        return ((uint32_t *)(((char *)(pCfg)) + pList->struct_offset));
 }
-       
-       
+
+
 #define SAM3_ENTRY(NAME, FUNC)  { .address = SAM3_ ## NAME, .struct_offset = offsetof(struct sam3_cfg, NAME), #NAME, FUNC }
 static const struct sam3_reg_list sam3_all_regs[] = {
        SAM3_ENTRY(CKGR_MOR , sam3_explain_ckgr_mor),
@@ -1428,14 +1454,14 @@ static const struct sam3_reg_list sam3_all_regs[] = {
 
 
 static struct sam3_bank_private *
-get_sam3_bank_private(flash_bank_t *bank)
+get_sam3_bank_private(struct flash_bank *bank)
 {
        return (struct sam3_bank_private *)(bank->driver_priv);
 }
 
-/*
- * Given a pointer to where it goes in the structure..
- *    Determine the register name, address from the all registers table.
+/**
+ * Given a pointer to where it goes in the structure,
+ * determine the register name, address from the all registers table.
  */
 static const struct sam3_reg_list *
 sam3_GetReg(struct sam3_chip *pChip, uint32_t *goes_here)
@@ -1448,7 +1474,7 @@ sam3_GetReg(struct sam3_chip *pChip, uint32_t *goes_here)
 
                // calculate where this one go..
                // it is "possibly" this register.
-               
+
                pPossible = ((uint32_t *)(((char *)(&(pChip->cfg))) + pReg->struct_offset));
 
                // well? Is it this register
@@ -1484,8 +1510,8 @@ sam3_ReadThisReg(struct sam3_chip *pChip, uint32_t *goes_here)
        }
        return r;
 }
-               
-       
+
+
 
 static int
 sam3_ReadAllRegs(struct sam3_chip *pChip)
@@ -1495,14 +1521,14 @@ sam3_ReadAllRegs(struct sam3_chip *pChip)
 
        pReg = &(sam3_all_regs[0]);
        while (pReg->name) {
-               r = sam3_ReadThisReg(pChip, 
+               r = sam3_ReadThisReg(pChip,
                                                                  sam3_get_reg_ptr(&(pChip->cfg), pReg));
                if (r != ERROR_OK) {
                        LOG_ERROR("Cannot read SAM3 registere: %s @ 0x%08x, Error: %d\n",
                                          pReg->name, ((unsigned)(pReg->address)), r);
                        return r;
                }
-               
+
                pReg++;
        }
 
@@ -1524,7 +1550,7 @@ sam3_GetInfo(struct sam3_chip *pChip)
                // display all regs
                LOG_DEBUG("Start: %s", pReg->name);
                regval = *sam3_get_reg_ptr(&(pChip->cfg), pReg);
-               sam3_sprintf(pChip, "%*s: [0x%08x] -> 0x%08x\n", 
+               sam3_sprintf(pChip, "%*s: [0x%08x] -> 0x%08x\n",
                                         REG_NAME_WIDTH,
                                         pReg->name,
                                         pReg->address,
@@ -1539,7 +1565,7 @@ sam3_GetInfo(struct sam3_chip *pChip)
        sam3_sprintf(pChip,"  mainosc: %3.03f MHz\n", _tomhz(pChip->cfg.mainosc_freq));
        sam3_sprintf(pChip,"     plla: %3.03f MHz\n", _tomhz(pChip->cfg.plla_freq));
        sam3_sprintf(pChip," cpu-freq: %3.03f MHz\n", _tomhz(pChip->cfg.cpu_freq));
-       sam3_sprintf(pChip,"mclk-freq: %3.03f MHz\n", _tomhz(pChip->cfg.mclk_freq));    
+       sam3_sprintf(pChip,"mclk-freq: %3.03f MHz\n", _tomhz(pChip->cfg.mclk_freq));
 
 
        sam3_sprintf(pChip, " UniqueId: 0x%08x 0x%08x 0x%08x 0x%08x\n",
@@ -1548,13 +1574,13 @@ sam3_GetInfo(struct sam3_chip *pChip)
                                  pChip->cfg.unique_id[2],
                                  pChip->cfg.unique_id[3]);
 
-       
+
        return ERROR_OK;
 }
 
-       
-static int 
-sam3_erase_check(struct flash_bank_s *bank)
+
+static int
+sam3_erase_check(struct flash_bank *bank)
 {
        int x;
 
@@ -1577,11 +1603,11 @@ sam3_erase_check(struct flash_bank_s *bank)
        return ERROR_OK;
 }
 
-static int 
-sam3_protect_check(struct flash_bank_s *bank)
+static int
+sam3_protect_check(struct flash_bank *bank)
 {
        int r;
-       uint32_t v;
+       uint32_t v=0;
        unsigned x;
        struct sam3_bank_private *pPrivate;
 
@@ -1599,7 +1625,7 @@ sam3_protect_check(struct flash_bank_s *bank)
        if (!(pPrivate->probed)) {
                return ERROR_FLASH_BANK_NOT_PROBED;
        }
-       
+
        r = FLASHD_GetLockBits(pPrivate , &v);
        if (r != ERROR_OK) {
                LOG_DEBUG("Failed: %d",r);
@@ -1613,17 +1639,12 @@ sam3_protect_check(struct flash_bank_s *bank)
        return ERROR_OK;
 }
 
-static int 
-sam3_flash_bank_command(struct command_context_s *cmd_ctx, 
-                           char *cmd, 
-                           char **args, 
-                           int argc, 
-                           struct flash_bank_s *bank)
+FLASH_BANK_COMMAND_HANDLER(sam3_flash_bank_command)
 {
        struct sam3_chip *pChip;
 
        pChip = all_sam3_chips;
-       
+
        // is this an existing chip?
        while (pChip) {
                if (pChip->target == bank->target) {
@@ -1653,7 +1674,7 @@ sam3_flash_bank_command(struct command_context_s *cmd_ctx,
                        return ERROR_FAIL;
                }
        }
-       
+
        switch (bank->base) {
        default:
                LOG_ERROR("Address 0x%08x invalid bank address (try 0x%08x or 0x%08x)",
@@ -1686,7 +1707,7 @@ sam3_GetDetails(struct sam3_bank_private *pPrivate)
        const struct sam3_chip_details *pDetails;
        struct sam3_chip *pChip;
        void *vp;
-       flash_bank_t *saved_banks[SAM3_MAX_FLASH_BANKS];
+       struct flash_bank *saved_banks[SAM3_MAX_FLASH_BANKS];
 
        unsigned x;
        const char *cp;
@@ -1701,11 +1722,11 @@ sam3_GetDetails(struct sam3_bank_private *pPrivate)
                }
        }
        if (pDetails->name == NULL) {
-               LOG_ERROR("SAM3 ChipID 0x%08x not found in table (perhaps you can this chip?)", 
+               LOG_ERROR("SAM3 ChipID 0x%08x not found in table (perhaps you can this chip?)",
                                  (unsigned int)(pPrivate->pChip->cfg.CHIPID_CIDR));
                // Help the victim, print details about the chip
                membuf_reset(pPrivate->pChip->mbuf);
-               membuf_sprintf(pPrivate->pChip->mbuf, 
+               membuf_sprintf(pPrivate->pChip->mbuf,
                                                "SAM3 CHIPID_CIDR: 0x%08x decodes as follows\n",
                                                pPrivate->pChip->cfg.CHIPID_CIDR);
                sam3_explain_chipid_cidr(pPrivate->pChip);
@@ -1735,8 +1756,8 @@ sam3_GetDetails(struct sam3_bank_private *pPrivate)
        }
 
        // Overwrite the "details" structure.
-       memcpy(&(pPrivate->pChip->details), 
-                       pDetails, 
+       memcpy(&(pPrivate->pChip->details),
+                       pDetails,
                        sizeof(pPrivate->pChip->details));
 
        // now fix the ghosted pointers
@@ -1745,16 +1766,16 @@ sam3_GetDetails(struct sam3_bank_private *pPrivate)
                pChip->details.bank[x].pBank = saved_banks[x];
        }
 
-       // update the *BANK*SIZE* 
+       // update the *BANK*SIZE*
 
        LOG_DEBUG("End");
        return ERROR_OK;
-}              
-                                 
+}
+
 
 
-static int 
-_sam3_probe(struct flash_bank_s *bank, int noise)
+static int
+_sam3_probe(struct flash_bank *bank, int noise)
 {
        unsigned x;
        int r;
@@ -1779,7 +1800,7 @@ _sam3_probe(struct flash_bank_s *bank, int noise)
                return r;
        }
 
-       
+
        LOG_DEBUG("Here");
        r = sam3_GetInfo(pPrivate->pChip);
        if (r != ERROR_OK) {
@@ -1791,7 +1812,7 @@ _sam3_probe(struct flash_bank_s *bank, int noise)
                r = sam3_GetDetails(pPrivate);
                if (r != ERROR_OK) {
                        return r;
-               }               
+               }
        }
 
        // update the flash bank size
@@ -1809,7 +1830,7 @@ _sam3_probe(struct flash_bank_s *bank, int noise)
                        return ERROR_FAIL;
                }
                bank->num_sectors = pPrivate->nsectors;
-                       
+
                for (x = 0 ; ((int)(x)) < bank->num_sectors ; x++) {
                        bank->sectors[x].size         = pPrivate->sector_size;
                        bank->sectors[x].offset       = x * (pPrivate->sector_size);
@@ -1829,7 +1850,7 @@ _sam3_probe(struct flash_bank_s *bank, int noise)
        LOG_DEBUG("Bank = %d, nbanks = %d",
                          pPrivate->bank_number , pPrivate->pChip->details.n_banks);
        if ((pPrivate->bank_number + 1) == pPrivate->pChip->details.n_banks) {
-               // read unique id, 
+               // read unique id,
                // it appears to be associated with the *last* flash bank.
                FLASHD_ReadUniqueID(pPrivate);
        }
@@ -1837,22 +1858,22 @@ _sam3_probe(struct flash_bank_s *bank, int noise)
        return r;
 }
 
-static int 
-sam3_probe(struct flash_bank_s *bank)
+static int
+sam3_probe(struct flash_bank *bank)
 {
        return _sam3_probe(bank, 1);
 }
 
-static int 
-sam3_auto_probe(struct flash_bank_s *bank)
+static int
+sam3_auto_probe(struct flash_bank *bank)
 {
        return _sam3_probe(bank, 0);
 }
 
 
 
-static int 
-sam3_erase(struct flash_bank_s *bank, int first, int last)
+static int
+sam3_erase(struct flash_bank *bank, int first, int last)
 {
        struct sam3_bank_private *pPrivate;
        int r;
@@ -1883,8 +1904,8 @@ sam3_erase(struct flash_bank_s *bank, int first, int last)
        return ERROR_OK;
 }
 
-static int 
-sam3_protect(struct flash_bank_s *bank, int set, int first, int last)
+static int
+sam3_protect(struct flash_bank *bank, int set, int first, int last)
 {
        struct sam3_bank_private *pPrivate;
        int r;
@@ -1908,12 +1929,12 @@ sam3_protect(struct flash_bank_s *bank, int set, int first, int last)
        LOG_DEBUG("End: r=%d",r);
 
        return r;
-               
+
 }
 
 
 static int
-sam3_info(flash_bank_t *bank, char *buf, int buf_size)
+sam3_info(struct flash_bank *bank, char *buf, int buf_size)
 {
        if (bank->target->state != TARGET_HALTED) {
                LOG_ERROR("Target not halted");
@@ -1932,7 +1953,7 @@ sam3_page_read(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *bu
        adr = pagenum * pPrivate->page_size;
        adr += adr + pPrivate->base_address;
 
-       r = target_read_memory(pPrivate->pChip->target, 
+       r = target_read_memory(pPrivate->pChip->target,
                                                        adr,
                                                        4, /* THIS*MUST*BE* in 32bit values */
                                                        pPrivate->page_size / 4,
@@ -1951,11 +1972,11 @@ sam3_page_read(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *bu
 // the DAP cannot... so - we download this 28byte thing
 // Run the algorithm - (below)
 // to program the device
-// 
+//
 // ========================================
 // #include <stdint.h>
-// 
-// struct foo { 
+//
+// struct foo {
 //   uint32_t *dst;
 //   const uint32_t *src;
 //   int   n;
@@ -1963,7 +1984,7 @@ sam3_page_read(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *bu
 //   uint32_t   cmd;
 // };
 //
-// 
+//
 // uint32_t sam3_function(struct foo *p)
 // {
 //   volatile uint32_t *v;
@@ -1971,18 +1992,18 @@ sam3_page_read(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *bu
 //   const uint32_t *s;
 //   int   n;
 //   uint32_t r;
-// 
+//
 //   d = p->dst;
 //   s = p->src;
 //   n = p->n;
-// 
+//
 //   do {
 //     *d++ = *s++;
 //   } while (--n)
 //     ;
-// 
+//
 //   v = p->base;
-//   
+//
 //   v[ 1 ] = p->cmd;
 //   do {
 //     r = v[8/4];
@@ -1994,7 +2015,7 @@ sam3_page_read(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *bu
 
 
 
-static const uint8_t 
+static const uint8_t
 sam3_page_write_opcodes[] = {
        //  24 0000 0446                mov     r4, r0
        0x04,0x46,
@@ -2046,7 +2067,7 @@ sam3_page_write(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *b
        adr += (adr + pPrivate->base_address);
 
        LOG_DEBUG("Wr Page %u @ phys address: 0x%08x", pagenum, (unsigned int)(adr));
-       r = target_write_memory(pPrivate->pChip->target, 
+       r = target_write_memory(pPrivate->pChip->target,
                                                         adr,
                                                         4, /* THIS*MUST*BE* in 32bit values */
                                                         pPrivate->page_size / 4,
@@ -2075,15 +2096,15 @@ sam3_page_write(struct sam3_bank_private *pPrivate, unsigned pagenum, uint8_t *b
        }
        return ERROR_OK;
 }
-                                               
-                                               
-                                               
-                                 
-
-static int 
-sam3_write(struct flash_bank_s *bank, 
-                  uint8_t *buffer, 
-                  uint32_t offset, 
+
+
+
+
+
+static int
+sam3_write(struct flash_bank *bank,
+                  uint8_t *buffer,
+                  uint32_t offset,
                   uint32_t count)
 {
        int n;
@@ -2094,65 +2115,78 @@ sam3_write(struct flash_bank_s *bank,
        struct sam3_bank_private *pPrivate;
        uint8_t *pagebuffer;
 
+       // incase we bail further below, set this to null
+       pagebuffer = NULL;
+
        // ignore dumb requests
        if (count == 0) {
-               return ERROR_OK;
+               r = ERROR_OK;
+               goto done;
        }
 
        if (bank->target->state != TARGET_HALTED) {
                LOG_ERROR("Target not halted");
-               return ERROR_TARGET_NOT_HALTED;
+               r = ERROR_TARGET_NOT_HALTED;
+               goto done;
        }
 
        pPrivate = get_sam3_bank_private(bank);
        if (!(pPrivate->probed)) {
-               return ERROR_FLASH_BANK_NOT_PROBED;
+               r = ERROR_FLASH_BANK_NOT_PROBED;
+               goto done;
        }
 
 
        if ((offset + count) > pPrivate->size_bytes) {
                LOG_ERROR("Flash write error - past end of bank");
                LOG_ERROR(" offset: 0x%08x, count 0x%08x, BankEnd: 0x%08x",
-                                 (unsigned int)(offset), 
+                                 (unsigned int)(offset),
                                  (unsigned int)(count),
                                  (unsigned int)(pPrivate->size_bytes));
-               return ERROR_FAIL;
+               r = ERROR_FAIL;
+               goto done;
+       }
+
+       pagebuffer = malloc(pPrivate->page_size);
+       if( !pagebuffer ){
+               LOG_ERROR("No memory for %d Byte page buffer", (int)(pPrivate->page_size));
+               r = ERROR_FAIL;
+               goto done;
        }
 
-       pagebuffer = alloca(pPrivate->page_size);
-               
        // what page do we start & end in?
        page_cur = offset / pPrivate->page_size;
        page_end = (offset + count - 1) / pPrivate->page_size;
-       
+
        LOG_DEBUG("Offset: 0x%08x, Count: 0x%08x", (unsigned int)(offset), (unsigned int)(count));
        LOG_DEBUG("Page start: %d, Page End: %d", (int)(page_cur), (int)(page_end));
-                         
+
        // Special case: all one page
        //
        // Otherwise:
        //    (1) non-aligned start
        //    (2) body pages
        //    (3) non-aligned end.
-       
+
        // Handle special case - all one page.
        if (page_cur == page_end) {
                LOG_DEBUG("Special case, all in one page");
                r = sam3_page_read(pPrivate, page_cur, pagebuffer);
                if (r != ERROR_OK) {
-                       return r;
+                       goto done;
                }
-               
+
                page_offset = (offset & (pPrivate->page_size-1));
                memcpy(pagebuffer + page_offset,
                                buffer,
                                count);
-               
+
                r = sam3_page_write(pPrivate, page_cur, pagebuffer);
                if (r != ERROR_OK) {
-                       return r;
+                       goto done;
                }
-               return ERROR_OK;
+               r = ERROR_OK;
+               goto done;
        }
 
        // non-aligned start
@@ -2162,7 +2196,7 @@ sam3_write(struct flash_bank_s *bank,
                // read the partial
                r = sam3_page_read(pPrivate, page_cur, pagebuffer);
                if (r != ERROR_OK) {
-                       return r;
+                       goto done;
                }
 
                // over-write with new data
@@ -2170,10 +2204,10 @@ sam3_write(struct flash_bank_s *bank,
                memcpy(pagebuffer + page_offset,
                                buffer,
                                n);
-       
+
                r = sam3_page_write(pPrivate, page_cur, pagebuffer);
                if (r != ERROR_OK) {
-                       return r;
+                       goto done;
                }
 
                count  -= n;
@@ -2183,16 +2217,16 @@ sam3_write(struct flash_bank_s *bank,
        }
 
        // intermediate large pages
-       // also - the final *terminal* 
+       // also - the final *terminal*
        // if that terminal page is a full page
-       LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x", 
+       LOG_DEBUG("Full Page Loop: cur=%d, end=%d, count = 0x%08x",
                          (int)page_cur, (int)page_end, (unsigned int)(count));
 
-       while ((page_cur < page_end) && 
+       while ((page_cur < page_end) &&
                   (count >= pPrivate->page_size)) {
                r = sam3_page_write(pPrivate, page_cur, buffer);
                if (r != ERROR_OK) {
-                       return r;
+                       goto done;
                }
                count    -= pPrivate->page_size;
                buffer   += pPrivate->page_size;
@@ -2205,23 +2239,27 @@ sam3_write(struct flash_bank_s *bank,
                // we have a partial page
                r = sam3_page_read(pPrivate, page_cur, pagebuffer);
                if (r != ERROR_OK) {
-                       return r;
+                       goto done;
                }
                // data goes at start
                memcpy(pagebuffer, buffer, count);
                r = sam3_page_write(pPrivate, page_cur, pagebuffer);
                if (r != ERROR_OK) {
-                       return r;
+                       goto done;
                }
                buffer += count;
                count  -= count;
        }
        LOG_DEBUG("Done!");
-       return ERROR_OK;
+       r = ERROR_OK;
+ done:
+       if( pagebuffer ){
+               free(pagebuffer);
+       }
+       return r;
 }
 
-static int
-sam3_handle_info_command(struct command_context_s *cmd_ctx, char *cmd, char **argv, int argc)
+COMMAND_HANDLER(sam3_handle_info_command)
 {
        struct sam3_chip *pChip;
        void *vp;
@@ -2235,13 +2273,13 @@ sam3_handle_info_command(struct command_context_s *cmd_ctx, char *cmd, char **ar
        }
 
        r = 0;
-       
+
        // bank0 must exist before we can do anything
        if (pChip->details.bank[0].pBank == NULL) {
                x = 0;
        need_define:
-               command_print(cmd_ctx, 
-                                          "Please define bank %d via command: flash bank %s ... ", 
+               command_print(cmd_ctx,
+                                          "Please define bank %d via command: flash bank %s ... ",
                                           x,
                                           at91sam3_flash.name);
                return ERROR_FAIL;
@@ -2256,8 +2294,8 @@ sam3_handle_info_command(struct command_context_s *cmd_ctx, char *cmd, char **ar
        }
        // above garentees the "chip details" structure is valid
        // and thus, bank private areas are valid
-       // and we have a SAM3 chip, what a concept! 
-               
+       // and we have a SAM3 chip, what a concept!
+
 
        // auto-probe other banks, 0 done above
     for (x = 1 ; x < SAM3_MAX_FLASH_BANKS ; x++) {
@@ -2265,7 +2303,7 @@ sam3_handle_info_command(struct command_context_s *cmd_ctx, char *cmd, char **ar
                if (!(pChip->details.bank[x].present)) {
                        continue;
                }
-               
+
                if (pChip->details.bank[x].pBank == NULL) {
                        goto need_define;
                }
@@ -2273,20 +2311,20 @@ sam3_handle_info_command(struct command_context_s *cmd_ctx, char *cmd, char **ar
                if (pChip->details.bank[x].probed) {
                        continue;
                }
-               
+
                r = sam3_auto_probe(pChip->details.bank[x].pBank);
                if (r != ERROR_OK) {
                        return r;
                }
        }
-                       
+
 
        r = sam3_GetInfo(pChip);
        if (r != ERROR_OK) {
                LOG_DEBUG("Sam3Info, Failed %d\n",r);
                return r;
        }
-       
+
 
        // print results
        cp = membuf_strtok(pChip->mbuf, "\n", &vp);
@@ -2297,11 +2335,9 @@ sam3_handle_info_command(struct command_context_s *cmd_ctx, char *cmd, char **ar
        return ERROR_OK;
 }
 
-static int
-sam3_handle_gpnvm_command(struct command_context_s *cmd_ctx, char *cmd, char **argv, int argc)
+COMMAND_HANDLER(sam3_handle_gpnvm_command)
 {
        unsigned x,v;
-       uint32_t v32;
        int r,who;
        struct sam3_chip *pChip;
 
@@ -2342,22 +2378,20 @@ sam3_handle_gpnvm_command(struct command_context_s *cmd_ctx, char *cmd, char **a
                who = -1;
                break;
        case 2:
-               if ((0 == strcmp(argv[0], "show")) && (0 == strcmp(argv[1], "all"))) {
+               if ((0 == strcmp(args[0], "show")) && (0 == strcmp(args[1], "all"))) {
                        who = -1;
                } else {
-                       r = parse_u32(argv[1], &v32);
-                       if (r != ERROR_OK) {
-                               command_print(cmd_ctx, "Not a number: %s", argv[1]);
-                               return r;
-                       }
+                       uint32_t v32;
+                       COMMAND_PARSE_NUMBER(u32, args[1], v32);
                        who = v32;
                }
                break;
        }
 
-       if (0 == strcmp("show", argv[0])) {
+       if (0 == strcmp("show", args[0])) {
                if (who == -1) {
                showall:
+                       r = ERROR_OK;
                        for (x = 0 ; x < pChip->details.n_gpnvms ; x++) {
                                r = FLASHD_GetGPNVM(&(pChip->details.bank[0]), x, &v);
                                if (r != ERROR_OK) {
@@ -2381,25 +2415,21 @@ sam3_handle_gpnvm_command(struct command_context_s *cmd_ctx, char *cmd, char **a
                command_print(cmd_ctx, "Missing GPNVM number");
                return ERROR_COMMAND_SYNTAX_ERROR;
        }
-       
-       if (0 == strcmp("set", argv[0])) {
+
+       if (0 == strcmp("set", args[0])) {
                r = FLASHD_SetGPNVM(&(pChip->details.bank[0]), who);
-       } else if ((0 == strcmp("clr", argv[0])) ||
-                          (0 == strcmp("clear", argv[0]))) { // quietly accept both
+       } else if ((0 == strcmp("clr", args[0])) ||
+                          (0 == strcmp("clear", args[0]))) { // quietly accept both
                r = FLASHD_ClrGPNVM(&(pChip->details.bank[0]), who);
        } else {
-               command_print(cmd_ctx, "Unkown command: %s", argv[0]);
+               command_print(cmd_ctx, "Unkown command: %s", args[0]);
                r = ERROR_COMMAND_SYNTAX_ERROR;
        }
        return r;
 }
 
-static int 
-sam3_handle_slowclk_command(struct command_context_s *cmd_ctx, char *cmd, char **argv, int argc)
+COMMAND_HANDLER(sam3_handle_slowclk_command)
 {
-       uint32_t v;
-       int r;
-
        struct sam3_chip *pChip;
 
        pChip = get_current_sam3(cmd_ctx);
@@ -2413,8 +2443,10 @@ sam3_handle_slowclk_command(struct command_context_s *cmd_ctx, char *cmd, char *
                // show
                break;
        case 1:
+       {
                // set
-               r = parse_u32(argv[0], &v);
+               uint32_t v;
+               COMMAND_PARSE_NUMBER(u32, args[0], v);
                if (v > 200000) {
                        // absurd slow clock of 200Khz?
                        command_print(cmd_ctx,"Absurd/illegal slow clock freq: %d\n", (int)(v));
@@ -2422,14 +2454,14 @@ sam3_handle_slowclk_command(struct command_context_s *cmd_ctx, char *cmd, char *
                }
                pChip->cfg.slow_freq = v;
                break;
-               
+       }
        default:
                // error
                command_print(cmd_ctx,"Too many parameters");
                return ERROR_COMMAND_SYNTAX_ERROR;
                break;
        }
-       command_print(cmd_ctx, "Slowclk freq: %d.%03dkhz", 
+       command_print(cmd_ctx, "Slowclk freq: %d.%03dkhz",
                                   (int)(pChip->cfg.slow_freq/ 1000),
                                   (int)(pChip->cfg.slow_freq% 1000));
        return ERROR_OK;
@@ -2438,9 +2470,9 @@ sam3_handle_slowclk_command(struct command_context_s *cmd_ctx, char *cmd, char *
 
 static int sam3_registered;
 static int
-sam3_register_commands(struct command_context_s *cmd_ctx)
+sam3_register_commands(struct command_context *cmd_ctx)
 {
-       command_t *pCmd;
+       struct command *pCmd;
 
        // only register once
        if (!sam3_registered) {
@@ -2448,9 +2480,9 @@ sam3_register_commands(struct command_context_s *cmd_ctx)
 
                pCmd = register_command(cmd_ctx, NULL, "at91sam3", NULL, COMMAND_ANY, NULL);
                register_command(cmd_ctx, pCmd,
-                                                 "gpnvm", 
-                                                 sam3_handle_gpnvm_command, 
-                                                 COMMAND_EXEC, 
+                                                 "gpnvm",
+                                                 sam3_handle_gpnvm_command,
+                                                 COMMAND_EXEC,
                                                  "at91sam3 gpnvm [action [<BIT>], by default 'show', otherwise set | clear BIT");
                register_command(cmd_ctx, pCmd,
                                                  "info",
@@ -2466,29 +2498,16 @@ sam3_register_commands(struct command_context_s *cmd_ctx)
        return ERROR_OK;
 }
 
-
-flash_driver_t at91sam3_flash =
-{
-       .name                                           = "at91sam3",
-       .register_commands                      = sam3_register_commands,
-       
-       .flash_bank_command                     = sam3_flash_bank_command,
-       .erase                                          = sam3_erase,
-       .protect                                        = sam3_protect,
-       .write                                          = sam3_write,
-       .probe                                          = sam3_probe,
-       .auto_probe                                     = sam3_auto_probe,
-       .erase_check                            = sam3_erase_check,
-       .protect_check                          = sam3_protect_check,
-       .info                                           = sam3_info
-};
-
-
-
-/**
- * Local Variables: **
- * mode: c **
- * c-basic-offset: 4 **
- * tab-width: 4 **
- * End: **
- */
+struct flash_driver at91sam3_flash = {
+               .name = "at91sam3",
+               .register_commands = &sam3_register_commands,
+               .flash_bank_command = &sam3_flash_bank_command,
+               .erase = &sam3_erase,
+               .protect = &sam3_protect,
+               .write = &sam3_write,
+               .probe = &sam3_probe,
+               .auto_probe = &sam3_auto_probe,
+               .erase_check = &sam3_erase_check,
+               .protect_check = &sam3_protect_check,
+               .info = &sam3_info,
+       };