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, see <http://www.gnu.org/licenses/>. *
17  ***************************************************************************/
18 
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22 
23 #include "imp.h"
24 
25 #include <target/cortex_m.h>
26 
27 /* At this time, the SAM4L Flash is available in these capacities:
28  * ATSAM4Lx4xx: 256KB (512 pages)
29  * ATSAM4Lx2xx: 128KB (256 pages)
30  * ATSAM4Lx8xx: 512KB (1024 pages)
31  */
32 
33 /* There are 16 lockable regions regardless of overall capacity. The number
34  * of pages per sector is therefore dependant on capacity. */
35 #define SAM4L_NUM_SECTORS 16
36 
37 /* Locations in memory map */
38 #define SAM4L_FLASH			((uint32_t)0x00000000) /* Flash region */
39 #define SAM4L_FLASH_USER	0x00800000 /* Flash user page region */
40 #define SAM4L_FLASHCALW		0x400A0000 /* Flash controller */
41 #define SAM4L_CHIPID		0x400E0740 /* Chip Identification */
42 
43 /* Offsets from SAM4L_FLASHCALW */
44 #define SAM4L_FCR			0x00 /* Flash Control Register (RW) */
45 #define SAM4L_FCMD			0x04 /* Flash Command Register (RW) */
46 #define SAM4L_FSR			0x08 /* Flash Status Register (RO) */
47 #define SAM4L_FPR			0x0C /* Flash Parameter Register (RO) */
48 #define SAM4L_FVR			0x10 /* Flash Version Register (RO) */
49 #define SAM4L_FGPFRHI		0x14 /* Flash General Purpose Register High (RO) */
50 #define SAM4L_FGPFRLO		0x18 /* Flash General Purpose Register Low (RO) */
51 
52 /* Offsets from SAM4L_CHIPID */
53 #define SAM4L_CIDR			0x00 /* Chip ID Register (RO) */
54 #define SAM4L_EXID			0x04 /* Chip ID Extension Register (RO) */
55 
56 /* Flash commands (for SAM4L_FCMD), see Table 14-5 */
57 #define SAM4L_FCMD_NOP		0	 /* No Operation */
58 #define SAM4L_FCMD_WP		1	 /* Write Page */
59 #define SAM4L_FCMD_EP		2	 /* Erase Page */
60 #define SAM4L_FCMD_CPB		3	 /* Clear Page Buffer */
61 #define SAM4L_FCMD_LP		4	 /* Lock region containing given page */
62 #define SAM4L_FCMD_UP		5	 /* Unlock region containing given page */
63 #define SAM4L_FCMD_EA		6	 /* Erase All */
64 #define SAM4L_FCMD_WGPB		7	 /* Write general-purpose fuse bit */
65 #define SAM4L_FCMD_EGPB		8	 /* Erase general-purpose fuse bit */
66 #define SAM4L_FCMD_SSB		9	 /* Set security fuses */
67 #define SAM4L_FCMD_PGPFB	10	/* Program general-purpose fuse byte */
68 #define SAM4L_FCMD_EAGPF	11	/* Erase all general-purpose fuse bits */
69 #define SAM4L_FCMD_QPR		12	/* Quick page read */
70 #define SAM4L_FCMD_WUP		13	/* Write user page */
71 #define SAM4L_FCMD_EUP		14	/* Erase user page */
72 #define SAM4L_FCMD_QPRUP	15	/* Quick page read (user page) */
73 #define SAM4L_FCMD_HSEN		16	/* High speed mode enable */
74 #define SAM4L_FCMD_HSDIS	17	/* High speed mode disable */
75 
76 #define SAM4L_FMCD_CMDKEY	0xA5UL	/* 'key' to issue commands, see 14.10.2 */
77 
78 
79 /* SMAP registers and bits */
80 #define SMAP_BASE 0x400A3000
81 
82 #define SMAP_SCR (SMAP_BASE + 8)
83 #define SMAP_SCR_HCR (1 << 1)
84 
85 
86 struct sam4l_chip_info {
87 	uint32_t id;
88 	uint32_t exid;
89 	const char *name;
90 };
91 
92 /* These are taken from Table 9-1 in 42023E-SAM-07/2013 */
93 static const struct sam4l_chip_info sam4l_known_chips[] = {
94 	{ 0xAB0B0AE0, 0x1400000F, "ATSAM4LC8C" },
95 	{ 0xAB0A09E0, 0x0400000F, "ATSAM4LC4C" },
96 	{ 0xAB0A07E0, 0x0400000F, "ATSAM4LC2C" },
97 	{ 0xAB0B0AE0, 0x1300000F, "ATSAM4LC8B" },
98 	{ 0xAB0A09E0, 0x0300000F, "ATSAM4LC4B" },
99 	{ 0xAB0A07E0, 0x0300000F, "ATSAM4LC2B" },
100 	{ 0xAB0B0AE0, 0x1200000F, "ATSAM4LC8A" },
101 	{ 0xAB0A09E0, 0x0200000F, "ATSAM4LC4A" },
102 	{ 0xAB0A07E0, 0x0200000F, "ATSAM4LC2A" },
103 	{ 0xAB0B0AE0, 0x14000002, "ATSAM4LS8C" },
104 	{ 0xAB0A09E0, 0x04000002, "ATSAM4LS4C" },
105 	{ 0xAB0A07E0, 0x04000002, "ATSAM4LS2C" },
106 	{ 0xAB0B0AE0, 0x13000002, "ATSAM4LS8B" },
107 	{ 0xAB0A09E0, 0x03000002, "ATSAM4LS4B" },
108 	{ 0xAB0A07E0, 0x03000002, "ATSAM4LS2B" },
109 	{ 0xAB0B0AE0, 0x12000002, "ATSAM4LS8A" },
110 	{ 0xAB0A09E0, 0x02000002, "ATSAM4LS4A" },
111 	{ 0xAB0A07E0, 0x02000002, "ATSAM4LS2A" },
112 };
113 
114 /* Meaning of SRAMSIZ field in CHIPID, see 9.3.1 in 42023E-SAM-07/2013 */
115 static const uint16_t sam4l_ram_sizes[16] = { 48, 1, 2, 6, 24, 4, 80, 160, 8, 16, 32, 64, 128, 256, 96, 512 };
116 
117 /* Meaning of PSZ field in FPR, see 14.10.4 in 42023E-SAM-07/2013 */
118 static const uint16_t sam4l_page_sizes[8] = { 32, 64, 128, 256, 512, 1024, 2048, 4096 };
119 
120 struct sam4l_info {
121 	const struct sam4l_chip_info *details;
122 
123 	uint32_t flash_kb;
124 	uint32_t ram_kb;
125 	uint32_t page_size;
126 	int num_pages;
127 	int sector_size;
128 	unsigned int pages_per_sector;
129 
130 	bool probed;
131 	struct target *target;
132 };
133 
134 
sam4l_flash_wait_until_ready(struct target * target)135 static int sam4l_flash_wait_until_ready(struct target *target)
136 {
137 	volatile unsigned int t = 0;
138 	uint32_t st;
139 	int res;
140 
141 	/* Poll the status register until the FRDY bit is set */
142 	do {
143 		res = target_read_u32(target, SAM4L_FLASHCALW + SAM4L_FSR, &st);
144 	} while (res == ERROR_OK && !(st & (1<<0)) && ++t < 10);
145 
146 	return res;
147 }
148 
sam4l_flash_check_error(struct target * target,uint32_t * err)149 static int sam4l_flash_check_error(struct target *target, uint32_t *err)
150 {
151 	uint32_t st;
152 	int res;
153 
154 	res = target_read_u32(target, SAM4L_FLASHCALW + SAM4L_FSR, &st);
155 
156 	if (res == ERROR_OK)
157 		*err = st & ((1<<3) | (1<<2)); /* grab PROGE and LOCKE bits */
158 
159 	return res;
160 }
161 
sam4l_flash_command(struct target * target,uint8_t cmd,int page)162 static int sam4l_flash_command(struct target *target, uint8_t cmd, int page)
163 {
164 	int res;
165 	uint32_t fcmd;
166 	uint32_t err;
167 
168 	res = sam4l_flash_wait_until_ready(target);
169 	if (res != ERROR_OK)
170 		return res;
171 
172 	if (page >= 0) {
173 		/* Set the page number. For some commands, the page number is just an
174 		 * argument (ex: fuse bit number). */
175 		fcmd = (SAM4L_FMCD_CMDKEY << 24) | ((page & 0xFFFF) << 8) | (cmd & 0x3F);
176 	} else {
177 		/* Reuse the page number that was read from the flash command register. */
178 		res = target_read_u32(target, SAM4L_FLASHCALW + SAM4L_FCMD, &fcmd);
179 		if (res != ERROR_OK)
180 			return res;
181 
182 		fcmd &= ~0x3F; /* clear out the command code */
183 		fcmd |= (SAM4L_FMCD_CMDKEY << 24) | (cmd & 0x3F);
184 	}
185 
186 	/* Send the command */
187 	res = target_write_u32(target, SAM4L_FLASHCALW + SAM4L_FCMD, fcmd);
188 	if (res != ERROR_OK)
189 		return res;
190 
191 	res = sam4l_flash_check_error(target, &err);
192 	if (res != ERROR_OK)
193 		return res;
194 
195 	if (err != 0)
196 		LOG_ERROR("%s got error status 0x%08" PRIx32, __func__, err);
197 
198 	res = sam4l_flash_wait_until_ready(target);
199 
200 	return res;
201 }
202 
FLASH_BANK_COMMAND_HANDLER(sam4l_flash_bank_command)203 FLASH_BANK_COMMAND_HANDLER(sam4l_flash_bank_command)
204 {
205 	if (bank->base != SAM4L_FLASH) {
206 		LOG_ERROR("Address " TARGET_ADDR_FMT
207 				" invalid bank address (try 0x%08" PRIx32
208 				"[at91sam4l series] )",
209 				bank->base, SAM4L_FLASH);
210 		return ERROR_FAIL;
211 	}
212 
213 	struct sam4l_info *chip;
214 	chip = calloc(1, sizeof(*chip));
215 	if (!chip) {
216 		LOG_ERROR("No memory for flash bank chip info");
217 		return ERROR_FAIL;
218 	}
219 
220 	chip->target = bank->target;
221 	chip->probed = false;
222 
223 	bank->driver_priv = chip;
224 
225 	return ERROR_OK;
226 }
227 
sam4l_find_chip_name(uint32_t id,uint32_t exid)228 static const struct sam4l_chip_info *sam4l_find_chip_name(uint32_t id, uint32_t exid)
229 {
230 	unsigned int i;
231 
232 	id &= ~0xF;
233 
234 	for (i = 0; i < ARRAY_SIZE(sam4l_known_chips); i++) {
235 		if (sam4l_known_chips[i].id == id && sam4l_known_chips[i].exid == exid)
236 			return &sam4l_known_chips[i];
237 	}
238 
239 	return NULL;
240 }
241 
sam4l_check_page_erased(struct flash_bank * bank,uint32_t pn,bool * is_erased_p)242 static int sam4l_check_page_erased(struct flash_bank *bank, uint32_t pn,
243 		bool *is_erased_p)
244 {
245 	int res;
246 	uint32_t st;
247 
248 	/* Issue a quick page read to verify that we've erased this page */
249 	res = sam4l_flash_command(bank->target, SAM4L_FCMD_QPR, pn);
250 	if (res != ERROR_OK) {
251 		LOG_ERROR("Quick page read %" PRIu32 " failed", pn);
252 		return res;
253 	}
254 
255 	/* Retrieve the flash status */
256 	res = target_read_u32(bank->target, SAM4L_FLASHCALW + SAM4L_FSR, &st);
257 	if (res != ERROR_OK) {
258 		LOG_ERROR("Couldn't read erase status");
259 		return res;
260 	}
261 
262 	/* Is the page in question really erased? */
263 	*is_erased_p = !!(st & (1<<5));
264 
265 	return ERROR_OK;
266 }
267 
sam4l_probe(struct flash_bank * bank)268 static int sam4l_probe(struct flash_bank *bank)
269 {
270 	uint32_t id, exid, param;
271 	int res;
272 	struct sam4l_info *chip = (struct sam4l_info *)bank->driver_priv;
273 
274 	if (chip->probed)
275 		return ERROR_OK;
276 
277 	res = target_read_u32(bank->target, SAM4L_CHIPID + SAM4L_CIDR, &id);
278 	if (res != ERROR_OK) {
279 		LOG_ERROR("Couldn't read chip ID");
280 		return res;
281 	}
282 
283 	res = target_read_u32(bank->target, SAM4L_CHIPID + SAM4L_EXID, &exid);
284 	if (res != ERROR_OK) {
285 		LOG_ERROR("Couldn't read extended chip ID");
286 		return res;
287 	}
288 
289 	chip->details = sam4l_find_chip_name(id, exid);
290 
291 	/* The RAM capacity is in a lookup table. */
292 	chip->ram_kb = sam4l_ram_sizes[0xF & (id >> 16)];
293 
294 	switch (0xF & (id >> 8)) {
295 		case 0x07:
296 			chip->flash_kb = 128;
297 			break;
298 		case 0x09:
299 			chip->flash_kb = 256;
300 			break;
301 		case 0x0A:
302 			chip->flash_kb = 512;
303 			break;
304 		default:
305 			LOG_ERROR("Unknown flash size (chip ID is %08" PRIx32 "), assuming 128K", id);
306 			chip->flash_kb = 128;
307 			break;
308 	}
309 
310 	/* Retrieve the Flash parameters */
311 	res = target_read_u32(bank->target, SAM4L_FLASHCALW + SAM4L_FPR, &param);
312 	if (res != ERROR_OK) {
313 		LOG_ERROR("Couldn't read Flash parameters");
314 		return res;
315 	}
316 
317 	/* Fetch the page size from the parameter register.	Technically the flash
318 	 * capacity is there too though the manual mentions that not all parts will
319 	 * have it set so we use the Chip ID capacity information instead. */
320 	chip->page_size = sam4l_page_sizes[0x7 & (param >> 8)];
321 	assert(chip->page_size);
322 	chip->num_pages = chip->flash_kb * 1024 / chip->page_size;
323 
324 	chip->sector_size = (chip->flash_kb * 1024) / SAM4L_NUM_SECTORS;
325 	chip->pages_per_sector = chip->sector_size / chip->page_size;
326 
327 	/* Make sure the bank size is correct */
328 	bank->size = chip->flash_kb * 1024;
329 
330 	/* Allocate the sector table. */
331 	bank->num_sectors = SAM4L_NUM_SECTORS;
332 	bank->sectors = calloc(bank->num_sectors, (sizeof((bank->sectors)[0])));
333 	if (!bank->sectors)
334 		return ERROR_FAIL;
335 
336 	/* Fill out the sector information: all SAM4L sectors are the same size and
337 	 * there is always a fixed number of them. */
338 	for (unsigned int i = 0; i < bank->num_sectors; i++) {
339 		bank->sectors[i].size = chip->sector_size;
340 		bank->sectors[i].offset = i * chip->sector_size;
341 		/* mark as unknown */
342 		bank->sectors[i].is_erased = -1;
343 		bank->sectors[i].is_protected = -1;
344 	}
345 
346 	/* Done */
347 	chip->probed = true;
348 
349 	LOG_INFO("SAM4L MCU: %s (Rev %c) (%" PRIu32 "KB Flash with %d %" PRIu32 "B pages, %" PRIu32 "KB RAM)",
350 			chip->details ? chip->details->name : "unknown", (char)('A' + (id & 0xF)),
351 			chip->flash_kb, chip->num_pages, chip->page_size, chip->ram_kb);
352 
353 	return ERROR_OK;
354 }
355 
sam4l_protect_check(struct flash_bank * bank)356 static int sam4l_protect_check(struct flash_bank *bank)
357 {
358 	int res;
359 	uint32_t st;
360 	struct sam4l_info *chip = (struct sam4l_info *)bank->driver_priv;
361 
362 	if (bank->target->state != TARGET_HALTED) {
363 		LOG_ERROR("Target not halted");
364 
365 		return ERROR_TARGET_NOT_HALTED;
366 	}
367 
368 	if (!chip->probed) {
369 		if (sam4l_probe(bank) != ERROR_OK)
370 			return ERROR_FLASH_BANK_NOT_PROBED;
371 	}
372 
373 	res = target_read_u32(bank->target, SAM4L_FLASHCALW + SAM4L_FSR, &st);
374 	if (res != ERROR_OK)
375 		return res;
376 
377 	st >>= 16; /* There are 16 lock region bits in the upper half word */
378 	for (unsigned int i = 0; i < bank->num_sectors; i++)
379 		bank->sectors[i].is_protected = !!(st & (1<<i));
380 
381 	return ERROR_OK;
382 }
383 
sam4l_protect(struct flash_bank * bank,int set,unsigned int first,unsigned int last)384 static int sam4l_protect(struct flash_bank *bank, int set, unsigned int first,
385 		unsigned int last)
386 {
387 	struct sam4l_info *chip = (struct sam4l_info *)bank->driver_priv;
388 
389 	if (bank->target->state != TARGET_HALTED) {
390 		LOG_ERROR("Target not halted");
391 
392 		return ERROR_TARGET_NOT_HALTED;
393 	}
394 
395 	if (!chip->probed) {
396 		if (sam4l_probe(bank) != ERROR_OK)
397 			return ERROR_FLASH_BANK_NOT_PROBED;
398 	}
399 
400 	/* Make sure the pages make sense. */
401 	if (first >= bank->num_sectors || last >= bank->num_sectors) {
402 		LOG_ERROR("Protect range %u - %u not valid (%u sectors total)", first, last,
403 				bank->num_sectors);
404 		return ERROR_FAIL;
405 	}
406 
407 	/* Try to lock or unlock each sector in the range.	This is done by locking
408 	 * a region containing one page in that sector, we arbitrarily choose the 0th
409 	 * page in the sector. */
410 	for (unsigned int i = first; i <= last; i++) {
411 		int res;
412 
413 		res = sam4l_flash_command(bank->target,
414 				set ? SAM4L_FCMD_LP : SAM4L_FCMD_UP, i * chip->pages_per_sector);
415 		if (res != ERROR_OK) {
416 			LOG_ERROR("Can't %slock region containing page %d", set ? "" : "un", i);
417 			return res;
418 		}
419 	}
420 
421 	return ERROR_OK;
422 }
423 
sam4l_erase(struct flash_bank * bank,unsigned int first,unsigned int last)424 static int sam4l_erase(struct flash_bank *bank, unsigned int first,
425 		unsigned int last)
426 {
427 	int ret;
428 	struct sam4l_info *chip = (struct sam4l_info *)bank->driver_priv;
429 
430 	if (bank->target->state != TARGET_HALTED) {
431 		LOG_ERROR("Target not halted");
432 
433 		return ERROR_TARGET_NOT_HALTED;
434 	}
435 
436 	if (!chip->probed) {
437 		if (sam4l_probe(bank) != ERROR_OK)
438 			return ERROR_FLASH_BANK_NOT_PROBED;
439 	}
440 
441 	/* Make sure the pages make sense. */
442 	if (first >= bank->num_sectors || last >= bank->num_sectors) {
443 		LOG_ERROR("Erase range %u - %u not valid (%u sectors total)", first, last,
444 				bank->num_sectors);
445 		return ERROR_FAIL;
446 	}
447 
448 	/* Erase */
449 	if ((first == 0) && ((last + 1) == bank->num_sectors)) {
450 		LOG_DEBUG("Erasing the whole chip");
451 
452 		ret = sam4l_flash_command(bank->target, SAM4L_FCMD_EA, -1);
453 		if (ret != ERROR_OK) {
454 			LOG_ERROR("Erase All failed");
455 			return ret;
456 		}
457 	} else {
458 		LOG_DEBUG("Erasing sectors %u through %u...\n", first, last);
459 
460 		/* For each sector... */
461 		for (unsigned int i = first; i <= last; i++) {
462 			/* For each page in that sector... */
463 			for (unsigned int j = 0; j < chip->pages_per_sector; j++) {
464 				unsigned int pn = i * chip->pages_per_sector + j;
465 				bool is_erased = false;
466 
467 				/* Issue the page erase */
468 				ret = sam4l_flash_command(bank->target, SAM4L_FCMD_EP, pn);
469 				if (ret != ERROR_OK) {
470 					LOG_ERROR("Erasing page %u failed", pn);
471 					return ret;
472 				}
473 
474 				ret = sam4l_check_page_erased(bank, pn, &is_erased);
475 				if (ret != ERROR_OK)
476 					return ret;
477 
478 				if (!is_erased) {
479 					LOG_DEBUG("Page %u was not erased.", pn);
480 					return ERROR_FAIL;
481 				}
482 			}
483 
484 			/* This sector is definitely erased. */
485 			bank->sectors[i].is_erased = 1;
486 		}
487 	}
488 
489 	return ERROR_OK;
490 }
491 
492 /* Write an entire page from host buffer 'buf' to page-aligned 'address' in the
493  * Flash. */
sam4l_write_page(struct sam4l_info * chip,struct target * target,uint32_t address,const uint8_t * buf)494 static int sam4l_write_page(struct sam4l_info *chip, struct target *target,
495 		uint32_t address, const uint8_t *buf)
496 {
497 	int res;
498 
499 	LOG_DEBUG("sam4l_write_page address=%08" PRIx32, address);
500 
501 	/* Clear the page buffer before we write to it */
502 	res = sam4l_flash_command(target, SAM4L_FCMD_CPB, -1);
503 	if (res != ERROR_OK) {
504 		LOG_ERROR("%s: can't clear page buffer", __func__);
505 		return res;
506 	}
507 
508 	/* Write the modified page back to the target's page buffer */
509 	res = target_write_memory(target, address, 4, chip->page_size / 4, buf);
510 
511 	if (res != ERROR_OK) {
512 		LOG_ERROR("%s: %d", __func__, __LINE__);
513 		return res;
514 	}
515 
516 	/* Commit the page contents to Flash: erase the current page and then
517 	 * write it out. */
518 	res = sam4l_flash_command(target, SAM4L_FCMD_EP, -1);
519 	if (res != ERROR_OK)
520 		return res;
521 	res = sam4l_flash_command(target, SAM4L_FCMD_WP, -1);
522 
523 	return res;
524 }
525 
526 /* Write partial contents into page-aligned 'address' on the Flash from host
527  * buffer 'buf' by writing 'nb' of 'buf' at 'offset' into the Flash page. */
sam4l_write_page_partial(struct sam4l_info * chip,struct flash_bank * bank,uint32_t address,const uint8_t * buf,uint32_t page_offset,uint32_t nb)528 static int sam4l_write_page_partial(struct sam4l_info *chip,
529 		struct flash_bank *bank, uint32_t address, const uint8_t *buf,
530 		uint32_t page_offset, uint32_t nb)
531 {
532 	int res;
533 	uint8_t *pg = malloc(chip->page_size);
534 	if (!pg)
535 		return ERROR_FAIL;
536 
537 	LOG_DEBUG("sam4l_write_page_partial address=%08" PRIx32 " nb=%08" PRIx32, address, nb);
538 
539 	assert(page_offset + nb < chip->page_size);
540 	assert((address % chip->page_size) == 0);
541 
542 	/* Retrieve the full page contents from Flash */
543 	res = target_read_memory(bank->target, address, 4,
544 			chip->page_size / 4, pg);
545 	if (res != ERROR_OK) {
546 		free(pg);
547 		return res;
548 	}
549 
550 	/* Insert our partial page over the data from Flash */
551 	memcpy(pg + (page_offset % chip->page_size), buf, nb);
552 
553 	/* Write the page back out */
554 	res = sam4l_write_page(chip, bank->target, address, pg);
555 	free(pg);
556 
557 	return res;
558 }
559 
sam4l_write(struct flash_bank * bank,const uint8_t * buffer,uint32_t offset,uint32_t count)560 static int sam4l_write(struct flash_bank *bank, const uint8_t *buffer,
561 		uint32_t offset, uint32_t count)
562 {
563 	int res;
564 	uint32_t nb = 0;
565 	struct sam4l_info *chip = (struct sam4l_info *)bank->driver_priv;
566 
567 	LOG_DEBUG("sam4l_write offset=%08" PRIx32 " count=%08" PRIx32, offset, count);
568 
569 	if (bank->target->state != TARGET_HALTED) {
570 		LOG_ERROR("Target not halted");
571 
572 		return ERROR_TARGET_NOT_HALTED;
573 	}
574 
575 	if (!chip->probed) {
576 		if (sam4l_probe(bank) != ERROR_OK)
577 			return ERROR_FLASH_BANK_NOT_PROBED;
578 	}
579 
580 	if (offset % chip->page_size) {
581 		/* We're starting at an unaligned offset so we'll write a partial page
582 		 * comprising that offset and up to the end of that page. */
583 		nb = chip->page_size - (offset % chip->page_size);
584 		if (nb > count)
585 			nb = count;
586 	} else if (count < chip->page_size) {
587 		/* We're writing an aligned but partial page. */
588 		nb = count;
589 	}
590 
591 	if (nb > 0) {
592 		res = sam4l_write_page_partial(chip, bank,
593 				(offset / chip->page_size) * chip->page_size + bank->base,
594 				buffer,
595 				offset % chip->page_size, nb);
596 		if (res != ERROR_OK)
597 			return res;
598 
599 		/* We're done with the page contents */
600 		count -= nb;
601 		offset += nb;
602 	}
603 
604 	/* There's at least one aligned page to write out. */
605 	if (count >= chip->page_size) {
606 		assert(chip->page_size > 0);
607 		int np = count / chip->page_size + ((count % chip->page_size) ? 1 : 0);
608 
609 		for (int i = 0; i < np; i++) {
610 			if (count >= chip->page_size) {
611 				res = sam4l_write_page(chip, bank->target,
612 						bank->base + offset,
613 						buffer + (i * chip->page_size));
614 				/* Advance one page */
615 				offset += chip->page_size;
616 				count -= chip->page_size;
617 			} else {
618 				res = sam4l_write_page_partial(chip, bank,
619 						bank->base + offset,
620 						buffer + (i * chip->page_size), 0, count);
621 				/* We're done after this. */
622 				offset += count;
623 				count = 0;
624 			}
625 
626 			if (res != ERROR_OK)
627 				return res;
628 		}
629 	}
630 
631 	return ERROR_OK;
632 }
633 
634 
COMMAND_HANDLER(sam4l_handle_reset_deassert)635 COMMAND_HANDLER(sam4l_handle_reset_deassert)
636 {
637 	struct target *target = get_current_target(CMD_CTX);
638 	int retval = ERROR_OK;
639 	enum reset_types jtag_reset_config = jtag_get_reset_config();
640 
641 	/* If the target has been unresponsive before, try to re-establish
642 	 * communication now - CPU is held in reset by DSU, DAP is working */
643 	if (!target_was_examined(target))
644 		target_examine_one(target);
645 	target_poll(target);
646 
647 	/* In case of sysresetreq, debug retains state set in cortex_m_assert_reset()
648 	 * so we just release reset held by SMAP
649 	 *
650 	 * n_RESET (srst) clears the DP, so reenable debug and set vector catch here
651 	 *
652 	 * After vectreset SMAP release is not needed however makes no harm
653 	 */
654 	if (target->reset_halt && (jtag_reset_config & RESET_HAS_SRST)) {
655 		retval = target_write_u32(target, DCB_DHCSR, DBGKEY | C_HALT | C_DEBUGEN);
656 		if (retval == ERROR_OK)
657 			retval = target_write_u32(target, DCB_DEMCR,
658 				TRCENA | VC_HARDERR | VC_BUSERR | VC_CORERESET);
659 		/* do not return on error here, releasing SMAP reset is more important */
660 	}
661 
662 	int retval2 = target_write_u32(target, SMAP_SCR, SMAP_SCR_HCR);
663 	if (retval2 != ERROR_OK)
664 		return retval2;
665 
666 	return retval;
667 }
668 
669 static const struct command_registration at91sam4l_exec_command_handlers[] = {
670 	{
671 		.name = "smap_reset_deassert",
672 		.handler = sam4l_handle_reset_deassert,
673 		.mode = COMMAND_EXEC,
674 		.help = "deassert internal reset held by SMAP",
675 		.usage = "",
676 	},
677 	COMMAND_REGISTRATION_DONE
678 };
679 
680 static const struct command_registration at91sam4l_command_handlers[] = {
681 	{
682 		.name = "at91sam4l",
683 		.mode = COMMAND_ANY,
684 		.help = "at91sam4l flash command group",
685 		.usage = "",
686 		.chain = at91sam4l_exec_command_handlers,
687 	},
688 	COMMAND_REGISTRATION_DONE
689 };
690 
691 const struct flash_driver at91sam4l_flash = {
692 	.name = "at91sam4l",
693 	.commands = at91sam4l_command_handlers,
694 	.flash_bank_command = sam4l_flash_bank_command,
695 	.erase = sam4l_erase,
696 	.protect = sam4l_protect,
697 	.write = sam4l_write,
698 	.read = default_flash_read,
699 	.probe = sam4l_probe,
700 	.auto_probe = sam4l_probe,
701 	.erase_check = default_flash_blank_check,
702 	.protect_check = sam4l_protect_check,
703 	.free_driver_priv = default_flash_free_driver_priv,
704 };
705