at91samd: add erase/secure commands, minor fix
[fw/openocd] / src / flash / nor / at91samd.c
1 /***************************************************************************
2  *   Copyright (C) 2013 by Andrey Yurovsky                                 *
3  *   Andrey Yurovsky <yurovsky@gmail.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  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
19  ***************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include "imp.h"
26
27 #define SAMD_NUM_SECTORS        16
28
29 #define SAMD_FLASH                      ((uint32_t)0x00000000)  /* physical Flash memory */
30 #define SAMD_PAC1                       0x41000000      /* Peripheral Access Control 1 */
31 #define SAMD_DSU                        0x41002000      /* Device Service Unit */
32 #define SAMD_NVMCTRL            0x41004000      /* Non-volatile memory controller */
33
34 #define SAMD_DSU_DID            0x18            /* Device ID register */
35
36 #define SAMD_NVMCTRL_CTRLA              0x00    /* NVM control A register */
37 #define SAMD_NVMCTRL_CTRLB              0x04    /* NVM control B register */
38 #define SAMD_NVMCTRL_PARAM              0x08    /* NVM parameters register */
39 #define SAMD_NVMCTRL_INTFLAG    0x18    /* NVM Interupt Flag Status & Clear */
40 #define SAMD_NVMCTRL_STATUS             0x18    /* NVM status register */
41 #define SAMD_NVMCTRL_ADDR               0x1C    /* NVM address register */
42 #define SAMD_NVMCTRL_LOCK               0x20    /* NVM Lock section register */
43
44 #define SAMD_CMDEX_KEY          0xA5UL
45 #define SAMD_NVM_CMD(n)         ((SAMD_CMDEX_KEY << 8) | (n & 0x7F))
46
47 /* NVMCTRL commands.  See Table 20-4 in 42129F–SAM–10/2013 */
48 #define SAMD_NVM_CMD_ER         0x02            /* Erase Row */
49 #define SAMD_NVM_CMD_WP         0x04            /* Write Page */
50 #define SAMD_NVM_CMD_EAR        0x05            /* Erase Auxilary Row */
51 #define SAMD_NVM_CMD_WAP        0x06            /* Write Auxilary Page */
52 #define SAMD_NVM_CMD_LR         0x40            /* Lock Region */
53 #define SAMD_NVM_CMD_UR         0x41            /* Unlock Region */
54 #define SAMD_NVM_CMD_SPRM       0x42            /* Set Power Reduction Mode */
55 #define SAMD_NVM_CMD_CPRM       0x43            /* Clear Power Reduction Mode */
56 #define SAMD_NVM_CMD_PBC        0x44            /* Page Buffer Clear */
57 #define SAMD_NVM_CMD_SSB        0x45            /* Set Security Bit */
58 #define SAMD_NVM_CMD_INVALL     0x46            /* Invalidate all caches */
59
60 /* Known identifiers */
61 #define SAMD_PROCESSOR_M0       0x01
62 #define SAMD_FAMILY_D           0x00
63 #define SAMD_SERIES_20          0x00
64 #define SAMD_SERIES_21          0x01
65 #define SAMD_SERIES_10          0x02
66 #define SAMD_SERIES_11          0x03
67
68 struct samd_part {
69         uint8_t id;
70         const char *name;
71         uint32_t flash_kb;
72         uint32_t ram_kb;
73 };
74
75 /* Known SAMD10 parts */
76 static const struct samd_part samd10_parts[] = {
77         { 0x0, "SAMD10D14AMU", 16, 4 },
78         { 0x1, "SAMD10D13AMU", 8, 4 },
79         { 0x2, "SAMD10D12AMU", 4, 4 },
80         { 0x3, "SAMD10D14ASU", 16, 4 },
81         { 0x4, "SAMD10D13ASU", 8, 4 },
82         { 0x5, "SAMD10D12ASU", 4, 4 },
83         { 0x6, "SAMD10C14A", 16, 4 },
84         { 0x7, "SAMD10C13A", 8, 4 },
85         { 0x8, "SAMD10C12A", 4, 4 },
86 };
87
88 /* Known SAMD11 parts */
89 static const struct samd_part samd11_parts[] = {
90         { 0x0, "SAMD11D14AMU", 16, 4 },
91         { 0x1, "SAMD11D13AMU", 8, 4 },
92         { 0x2, "SAMD11D12AMU", 4, 4 },
93         { 0x3, "SAMD11D14ASU", 16, 4 },
94         { 0x4, "SAMD11D13ASU", 8, 4 },
95         { 0x5, "SAMD11D12ASU", 4, 4 },
96         { 0x6, "SAMD11C14A", 16, 4 },
97         { 0x7, "SAMD11C13A", 8, 4 },
98         { 0x8, "SAMD11C12A", 4, 4 },
99 };
100
101 /* Known SAMD20 parts. See Table 12-8 in 42129F–SAM–10/2013 */
102 static const struct samd_part samd20_parts[] = {
103         { 0x0, "SAMD20J18A", 256, 32 },
104         { 0x1, "SAMD20J17A", 128, 16 },
105         { 0x2, "SAMD20J16A", 64, 8 },
106         { 0x3, "SAMD20J15A", 32, 4 },
107         { 0x4, "SAMD20J14A", 16, 2 },
108         { 0x5, "SAMD20G18A", 256, 32 },
109         { 0x6, "SAMD20G17A", 128, 16 },
110         { 0x7, "SAMD20G16A", 64, 8 },
111         { 0x8, "SAMD20G15A", 32, 4 },
112         { 0x9, "SAMD20G14A", 16, 2 },
113         { 0xA, "SAMD20E18A", 256, 32 },
114         { 0xB, "SAMD20E17A", 128, 16 },
115         { 0xC, "SAMD20E16A", 64, 8 },
116         { 0xD, "SAMD20E15A", 32, 4 },
117         { 0xE, "SAMD20E14A", 16, 2 },
118 };
119
120 /* Known SAMD21 parts. */
121 static const struct samd_part samd21_parts[] = {
122         { 0x0, "SAMD21J18A", 256, 32 },
123         { 0x1, "SAMD21J17A", 128, 16 },
124         { 0x2, "SAMD21J16A", 64, 8 },
125         { 0x3, "SAMD21J15A", 32, 4 },
126         { 0x4, "SAMD21J14A", 16, 2 },
127         { 0x5, "SAMD21G18A", 256, 32 },
128         { 0x6, "SAMD21G17A", 128, 16 },
129         { 0x7, "SAMD21G16A", 64, 8 },
130         { 0x8, "SAMD21G15A", 32, 4 },
131         { 0x9, "SAMD21G14A", 16, 2 },
132         { 0xA, "SAMD21E18A", 256, 32 },
133         { 0xB, "SAMD21E17A", 128, 16 },
134         { 0xC, "SAMD21E16A", 64, 8 },
135         { 0xD, "SAMD21E15A", 32, 4 },
136         { 0xE, "SAMD21E14A", 16, 2 },
137 };
138
139 /* Known SAMR21 parts. */
140 static const struct samd_part samr21_parts[] = {
141         { 0x19, "SAMR21G18A", 256, 32 },
142         { 0x1A, "SAMR21G17A", 128, 32 },
143         { 0x1B, "SAMR21G16A",  64, 32 },
144         { 0x1C, "SAMR21E18A", 256, 32 },
145         { 0x1D, "SAMR21E17A", 128, 32 },
146         { 0x1E, "SAMR21E16A",  64, 32 },
147 };
148
149
150 /* Each family of parts contains a parts table in the DEVSEL field of DID.  The
151  * processor ID, family ID, and series ID are used to determine which exact
152  * family this is and then we can use the corresponding table. */
153 struct samd_family {
154         uint8_t processor;
155         uint8_t family;
156         uint8_t series;
157         const struct samd_part *parts;
158         size_t num_parts;
159 };
160
161 /* Known SAMD families */
162 static const struct samd_family samd_families[] = {
163         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_20,
164                 samd20_parts, ARRAY_SIZE(samd20_parts) },
165         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_21,
166                 samd21_parts, ARRAY_SIZE(samd21_parts) },
167         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_21,
168                 samr21_parts, ARRAY_SIZE(samr21_parts) },
169         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_10,
170                 samd10_parts, ARRAY_SIZE(samd10_parts) },
171         { SAMD_PROCESSOR_M0, SAMD_FAMILY_D, SAMD_SERIES_11,
172                 samd11_parts, ARRAY_SIZE(samd11_parts) },
173 };
174
175 struct samd_info {
176         uint32_t page_size;
177         int num_pages;
178         int sector_size;
179
180         bool probed;
181         struct target *target;
182         struct samd_info *next;
183 };
184
185 static struct samd_info *samd_chips;
186
187 static const struct samd_part *samd_find_part(uint32_t id)
188 {
189         uint8_t processor = (id >> 28);
190         uint8_t family = (id >> 24) & 0x0F;
191         uint8_t series = (id >> 16) & 0xFF;
192         uint8_t devsel = id & 0xFF;
193
194         for (unsigned i = 0; i < ARRAY_SIZE(samd_families); i++) {
195                 if (samd_families[i].processor == processor &&
196                         samd_families[i].series == series &&
197                         samd_families[i].family == family) {
198                         for (unsigned j = 0; j < samd_families[i].num_parts; j++) {
199                                 if (samd_families[i].parts[j].id == devsel)
200                                         return &samd_families[i].parts[j];
201                         }
202                 }
203         }
204
205         return NULL;
206 }
207
208 static int samd_protect_check(struct flash_bank *bank)
209 {
210         int res;
211         uint16_t lock;
212
213         res = target_read_u16(bank->target,
214                         SAMD_NVMCTRL + SAMD_NVMCTRL_LOCK, &lock);
215         if (res != ERROR_OK)
216                 return res;
217
218         /* Lock bits are active-low */
219         for (int i = 0; i < bank->num_sectors; i++)
220                 bank->sectors[i].is_protected = !(lock & (1<<i));
221
222         return ERROR_OK;
223 }
224
225 static int samd_probe(struct flash_bank *bank)
226 {
227         uint32_t id, param;
228         int res;
229         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
230         const struct samd_part *part;
231
232         if (chip->probed)
233                 return ERROR_OK;
234
235         res = target_read_u32(bank->target, SAMD_DSU + SAMD_DSU_DID, &id);
236         if (res != ERROR_OK) {
237                 LOG_ERROR("Couldn't read Device ID register");
238                 return res;
239         }
240
241         part = samd_find_part(id);
242         if (part == NULL) {
243                 LOG_ERROR("Couldn't find part correspoding to DID %08" PRIx32, id);
244                 return ERROR_FAIL;
245         }
246
247         res = target_read_u32(bank->target,
248                         SAMD_NVMCTRL + SAMD_NVMCTRL_PARAM, &param);
249         if (res != ERROR_OK) {
250                 LOG_ERROR("Couldn't read NVM Parameters register");
251                 return res;
252         }
253
254         bank->size = part->flash_kb * 1024;
255
256         chip->sector_size = bank->size / SAMD_NUM_SECTORS;
257
258         /* The PSZ field (bits 18:16) indicate the page size bytes as 2^(3+n) so
259          * 0 is 8KB and 7 is 1024KB. */
260         chip->page_size = (8 << ((param >> 16) & 0x7));
261         /* The NVMP field (bits 15:0) indicates the total number of pages */
262         chip->num_pages = param & 0xFFFF;
263
264         /* Sanity check: the total flash size in the DSU should match the page size
265          * multiplied by the number of pages. */
266         if (bank->size != chip->num_pages * chip->page_size) {
267                 LOG_WARNING("SAMD: bank size doesn't match NVM parameters. "
268                                 "Identified %" PRIu32 "KB Flash but NVMCTRL reports %u %" PRIu32 "B pages",
269                                 part->flash_kb, chip->num_pages, chip->page_size);
270         }
271
272         /* Allocate the sector table */
273         bank->num_sectors = SAMD_NUM_SECTORS;
274         bank->sectors = calloc(bank->num_sectors, sizeof((bank->sectors)[0]));
275         if (!bank->sectors)
276                 return ERROR_FAIL;
277
278         /* Fill out the sector information: all SAMD sectors are the same size and
279          * there is always a fixed number of them. */
280         for (int i = 0; i < bank->num_sectors; i++) {
281                 bank->sectors[i].size = chip->sector_size;
282                 bank->sectors[i].offset = i * chip->sector_size;
283                 /* mark as unknown */
284                 bank->sectors[i].is_erased = -1;
285                 bank->sectors[i].is_protected = -1;
286         }
287
288         samd_protect_check(bank);
289
290         /* Done */
291         chip->probed = true;
292
293         LOG_INFO("SAMD MCU: %s (%" PRIu32 "KB Flash, %" PRIu32 "KB RAM)", part->name,
294                         part->flash_kb, part->ram_kb);
295
296         return ERROR_OK;
297 }
298
299 static bool samd_check_error(struct target *target)
300 {
301         int ret;
302         bool error;
303         uint16_t status;
304
305         ret = target_read_u16(target,
306                         SAMD_NVMCTRL + SAMD_NVMCTRL_STATUS, &status);
307         if (ret != ERROR_OK) {
308                 LOG_ERROR("Can't read NVM status");
309                 return true;
310         }
311
312         if (status & 0x001C) {
313                 if (status & (1 << 4)) /* NVME */
314                         LOG_ERROR("SAMD: NVM Error");
315                 if (status & (1 << 3)) /* LOCKE */
316                         LOG_ERROR("SAMD: NVM lock error");
317                 if (status & (1 << 2)) /* PROGE */
318                         LOG_ERROR("SAMD: NVM programming error");
319
320                 error = true;
321         } else {
322                 error = false;
323         }
324
325         /* Clear the error conditions by writing a one to them */
326         ret = target_write_u16(target,
327                         SAMD_NVMCTRL + SAMD_NVMCTRL_STATUS, status);
328         if (ret != ERROR_OK)
329                 LOG_ERROR("Can't clear NVM error conditions");
330
331         return error;
332 }
333
334 static int samd_issue_nvmctrl_command(struct target *target, uint16_t cmd)
335 {
336         if (target->state != TARGET_HALTED) {
337                 LOG_ERROR("Target not halted");
338                 return ERROR_TARGET_NOT_HALTED;
339         }
340
341         /* Read current configuration. */
342         uint16_t tmp = 0;
343         int res = target_read_u16(target, SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLB,
344                         &tmp);
345         if (res != ERROR_OK)
346                 return res;
347
348         /* Set cache disable. */
349         res = target_write_u16(target, SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLB,
350                         tmp | (1<<18));
351         if (res != ERROR_OK)
352                 return res;
353
354         /* Issue the NVM command */
355         int res_cmd = target_write_u16(target,
356                         SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLA, SAMD_NVM_CMD(cmd));
357
358         /* Try to restore configuration, regardless of NVM command write
359          * status. */
360         res = target_write_u16(target, SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLB, tmp);
361
362         if (res_cmd != ERROR_OK)
363                 return res_cmd;
364
365         if (res != ERROR_OK)
366                 return res;
367
368         /* Check to see if the NVM command resulted in an error condition. */
369         if (samd_check_error(target))
370                 return ERROR_FAIL;
371
372         return ERROR_OK;
373 }
374
375 static int samd_protect(struct flash_bank *bank, int set, int first, int last)
376 {
377         int res;
378         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
379
380         res = ERROR_OK;
381
382         for (int s = first; s <= last; s++) {
383                 if (set != bank->sectors[s].is_protected) {
384                         /* Load an address that is within this sector (we use offset 0) */
385                         res = target_write_u32(bank->target, SAMD_NVMCTRL + SAMD_NVMCTRL_ADDR,
386                                                s * chip->sector_size);
387                         if (res != ERROR_OK)
388                                 goto exit;
389
390                         /* Tell the controller to lock that sector */
391                         res = samd_issue_nvmctrl_command(bank->target,
392                                         set ? SAMD_NVM_CMD_LR : SAMD_NVM_CMD_UR);
393                         if (res != ERROR_OK)
394                                 goto exit;
395                 }
396         }
397 exit:
398         samd_protect_check(bank);
399
400         return res;
401 }
402
403 static int samd_erase_row(struct flash_bank *bank, uint32_t address)
404 {
405         int res;
406
407         /* Set an address contained in the row to be erased */
408         res = target_write_u32(bank->target,
409                         SAMD_NVMCTRL + SAMD_NVMCTRL_ADDR, address >> 1);
410
411         /* Issue the Erase Row command to erase that row */
412         if (res == ERROR_OK)
413                 res = samd_issue_nvmctrl_command(bank->target, SAMD_NVM_CMD_ER);
414
415         if (res != ERROR_OK)  {
416                 LOG_ERROR("Failed to erase row containing %08" PRIx32, address);
417                 return ERROR_FAIL;
418         }
419
420         return ERROR_OK;
421 }
422
423 static int samd_erase(struct flash_bank *bank, int first, int last)
424 {
425         int res;
426         int rows_in_sector;
427         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
428
429         if (bank->target->state != TARGET_HALTED) {
430                 LOG_ERROR("Target not halted");
431
432                 return ERROR_TARGET_NOT_HALTED;
433         }
434
435         if (!chip->probed) {
436                 if (samd_probe(bank) != ERROR_OK)
437                         return ERROR_FLASH_BANK_NOT_PROBED;
438         }
439
440         /* The SAMD NVM has row erase granularity.  There are four pages in a row
441          * and the number of rows in a sector depends on the sector size, which in
442          * turn depends on the Flash capacity as there is a fixed number of
443          * sectors. */
444         rows_in_sector = chip->sector_size / (chip->page_size * 4);
445
446         /* For each sector to be erased */
447         for (int s = first; s <= last; s++) {
448                 if (bank->sectors[s].is_protected) {
449                         LOG_ERROR("SAMD: failed to erase sector %d. That sector is write-protected", s);
450                         return ERROR_FLASH_OPERATION_FAILED;
451                 }
452
453                 if (!bank->sectors[s].is_erased) {
454                         /* For each row in that sector */
455                         for (int r = s * rows_in_sector; r < (s + 1) * rows_in_sector; r++) {
456                                 res = samd_erase_row(bank, r * chip->page_size * 4);
457                                 if (res != ERROR_OK) {
458                                         LOG_ERROR("SAMD: failed to erase sector %d", s);
459                                         return res;
460                                 }
461                         }
462
463                         bank->sectors[s].is_erased = 1;
464                 }
465         }
466
467         return ERROR_OK;
468 }
469
470 static struct flash_sector *samd_find_sector_by_address(struct flash_bank *bank, uint32_t address)
471 {
472         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
473
474         for (int i = 0; i < bank->num_sectors; i++) {
475                 if (bank->sectors[i].offset <= address &&
476                     address < bank->sectors[i].offset + chip->sector_size)
477                         return &bank->sectors[i];
478         }
479         return NULL;
480 }
481
482 /* Write an entire row (four pages) from host buffer 'buf' to row-aligned
483  * 'address' in the Flash. */
484 static int samd_write_row(struct flash_bank *bank, uint32_t address,
485                 const uint8_t *buf)
486 {
487         int res;
488         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
489
490         struct flash_sector *sector = samd_find_sector_by_address(bank, address);
491
492         if (!sector) {
493                 LOG_ERROR("Can't find sector corresponding to address 0x%08" PRIx32, address);
494                 return ERROR_FLASH_OPERATION_FAILED;
495         }
496
497         if (sector->is_protected) {
498                 LOG_ERROR("Trying to write to a protected sector at 0x%08" PRIx32, address);
499                 return ERROR_FLASH_OPERATION_FAILED;
500         }
501
502         /* Erase the row that we'll be writing to */
503         res = samd_erase_row(bank, address);
504         if (res != ERROR_OK)
505                 return res;
506
507         /* Now write the pages in this row. */
508         for (unsigned int i = 0; i < 4; i++) {
509                 bool error;
510
511                 /* Write the page contents to the target's page buffer.  A page write
512                  * is issued automatically once the last location is written in the
513                  * page buffer (ie: a complete page has been written out). */
514                 res = target_write_memory(bank->target, address, 4,
515                                 chip->page_size / 4, buf);
516                 if (res != ERROR_OK) {
517                         LOG_ERROR("%s: %d", __func__, __LINE__);
518                         return res;
519                 }
520
521                 error = samd_check_error(bank->target);
522                 if (error)
523                         return ERROR_FAIL;
524
525                 /* Next page */
526                 address += chip->page_size;
527                 buf += chip->page_size;
528         }
529
530         sector->is_erased = 0;
531
532         return res;
533 }
534
535 /* Write partial contents into row-aligned 'address' on the Flash from host
536  * buffer 'buf' by writing 'nb' of 'buf' at 'row_offset' into the Flash row. */
537 static int samd_write_row_partial(struct flash_bank *bank, uint32_t address,
538                 const uint8_t *buf, uint32_t row_offset, uint32_t nb)
539 {
540         int res;
541         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
542         uint32_t row_size = chip->page_size * 4;
543         uint8_t *rb = malloc(row_size);
544         if (!rb)
545                 return ERROR_FAIL;
546
547         assert(row_offset + nb < row_size);
548         assert((address % row_size) == 0);
549
550         /* Retrieve the full row contents from Flash */
551         res = target_read_memory(bank->target, address, 4, row_size / 4, rb);
552         if (res != ERROR_OK) {
553                 free(rb);
554                 return res;
555         }
556
557         /* Insert our partial row over the data from Flash */
558         memcpy(rb + (row_offset % row_size), buf, nb);
559
560         /* Write the row back out */
561         res = samd_write_row(bank, address, rb);
562         free(rb);
563
564         return res;
565 }
566
567 static int samd_write(struct flash_bank *bank, const uint8_t *buffer,
568                 uint32_t offset, uint32_t count)
569 {
570         int res;
571         uint32_t address;
572         uint32_t nb = 0;
573         struct samd_info *chip = (struct samd_info *)bank->driver_priv;
574         uint32_t row_size = chip->page_size * 4;
575
576         if (bank->target->state != TARGET_HALTED) {
577                 LOG_ERROR("Target not halted");
578
579                 return ERROR_TARGET_NOT_HALTED;
580         }
581
582         if (!chip->probed) {
583                 if (samd_probe(bank) != ERROR_OK)
584                         return ERROR_FLASH_BANK_NOT_PROBED;
585         }
586
587         if (offset % row_size) {
588                 /* We're starting at an unaligned offset so we'll write a partial row
589                  * comprising that offset and up to the end of that row. */
590                 nb = row_size - (offset % row_size);
591                 if (nb > count)
592                         nb = count;
593         } else if (count < row_size) {
594                 /* We're writing an aligned but partial row. */
595                 nb = count;
596         }
597
598         address = (offset / row_size) * row_size + bank->base;
599
600         if (nb > 0) {
601                 res = samd_write_row_partial(bank, address, buffer,
602                                 offset % row_size, nb);
603                 if (res != ERROR_OK)
604                         return res;
605
606                 /* We're done with the row contents */
607                 count -= nb;
608                 offset += nb;
609                 buffer += row_size;
610         }
611
612         /* There's at least one aligned row to write out. */
613         if (count >= row_size) {
614                 int nr = count / row_size + ((count % row_size) ? 1 : 0);
615                 unsigned int r = 0;
616
617                 for (unsigned int i = address / row_size;
618                                 (i < (address / row_size) + nr) && count > 0; i++) {
619                         address = (i * row_size) + bank->base;
620
621                         if (count >= row_size) {
622                                 res = samd_write_row(bank, address, buffer + (r * row_size));
623                                 /* Advance one row */
624                                 offset += row_size;
625                                 count -= row_size;
626                         } else {
627                                 res = samd_write_row_partial(bank, address,
628                                                 buffer + (r * row_size), 0, count);
629                                 /* We're done after this. */
630                                 offset += count;
631                                 count = 0;
632                         }
633
634                         r++;
635
636                         if (res != ERROR_OK)
637                                 return res;
638                 }
639         }
640
641         return ERROR_OK;
642 }
643
644 FLASH_BANK_COMMAND_HANDLER(samd_flash_bank_command)
645 {
646         struct samd_info *chip = samd_chips;
647
648         while (chip) {
649                 if (chip->target == bank->target)
650                         break;
651                 chip = chip->next;
652         }
653
654         if (!chip) {
655                 /* Create a new chip */
656                 chip = calloc(1, sizeof(*chip));
657                 if (!chip)
658                         return ERROR_FAIL;
659
660                 chip->target = bank->target;
661                 chip->probed = false;
662
663                 bank->driver_priv = chip;
664
665                 /* Insert it into the chips list (at head) */
666                 chip->next = samd_chips;
667                 samd_chips = chip;
668         }
669
670         if (bank->base != SAMD_FLASH) {
671                 LOG_ERROR("Address 0x%08" PRIx32 " invalid bank address (try 0x%08" PRIx32
672                                 "[at91samd series] )",
673                                 bank->base, SAMD_FLASH);
674                 return ERROR_FAIL;
675         }
676
677         return ERROR_OK;
678 }
679
680 COMMAND_HANDLER(samd_handle_info_command)
681 {
682         return ERROR_OK;
683 }
684
685 COMMAND_HANDLER(samd_handle_chip_erase_command)
686 {
687         struct target *target = get_current_target(CMD_CTX);
688
689         if (target) {
690                 /* Enable access to the DSU by disabling the write protect bit */
691                 target_write_u32(target, SAMD_PAC1, (1<<1));
692                 /* Tell the DSU to perform a full chip erase.  It takes about 240ms to
693                  * perform the erase. */
694                 target_write_u8(target, SAMD_DSU, (1<<4));
695
696                 command_print(CMD_CTX, "chip erased");
697         }
698
699         return ERROR_OK;
700 }
701
702 COMMAND_HANDLER(samd_handle_set_security_command)
703 {
704         int res = ERROR_OK;
705         struct target *target = get_current_target(CMD_CTX);
706
707         if (CMD_ARGC < 1 || (CMD_ARGC >= 1 && (strcmp(CMD_ARGV[0], "enable")))) {
708                 command_print(CMD_CTX, "supply the \"enable\" argument to proceed.");
709                 return ERROR_COMMAND_SYNTAX_ERROR;
710         }
711
712         if (target) {
713                 if (target->state != TARGET_HALTED) {
714                         LOG_ERROR("Target not halted");
715                         return ERROR_TARGET_NOT_HALTED;
716                 }
717
718                 res = samd_issue_nvmctrl_command(target, SAMD_NVM_CMD_SSB);
719
720                 /* Check (and clear) error conditions */
721                 if (res == ERROR_OK)
722                         command_print(CMD_CTX, "chip secured on next power-cycle");
723                 else
724                         command_print(CMD_CTX, "failed to secure chip");
725         }
726
727         return res;
728 }
729
730 static const struct command_registration at91samd_exec_command_handlers[] = {
731         {
732                 .name = "info",
733                 .handler = samd_handle_info_command,
734                 .mode = COMMAND_EXEC,
735                 .help = "Print information about the current at91samd chip"
736                         "and its flash configuration.",
737         },
738         {
739                 .name = "chip-erase",
740                 .handler = samd_handle_chip_erase_command,
741                 .mode = COMMAND_EXEC,
742                 .help = "Erase the entire Flash by using the Chip"
743                         "Erase feature in the Device Service Unit (DSU).",
744         },
745         {
746                 .name = "set-security",
747                 .handler = samd_handle_set_security_command,
748                 .mode = COMMAND_EXEC,
749                 .help = "Secure the chip's Flash by setting the Security Bit."
750                         "This makes it impossible to read the Flash contents."
751                         "The only way to undo this is to issue the chip-erase"
752                         "command.",
753         },
754         COMMAND_REGISTRATION_DONE
755 };
756
757 static const struct command_registration at91samd_command_handlers[] = {
758         {
759                 .name = "at91samd",
760                 .mode = COMMAND_ANY,
761                 .help = "at91samd flash command group",
762                 .usage = "",
763                 .chain = at91samd_exec_command_handlers,
764         },
765         COMMAND_REGISTRATION_DONE
766 };
767
768 struct flash_driver at91samd_flash = {
769         .name = "at91samd",
770         .commands = at91samd_command_handlers,
771         .flash_bank_command = samd_flash_bank_command,
772         .erase = samd_erase,
773         .protect = samd_protect,
774         .write = samd_write,
775         .read = default_flash_read,
776         .probe = samd_probe,
777         .auto_probe = samd_probe,
778         .erase_check = default_flash_blank_check,
779         .protect_check = samd_protect_check,
780 };