]> git.sur5r.net Git - openocd/blob - src/flash/nor/xmc4xxx.c
xmc4xxx: Add XMC4700 support
[openocd] / src / flash / nor / xmc4xxx.c
1 /**************************************************************************
2 *   Copyright (C) 2015 Jeff Ciesielski <jeffciesielski@gmail.com>         *
3 *                                                                         *
4 *   This program is free software; you can redistribute it and/or modify  *
5 *   it under the terms of the GNU General Public License as published by  *
6 *   the Free Software Foundation; either version 2 of the License, or     *
7 *   (at your option) any later version.                                   *
8 *                                                                         *
9 *   This program is distributed in the hope that it will be useful,       *
10 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12 *   GNU General Public License for more details.                          *
13 *                                                                         *
14 ***************************************************************************/
15
16 #ifdef HAVE_CONFIG_H
17 #include "config.h"
18 #endif
19
20 #include "imp.h"
21 #include <helper/binarybuffer.h>
22 #include <target/algorithm.h>
23 #include <target/armv7m.h>
24
25 /* Maximum number of sectors */
26 #define MAX_XMC_SECTORS 12
27
28 /* System control unit registers */
29 #define SCU_REG_BASE 0x50004000
30
31 #define SCU_ID_CHIP 0x04
32
33 /* Base of the non-cached flash memory */
34 #define PFLASH_BASE     0x0C000000
35
36 /* User configuration block offsets */
37 #define UCB0_BASE       0x00000000
38 #define UCB1_BASE       0x00000400
39 #define UCB2_BASE       0x00000800
40
41 /* Flash register base */
42 #define FLASH_REG_BASE 0x58000000
43
44 /* PMU ID Registers */
45 #define FLASH_REG_PMU_ID        (FLASH_REG_BASE | 0x0508)
46
47 /* PMU Fields */
48 #define PMU_MOD_REV_MASK        0xFF
49 #define PMU_MOD_TYPE_MASK       0xFF00
50 #define PMU_MOD_NO_MASK         0xFFFF0000
51
52 /* Prefetch Config */
53 #define FLASH_REG_PREF_PCON     (FLASH_REG_BASE | 0x4000)
54
55 /* Prefetch Fields */
56 #define PCON_IBYP       (1 << 0)
57 #define PCON_IINV       (1 << 1)
58
59 /* Flash ID Register */
60 #define FLASH_REG_FLASH0_ID     (FLASH_REG_BASE | 0x2008)
61
62 /* Flash Status Register */
63 #define FLASH_REG_FLASH0_FSR    (FLASH_REG_BASE | 0x2010)
64
65 #define FSR_PBUSY       (0)
66 #define FSR_FABUSY      (1)
67 #define FSR_PROG        (4)
68 #define FSR_ERASE       (5)
69 #define FSR_PFPAGE      (6)
70 #define FSR_PFOPER      (8)
71 #define FSR_SQER        (10)
72 #define FSR_PROER       (11)
73 #define FSR_PFSBER      (12)
74 #define FSR_PFDBER      (14)
75 #define FSR_PROIN       (16)
76 #define FSR_RPROIN      (18)
77 #define FSR_RPRODIS     (19)
78 #define FSR_WPROIN0     (21)
79 #define FSR_WPROIN1     (22)
80 #define FSR_WPROIN2     (23)
81 #define FSR_WPRODIS0    (25)
82 #define FSR_WPRODIS1    (26)
83 #define FSR_SLM         (28)
84 #define FSR_VER         (31)
85
86 #define FSR_PBUSY_MASK          (0x01 << FSR_PBUSY)
87 #define FSR_FABUSY_MASK         (0x01 << FSR_FABUSY)
88 #define FSR_PROG_MASK           (0x01 << FSR_PROG)
89 #define FSR_ERASE_MASK          (0x01 << FSR_ERASE)
90 #define FSR_PFPAGE_MASK         (0x01 << FSR_PFPAGE)
91 #define FSR_PFOPER_MASK         (0x01 << FSR_PFOPER)
92 #define FSR_SQER_MASK           (0x01 << FSR_SQER)
93 #define FSR_PROER_MASK          (0x01 << FSR_PROER)
94 #define FSR_PFSBER_MASK         (0x01 << FSR_PFSBER)
95 #define FSR_PFDBER_MASK         (0x01 << FSR_PFDBER)
96 #define FSR_PROIN_MASK          (0x01 << FSR_PROIN)
97 #define FSR_RPROIN_MASK         (0x01 << FSR_RPROIN)
98 #define FSR_RPRODIS_MASK        (0x01 << FSR_RPRODIS)
99 #define FSR_WPROIN0_MASK        (0x01 << FSR_WPROIN0)
100 #define FSR_WPROIN1_MASK        (0x01 << FSR_WPROIN1)
101 #define FSR_WPROIN2_MASK        (0x01 << FSR_WPROIN2)
102 #define FSR_WPRODIS0_MASK       (0x01 << FSR_WPRODIS0)
103 #define FSR_WPRODIS1_MASK       (0x01 << FSR_WPRODIS1)
104 #define FSR_SLM_MASK            (0x01 << FSR_SLM)
105 #define FSR_VER_MASK            (0x01 << FSR_VER)
106
107 /* Flash Config Register */
108 #define FLASH_REG_FLASH0_FCON   (FLASH_REG_BASE | 0x2014)
109
110 #define FCON_WSPFLASH           (0)
111 #define FCON_WSECPF             (4)
112 #define FCON_IDLE               (13)
113 #define FCON_ESLDIS             (14)
114 #define FCON_SLEEP              (15)
115 #define FCON_RPA                (16)
116 #define FCON_DCF                (17)
117 #define FCON_DDF                (18)
118 #define FCON_VOPERM             (24)
119 #define FCON_SQERM              (25)
120 #define FCON_PROERM             (26)
121 #define FCON_PFSBERM            (27)
122 #define FCON_PFDBERM            (29)
123 #define FCON_EOBM               (31)
124
125 #define FCON_WSPFLASH_MASK      (0x0f << FCON_WSPFLASH)
126 #define FCON_WSECPF_MASK        (0x01 << FCON_WSECPF)
127 #define FCON_IDLE_MASK          (0x01 << FCON_IDLE)
128 #define FCON_ESLDIS_MASK        (0x01 << FCON_ESLDIS)
129 #define FCON_SLEEP_MASK         (0x01 << FCON_SLEEP)
130 #define FCON_RPA_MASK           (0x01 << FCON_RPA)
131 #define FCON_DCF_MASK           (0x01 << FCON_DCF)
132 #define FCON_DDF_MASK           (0x01 << FCON_DDF)
133 #define FCON_VOPERM_MASK        (0x01 << FCON_VOPERM)
134 #define FCON_SQERM_MASK         (0x01 << FCON_SQERM)
135 #define FCON_PROERM_MASK        (0x01 << FCON_PROERM)
136 #define FCON_PFSBERM_MASK       (0x01 << FCON_PFSBERM)
137 #define FCON_PFDBERM_MASK       (0x01 << FCON_PFDBERM)
138 #define FCON_EOBM_MASK          (0x01 << FCON_EOBM)
139
140 /* Flash Margin Control Register */
141 #define FLASH_REG_FLASH0_MARP   (FLASH_REG_BASE | 0x2018)
142
143 #define MARP_MARGIN             (0)
144 #define MARP_TRAPDIS            (15)
145
146 #define MARP_MARGIN_MASK        (0x0f << MARP_MARGIN)
147 #define MARP_TRAPDIS_MASK       (0x01 << MARP_TRAPDIS)
148
149 /* Flash Protection Registers */
150 #define FLASH_REG_FLASH0_PROCON0        (FLASH_REG_BASE | 0x2020)
151 #define FLASH_REG_FLASH0_PROCON1        (FLASH_REG_BASE | 0x2024)
152 #define FLASH_REG_FLASH0_PROCON2        (FLASH_REG_BASE | 0x2028)
153
154 #define PROCON_S0L             (0)
155 #define PROCON_S1L             (1)
156 #define PROCON_S2L             (2)
157 #define PROCON_S3L             (3)
158 #define PROCON_S4L             (4)
159 #define PROCON_S5L             (5)
160 #define PROCON_S6L             (6)
161 #define PROCON_S7L             (7)
162 #define PROCON_S8L             (8)
163 #define PROCON_S9L             (9)
164 #define PROCON_S10_S11L        (10)
165 #define PROCON_RPRO            (15)
166
167 #define PROCON_S0L_MASK        (0x01 << PROCON_S0L)
168 #define PROCON_S1L_MASK        (0x01 << PROCON_S1L)
169 #define PROCON_S2L_MASK        (0x01 << PROCON_S2L)
170 #define PROCON_S3L_MASK        (0x01 << PROCON_S3L)
171 #define PROCON_S4L_MASK        (0x01 << PROCON_S4L)
172 #define PROCON_S5L_MASK        (0x01 << PROCON_S5L)
173 #define PROCON_S6L_MASK        (0x01 << PROCON_S6L)
174 #define PROCON_S7L_MASK        (0x01 << PROCON_S7L)
175 #define PROCON_S8L_MASK        (0x01 << PROCON_S8L)
176 #define PROCON_S9L_MASK        (0x01 << PROCON_S9L)
177 #define PROCON_S10_S11L_MASK   (0x01 << PROCON_S10_S11L)
178 #define PROCON_RPRO_MASK       (0x01 << PROCON_RPRO)
179
180 #define FLASH_PROTECT_CONFIRMATION_CODE 0x8AFE15C3
181
182 /* Flash controller configuration values */
183 #define FLASH_ID_XMC4500        0xA2
184 #define FLASH_ID_XMC4700_4800   0x92
185 #define FLASH_ID_XMC4100_4200   0x9C
186 #define FLASH_ID_XMC4400        0x9F
187
188 /* Timeouts */
189 #define FLASH_OP_TIMEOUT 5000
190
191 /* Flash commands (write/erase/protect) are performed using special
192  * command sequences that are written to magic addresses in the flash controller */
193 /* Command sequence addresses.  See reference manual, section 8: Flash Command Sequences */
194 #define FLASH_CMD_ERASE_1 0x0C005554
195 #define FLASH_CMD_ERASE_2 0x0C00AAA8
196 #define FLASH_CMD_ERASE_3 FLASH_CMD_ERASE_1
197 #define FLASH_CMD_ERASE_4 FLASH_CMD_ERASE_1
198 #define FLASH_CMD_ERASE_5 FLASH_CMD_ERASE_2
199 /* ERASE_6 is the sector base address */
200
201 #define FLASH_CMD_CLEAR_STATUS FLASH_CMD_ERASE_1
202
203 #define FLASH_CMD_ENTER_PAGEMODE FLASH_CMD_ERASE_1
204
205 #define FLASH_CMD_LOAD_PAGE_1 0x0C0055F0
206 #define FLASH_CMD_LOAD_PAGE_2 0x0C0055F4
207
208 #define FLASH_CMD_WRITE_PAGE_1 FLASH_CMD_ERASE_1
209 #define FLASH_CMD_WRITE_PAGE_2 FLASH_CMD_ERASE_2
210 #define FLASH_CMD_WRITE_PAGE_3 FLASH_CMD_ERASE_1
211 /* WRITE_PAGE_4 is the page base address */
212
213 #define FLASH_CMD_TEMP_UNPROT_1 FLASH_CMD_ERASE_1
214 #define FLASH_CMD_TEMP_UNPROT_2 FLASH_CMD_ERASE_2
215 #define FLASH_CMD_TEMP_UNPROT_3 0x0C00553C
216 #define FLASH_CMD_TEMP_UNPROT_4 FLASH_CMD_ERASE_2
217 #define FLASH_CMD_TEMP_UNPROT_5 FLASH_CMD_ERASE_2
218 #define FLASH_CMD_TEMP_UNPROT_6 0x0C005558
219
220 struct xmc4xxx_flash_bank {
221         bool probed;
222
223         /* We need the flash controller ID to choose the sector layout */
224         uint32_t fcon_id;
225
226         /* Passwords used for protection operations */
227         uint32_t pw1;
228         uint32_t pw2;
229         bool pw_set;
230
231         /* Protection flags */
232         bool read_protected;
233
234         bool write_prot_otp[MAX_XMC_SECTORS];
235 };
236
237 struct xmc4xxx_command_seq {
238         uint32_t address;
239         uint32_t magic;
240 };
241
242 /* Sector capacities.  See section 8 of xmc4x00_rm */
243 static const unsigned int sector_capacity_8[8] = {
244         16, 16, 16, 16, 16, 16, 16, 128
245 };
246
247 static const unsigned int sector_capacity_9[9] = {
248         16, 16, 16, 16, 16, 16, 16, 128, 256
249 };
250
251 static const unsigned int sector_capacity_12[12] = {
252         16, 16, 16, 16, 16, 16, 16, 16, 128, 256, 256, 256
253 };
254
255 static const unsigned int sector_capacity_16[16] = {
256         16, 16, 16, 16, 16, 16, 16, 16, 128, 256, 256, 256, 256, 256, 256, 256
257 };
258
259 static int xmc4xxx_write_command_sequence(struct flash_bank *bank,
260                                          struct xmc4xxx_command_seq *seq,
261                                          int seq_len)
262 {
263         int res = ERROR_OK;
264
265         for (int i = 0; i < seq_len; i++) {
266                 res = target_write_u32(bank->target, seq[i].address,
267                                        seq[i].magic);
268                 if (res != ERROR_OK)
269                         return res;
270         }
271
272         return ERROR_OK;
273 }
274
275 static int xmc4xxx_load_bank_layout(struct flash_bank *bank)
276 {
277         const unsigned int *capacity = NULL;
278
279         /* At this point, we know which flash controller ID we're
280          * talking to and simply need to fill out the bank structure accordingly */
281         LOG_DEBUG("%d sectors", bank->num_sectors);
282
283         switch (bank->num_sectors) {
284         case 8:
285                 capacity = sector_capacity_8;
286                 break;
287         case 9:
288                 capacity = sector_capacity_9;
289                 break;
290         case 12:
291                 capacity = sector_capacity_12;
292                 break;
293         case 16:
294                 capacity = sector_capacity_16;
295                 break;
296         default:
297                 LOG_ERROR("Unexpected number of sectors, %d\n",
298                           bank->num_sectors);
299                 return ERROR_FAIL;
300         }
301
302         /* This looks like a bank that we understand, now we know the
303          * corresponding sector capacities and we can add those up into the
304          * bank size. */
305         uint32_t total_offset = 0;
306         bank->sectors = calloc(bank->num_sectors,
307                                sizeof(struct flash_sector));
308         for (int i = 0; i < bank->num_sectors; i++) {
309                 bank->sectors[i].size = capacity[i] * 1024;
310                 bank->sectors[i].offset = total_offset;
311                 bank->sectors[i].is_erased = -1;
312                 bank->sectors[i].is_protected = -1;
313
314                 bank->size += bank->sectors[i].size;
315                 LOG_DEBUG("\t%d: %uk", i, capacity[i]);
316                 total_offset += bank->sectors[i].size;
317         }
318
319         /* This part doesn't follow the typical standard of 0xff
320          * being the default padding value.*/
321         bank->default_padded_value = 0x00;
322
323         return ERROR_OK;
324 }
325
326 static int xmc4xxx_probe(struct flash_bank *bank)
327 {
328         int res;
329         uint32_t devid, config;
330         struct xmc4xxx_flash_bank *fb = bank->driver_priv;
331         uint8_t flash_id;
332
333         if (fb->probed)
334                 return ERROR_OK;
335
336         /* It's not possible for the DAP to access the OTP locations needed for
337          * probing the part info and Flash geometry so we require that the target
338          * be halted before proceeding. */
339         if (bank->target->state != TARGET_HALTED) {
340                 LOG_WARNING("Cannot communicate... target not halted.");
341                 return ERROR_TARGET_NOT_HALTED;
342         }
343
344         /* The SCU registers contain the ID of the chip */
345         res = target_read_u32(bank->target, SCU_REG_BASE + SCU_ID_CHIP, &devid);
346         if (res != ERROR_OK) {
347                 LOG_ERROR("Cannot read device identification register.");
348                 return res;
349         }
350
351         /* Make sure this is a XMC4000 family device */
352         if ((devid & 0xF0000) != 0x40000 && devid != 0) {
353                 LOG_ERROR("Platform ID doesn't match XMC4xxx: 0x%08" PRIx32, devid);
354                 return ERROR_FAIL;
355         }
356
357         LOG_DEBUG("Found XMC4xxx with devid: 0x%08" PRIx32, devid);
358
359         /* Now sanity-check the Flash controller itself. */
360         res = target_read_u32(bank->target, FLASH_REG_FLASH0_ID,
361                         &config);
362         if (res != ERROR_OK) {
363                 LOG_ERROR("Cannot read Flash bank configuration.");
364                 return res;
365         }
366         flash_id = (config & 0xff0000) >> 16;
367
368         /* The Flash configuration register is our only means of
369          * determining the sector layout. We need to make sure that
370          * we understand the type of controller we're dealing with */
371         switch (flash_id) {
372         case FLASH_ID_XMC4100_4200:
373                 bank->num_sectors = 8;
374                 LOG_DEBUG("XMC4xxx: XMC4100/4200 detected.");
375                 break;
376         case FLASH_ID_XMC4400:
377                 bank->num_sectors = 9;
378                 LOG_DEBUG("XMC4xxx: XMC4400 detected.");
379                 break;
380         case FLASH_ID_XMC4500:
381                 bank->num_sectors = 12;
382                 LOG_DEBUG("XMC4xxx: XMC4500 detected.");
383                 break;
384         case FLASH_ID_XMC4700_4800:
385                 bank->num_sectors = 16;
386                 LOG_DEBUG("XMC4xxx: XMC4700/4800 detected.");
387                 break;
388         default:
389                 LOG_ERROR("XMC4xxx: Unexpected flash ID. got %02" PRIx8,
390                           flash_id);
391                 return ERROR_FAIL;
392         }
393
394         /* Retrieve information about the particular bank we're probing and fill in
395          * the bank structure accordingly. */
396         res = xmc4xxx_load_bank_layout(bank);
397         if (res == ERROR_OK) {
398                 /* We're done */
399                 fb->probed = true;
400         } else {
401                 LOG_ERROR("Unable to load bank information.");
402                 return ERROR_FAIL;
403         }
404
405         return ERROR_OK;
406 }
407
408 static int xmc4xxx_get_sector_start_addr(struct flash_bank *bank,
409                                          int sector, uint32_t *ret_addr)
410 {
411         /* Make sure we understand this sector */
412         if (sector > bank->num_sectors)
413                 return ERROR_FAIL;
414
415         *ret_addr = bank->base + bank->sectors[sector].offset;
416
417         return ERROR_OK;
418
419 }
420
421 static int xmc4xxx_clear_flash_status(struct flash_bank *bank)
422 {
423         int res;
424         /* TODO: Do we need to check for sequence error? */
425         LOG_INFO("Clearing flash status");
426         res = target_write_u32(bank->target, FLASH_CMD_CLEAR_STATUS,
427                                0xF5);
428         if (res != ERROR_OK) {
429                 LOG_ERROR("Unable to write erase command sequence");
430                 return res;
431         }
432
433         return ERROR_OK;
434 }
435
436 static int xmc4xxx_get_flash_status(struct flash_bank *bank, uint32_t *status)
437 {
438         int res;
439
440         res = target_read_u32(bank->target, FLASH_REG_FLASH0_FSR, status);
441
442         if (res != ERROR_OK)
443                 LOG_ERROR("Cannot read flash status register.");
444
445         return res;
446 }
447
448 static int xmc4xxx_wait_status_busy(struct flash_bank *bank, int timeout)
449 {
450         int res;
451         uint32_t status;
452
453         res = xmc4xxx_get_flash_status(bank, &status);
454         if (res != ERROR_OK)
455                 return res;
456
457         /* While the flash controller is busy, wait */
458         while (status & FSR_PBUSY_MASK) {
459                 res = xmc4xxx_get_flash_status(bank, &status);
460                 if (res != ERROR_OK)
461                         return res;
462
463                 if (timeout-- <= 0) {
464                         LOG_ERROR("Timed out waiting for flash");
465                         return ERROR_FAIL;
466                 }
467                 alive_sleep(1);
468                 keep_alive();
469         }
470
471         if (status & FSR_PROER_MASK) {
472                 LOG_ERROR("XMC4xxx flash protected");
473                 res = ERROR_FAIL;
474         }
475
476         return res;
477 }
478
479 static int xmc4xxx_erase_sector(struct flash_bank *bank, uint32_t address,
480                                 bool user_config)
481 {
482         int res;
483         uint32_t status;
484
485         /* See reference manual table 8.4: Command Sequences for Flash Control */
486         struct xmc4xxx_command_seq erase_cmd_seq[6] = {
487                 {FLASH_CMD_ERASE_1, 0xAA},
488                 {FLASH_CMD_ERASE_2, 0x55},
489                 {FLASH_CMD_ERASE_3, 0x80},
490                 {FLASH_CMD_ERASE_4, 0xAA},
491                 {FLASH_CMD_ERASE_5, 0x55},
492                 {0xFF,              0xFF} /* Needs filled in */
493         };
494
495         /* We need to fill in the base address of the sector we'll be
496          * erasing, as well as the magic code that determines whether
497          * this is a standard flash sector or a user configuration block */
498
499         erase_cmd_seq[5].address = address;
500         if (user_config) {
501                 /* Removing flash protection requires the addition of
502                  * the base address */
503                 erase_cmd_seq[5].address += bank->base;
504                 erase_cmd_seq[5].magic = 0xC0;
505         } else {
506                 erase_cmd_seq[5].magic = 0x30;
507         }
508
509         res = xmc4xxx_write_command_sequence(bank, erase_cmd_seq,
510                                              ARRAY_SIZE(erase_cmd_seq));
511         if (res != ERROR_OK)
512                 return res;
513
514         /* Read the flash status register */
515         res = target_read_u32(bank->target, FLASH_REG_FLASH0_FSR, &status);
516         if (res != ERROR_OK) {
517                 LOG_ERROR("Cannot read flash status register.");
518                 return res;
519         }
520
521         /* Check for a sequence error */
522         if (status & FSR_SQER_MASK) {
523                 LOG_ERROR("Error with flash erase sequence");
524                 return ERROR_FAIL;
525         }
526
527         /* Make sure a flash erase was triggered */
528         if (!(status & FSR_ERASE_MASK)) {
529                 LOG_ERROR("Flash failed to erase");
530                 return ERROR_FAIL;
531         }
532
533         /* Now we must wait for the erase operation to end */
534         res = xmc4xxx_wait_status_busy(bank, FLASH_OP_TIMEOUT);
535
536         return res;
537 }
538
539 static int xmc4xxx_erase(struct flash_bank *bank, int first, int last)
540 {
541         struct xmc4xxx_flash_bank *fb = bank->driver_priv;
542         int res;
543
544         if (bank->target->state != TARGET_HALTED) {
545                 LOG_ERROR("Unable to erase, target is not halted");
546                 return ERROR_TARGET_NOT_HALTED;
547         }
548
549         if (!fb->probed) {
550                 res = xmc4xxx_probe(bank);
551                 if (res != ERROR_OK)
552                         return res;
553         }
554
555         uint32_t tmp_addr;
556         /* Loop through the sectors and erase each one */
557         for (int i = first; i <= last; i++) {
558                 res = xmc4xxx_get_sector_start_addr(bank, i, &tmp_addr);
559                 if (res != ERROR_OK) {
560                         LOG_ERROR("Invalid sector %d", i);
561                         return res;
562                 }
563
564                 LOG_DEBUG("Erasing sector %d @ 0x%08"PRIx32, i, tmp_addr);
565
566                 res = xmc4xxx_erase_sector(bank, tmp_addr, false);
567                 if (res != ERROR_OK) {
568                         LOG_ERROR("Unable to write erase command sequence");
569                         goto clear_status_and_exit;
570                 }
571
572                 /* Now we must wait for the erase operation to end */
573                 res = xmc4xxx_wait_status_busy(bank, FLASH_OP_TIMEOUT);
574
575                 if (res != ERROR_OK)
576                         goto clear_status_and_exit;
577
578                 bank->sectors[i].is_erased = 1;
579         }
580
581 clear_status_and_exit:
582         res = xmc4xxx_clear_flash_status(bank);
583         return res;
584
585 }
586
587 static int xmc4xxx_enter_page_mode(struct flash_bank *bank)
588 {
589         int res;
590         uint32_t status;
591
592         res = target_write_u32(bank->target, FLASH_CMD_ENTER_PAGEMODE, 0x50);
593         if (res != ERROR_OK) {
594                 LOG_ERROR("Unable to write enter page mode command");
595                 return ERROR_FAIL;
596         }
597
598         res = xmc4xxx_get_flash_status(bank, &status);
599
600         if (res != ERROR_OK)
601                 return res;
602
603         /* Make sure we're in page mode */
604         if (!(status & FSR_PFPAGE_MASK)) {
605                 LOG_ERROR("Unable to enter page mode");
606                 return ERROR_FAIL;
607         }
608
609         /* Make sure we didn't encounter a sequence error */
610         if (status & FSR_SQER_MASK) {
611                 LOG_ERROR("Sequence error while entering page mode");
612                 return ERROR_FAIL;
613         }
614
615         return res;
616 }
617
618 /* The logical erase value of an xmc4xxx memory cell is 0x00,
619  * therefore, we cannot use the built in flash blank check and must
620  * implement our own */
621
622 /** Checks whether a memory region is zeroed. */
623 int xmc4xxx_blank_check_memory(struct target *target,
624         uint32_t address, uint32_t count, uint32_t *blank)
625 {
626         struct working_area *erase_check_algorithm;
627         struct reg_param reg_params[3];
628         struct armv7m_algorithm armv7m_info;
629         int retval;
630
631         /* see contrib/loaders/erase_check/armv7m_0_erase_check.s for src */
632
633         static const uint8_t erase_check_code[] = {
634                 /* loop: */
635                 0x03, 0x78,             /* ldrb r3, [r0] */
636                 0x01, 0x30,             /* adds r0, #1 */
637                 0x1A, 0x43,             /* orrs r2, r2, r3 */
638                 0x01, 0x39,             /* subs r1, r1, #1 */
639                 0xFA, 0xD1,             /* bne  loop */
640                 0x00, 0xBE              /* bkpt #0 */
641         };
642
643         /* make sure we have a working area */
644         if (target_alloc_working_area(target, sizeof(erase_check_code),
645                 &erase_check_algorithm) != ERROR_OK)
646                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
647
648         retval = target_write_buffer(target, erase_check_algorithm->address,
649                         sizeof(erase_check_code), (uint8_t *)erase_check_code);
650         if (retval != ERROR_OK)
651                 return retval;
652
653         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
654         armv7m_info.core_mode = ARM_MODE_THREAD;
655
656         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
657         buf_set_u32(reg_params[0].value, 0, 32, address);
658
659         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
660         buf_set_u32(reg_params[1].value, 0, 32, count);
661
662         init_reg_param(&reg_params[2], "r2", 32, PARAM_IN_OUT);
663         buf_set_u32(reg_params[2].value, 0, 32, 0x00);
664
665         retval = target_run_algorithm(target,
666                                       0,
667                                       NULL,
668                                       3,
669                                       reg_params,
670                                       erase_check_algorithm->address,
671                                       erase_check_algorithm->address + (sizeof(erase_check_code) - 2),
672                                       10000,
673                                       &armv7m_info);
674
675         if (retval == ERROR_OK)
676                 *blank = buf_get_u32(reg_params[2].value, 0, 32);
677
678         destroy_reg_param(&reg_params[0]);
679         destroy_reg_param(&reg_params[1]);
680         destroy_reg_param(&reg_params[2]);
681
682         target_free_working_area(target, erase_check_algorithm);
683
684         return retval;
685 }
686
687 static int xmc4xxx_flash_blank_check(struct flash_bank *bank)
688 {
689         struct target *target = bank->target;
690         int i;
691         int retval;
692         uint32_t blank;
693
694         if (bank->target->state != TARGET_HALTED) {
695                 LOG_ERROR("Target not halted");
696                 return ERROR_TARGET_NOT_HALTED;
697         }
698
699         for (i = 0; i < bank->num_sectors; i++) {
700                 uint32_t address = bank->base + bank->sectors[i].offset;
701                 uint32_t size = bank->sectors[i].size;
702
703                 LOG_DEBUG("Erase checking 0x%08"PRIx32, address);
704                 retval = xmc4xxx_blank_check_memory(target, address, size, &blank);
705
706                 if (retval != ERROR_OK)
707                         break;
708
709                 if (blank == 0x00)
710                         bank->sectors[i].is_erased = 1;
711                 else
712                         bank->sectors[i].is_erased = 0;
713         }
714
715         return ERROR_OK;
716 }
717
718 static int xmc4xxx_write_page(struct flash_bank *bank, const uint8_t *pg_buf,
719                               uint32_t offset, bool user_config)
720 {
721         int res;
722         uint32_t status;
723
724         /* Base of the flash write command */
725         struct xmc4xxx_command_seq write_cmd_seq[4] = {
726                 {FLASH_CMD_WRITE_PAGE_1, 0xAA},
727                 {FLASH_CMD_WRITE_PAGE_2, 0x55},
728                 {FLASH_CMD_WRITE_PAGE_3, 0xFF}, /* Needs filled in */
729                 {0xFF,                   0xFF}  /* Needs filled in */
730         };
731
732         /* The command sequence differs depending on whether this is
733          * being written to standard flash or the user configuration
734          * area */
735         if (user_config)
736                 write_cmd_seq[2].magic = 0xC0;
737         else
738                 write_cmd_seq[2].magic = 0xA0;
739
740         /* Finally, we need to add the address that this page will be
741          * written to */
742         write_cmd_seq[3].address = bank->base + offset;
743         write_cmd_seq[3].magic = 0xAA;
744
745
746         /* Flash pages are written 256 bytes at a time.  For each 256
747          * byte chunk, we need to:
748          * 1. Enter page mode. This activates the flash write buffer
749          * 2. Load the page buffer with data (2x 32 bit words at a time)
750          * 3. Burn the page buffer into its intended location
751          * If the starting offset is not on a 256 byte boundary, we
752          * will need to pad the beginning of the write buffer
753          * accordingly. Likewise, if the last page does not fill the
754          * buffer, we should pad it to avoid leftover data from being
755          * written to flash
756          */
757         res = xmc4xxx_enter_page_mode(bank);
758         if (res != ERROR_OK)
759                 return res;
760
761         /* Copy the data into the page buffer*/
762         for (int i = 0; i < 256; i += 8) {
763                 uint32_t w_lo = target_buffer_get_u32(bank->target, &pg_buf[i]);
764                 uint32_t w_hi = target_buffer_get_u32(bank->target, &pg_buf[i + 4]);
765                 LOG_DEBUG("WLO: %08"PRIx32, w_lo);
766                 LOG_DEBUG("WHI: %08"PRIx32, w_hi);
767
768                 /* Data is loaded 2x 32 bit words at a time */
769                 res = target_write_u32(bank->target, FLASH_CMD_LOAD_PAGE_1, w_lo);
770                 if (res != ERROR_OK)
771                         return res;
772
773                 res = target_write_u32(bank->target, FLASH_CMD_LOAD_PAGE_2, w_hi);
774                 if (res != ERROR_OK)
775                         return res;
776
777                 /* Check for an error */
778                 res = xmc4xxx_get_flash_status(bank, &status);
779                 if (res != ERROR_OK)
780                         return res;
781
782                 if (status & FSR_SQER_MASK) {
783                         LOG_ERROR("Error loading page buffer");
784                         return ERROR_FAIL;
785                 }
786         }
787
788         /* The page buffer is now full, time to commit it to flash */
789
790         res = xmc4xxx_write_command_sequence(bank, write_cmd_seq, ARRAY_SIZE(write_cmd_seq));
791         if (res != ERROR_OK) {
792                 LOG_ERROR("Unable to enter write command sequence");
793                 return res;
794         }
795
796         /* Read the flash status register */
797         res = xmc4xxx_get_flash_status(bank, &status);
798         if (res != ERROR_OK)
799                 return res;
800
801         /* Check for a sequence error */
802         if (status & FSR_SQER_MASK) {
803                 LOG_ERROR("Error with flash write sequence");
804                 return ERROR_FAIL;
805         }
806
807         /* Make sure a flash write was triggered */
808         if (!(status & FSR_PROG_MASK)) {
809                 LOG_ERROR("Failed to write flash page");
810                 return ERROR_FAIL;
811         }
812
813         /* Wait for the write operation to end */
814         res = xmc4xxx_wait_status_busy(bank, FLASH_OP_TIMEOUT);
815         if (res != ERROR_OK)
816                 return res;
817
818         /* TODO: Verify that page was written without error */
819         return res;
820 }
821
822 static int xmc4xxx_write(struct flash_bank *bank, const uint8_t *buffer,
823                          uint32_t offset, uint32_t count)
824 {
825         struct xmc4xxx_flash_bank *fb = bank->driver_priv;
826         int res = ERROR_OK;
827
828         if (bank->target->state != TARGET_HALTED) {
829                 LOG_ERROR("Unable to erase, target is not halted");
830                 return ERROR_TARGET_NOT_HALTED;
831         }
832
833         if (!fb->probed) {
834                 res = xmc4xxx_probe(bank);
835                 if (res != ERROR_OK)
836                         return res;
837         }
838
839         /* Make sure we won't run off the end of the flash bank */
840         if ((offset + count) > (bank->size)) {
841                 LOG_ERROR("Attempting to write past the end of flash");
842                 return ERROR_FAIL;
843         }
844
845
846         /* Attempt to write the passed in buffer to flash */
847         /* Pages are written 256 bytes at a time, we need to handle
848          * scenarios where padding is required at the beginning and
849          * end of a page */
850         while (count) {
851                 /* page working area */
852                 uint8_t tmp_buf[256] = {0};
853
854                 /* Amount of data we'll be writing to this page */
855                 int remaining;
856                 int end_pad;
857
858                 remaining = MIN(count, sizeof(tmp_buf));
859                 end_pad   = sizeof(tmp_buf) - remaining;
860
861                 /* Make sure we're starting on a page boundary */
862                 int start_pad = offset % 256;
863                 if (start_pad) {
864                         LOG_INFO("Write does not start on a 256 byte boundary. "
865                                  "Padding by %d bytes", start_pad);
866                         memset(tmp_buf, 0xff, start_pad);
867                         /* Subtract the amount of start offset from
868                          * the amount of data we'll need to write */
869                         remaining -= start_pad;
870                 }
871
872                 /* Remove the amount we'll be writing from the total count */
873                 count -= remaining;
874
875                 /* Now copy in the remaining data */
876                 memcpy(&tmp_buf[start_pad], buffer, remaining);
877
878                 if (end_pad) {
879                         LOG_INFO("Padding end of page @%08"PRIx32" by %d bytes",
880                                  bank->base + offset, end_pad);
881                         memset(&tmp_buf[256 - end_pad], 0xff, end_pad);
882                 }
883
884                 /* Now commit this page to flash, if there was start
885                  * padding, we should subtract that from the target offset */
886                 res = xmc4xxx_write_page(bank, tmp_buf, (offset - start_pad), false);
887                 if (res != ERROR_OK) {
888                         LOG_ERROR("Unable to write flash page");
889                         goto abort_write_and_exit;
890                 }
891
892                 /* Advance the buffer pointer */
893                 buffer += remaining;
894
895                 /* Advance the offset */
896                 offset += remaining;
897         }
898
899 abort_write_and_exit:
900         xmc4xxx_clear_flash_status(bank);
901         return res;
902
903 }
904
905 static int xmc4xxx_get_info_command(struct flash_bank *bank, char *buf, int buf_size)
906 {
907         struct xmc4xxx_flash_bank *fb = bank->driver_priv;
908         uint32_t scu_idcode;
909
910         if (bank->target->state != TARGET_HALTED) {
911                 LOG_WARNING("Cannot communicate... target not halted.");
912                 return ERROR_TARGET_NOT_HALTED;
913         }
914
915         /* The SCU registers contain the ID of the chip */
916         int res = target_read_u32(bank->target, SCU_REG_BASE + SCU_ID_CHIP, &scu_idcode);
917         if (res != ERROR_OK) {
918                 LOG_ERROR("Cannot read device identification register.");
919                 return res;
920         }
921
922         uint16_t dev_id = (scu_idcode & 0xfff0) >> 4;
923         uint16_t rev_id = scu_idcode & 0xf;
924         const char *dev_str;
925         const char *rev_str = NULL;
926
927         switch (dev_id) {
928         case 0x100:
929                 dev_str = "XMC4100";
930
931                 switch (rev_id) {
932                 case 0x1:
933                         rev_str = "AA";
934                         break;
935                 case 0x2:
936                         rev_str = "AB";
937                         break;
938                 }
939                 break;
940         case 0x200:
941                 dev_str = "XMC4200";
942
943                 switch (rev_id) {
944                 case 0x1:
945                         rev_str = "AA";
946                         break;
947                 case 0x2:
948                         rev_str = "AB";
949                         break;
950                 }
951                 break;
952         case 0x400:
953                 dev_str = "XMC4400";
954
955                 switch (rev_id) {
956                 case 0x1:
957                         rev_str = "AA";
958                         break;
959                 case 0x2:
960                         rev_str = "AB";
961                         break;
962                 }
963                 break;
964         case 0:
965                 /* XMC4500 EES AA13 with date codes before GE212
966                  * had zero SCU_IDCHIP
967                  */
968                 dev_str = "XMC4500 EES";
969                 rev_str = "AA13";
970                 break;
971         case 0x500:
972                 dev_str = "XMC4500";
973
974                 switch (rev_id) {
975                 case 0x2:
976                         rev_str = "AA";
977                         break;
978                 case 0x3:
979                         rev_str = "AB";
980                         break;
981                 case 0x4:
982                         rev_str = "AC";
983                         break;
984                 }
985                 break;
986         case 0x700:
987                 dev_str = "XMC4700";
988
989                 switch (rev_id) {
990                 case 0x1:
991                         rev_str = "EES-AA";
992                         break;
993                 }
994                 break;
995         case 0x800:
996                 dev_str = "XMC4800";
997
998                 switch (rev_id) {
999                 case 0x1:
1000                         rev_str = "EES-AA";
1001                         break;
1002                 }
1003                 break;
1004
1005         default:
1006                 snprintf(buf, buf_size,
1007                          "Cannot identify target as an XMC4xxx. SCU_ID: %"PRIx32"\n",
1008                          scu_idcode);
1009                 return ERROR_OK;
1010         }
1011
1012         /* String to declare protection data held in the private driver */
1013         char prot_str[512] = {0};
1014         if (fb->read_protected)
1015                 snprintf(prot_str, sizeof(prot_str), "\nFlash is read protected");
1016
1017         bool otp_enabled = false;
1018         for (int i = 0; i < bank->num_sectors; i++)
1019                 if (fb->write_prot_otp[i])
1020                         otp_enabled = true;
1021
1022         /* If OTP Write protection is enabled (User 2), list each
1023          * sector that has it enabled */
1024         char otp_str[8];
1025         if (otp_enabled) {
1026                 strcat(prot_str, "\nOTP Protection is enabled for sectors:\n");
1027                 for (int i = 0; i < bank->num_sectors; i++) {
1028                         if (fb->write_prot_otp[i]) {
1029                                 snprintf(otp_str, sizeof(otp_str), "- %d\n", i);
1030                                 strncat(prot_str, otp_str, ARRAY_SIZE(otp_str));
1031                         }
1032                 }
1033         }
1034
1035         if (rev_str != NULL)
1036                 snprintf(buf, buf_size, "%s - Rev: %s%s",
1037                          dev_str, rev_str, prot_str);
1038         else
1039                 snprintf(buf, buf_size, "%s - Rev: unknown (0x%01x)%s",
1040                          dev_str, rev_id, prot_str);
1041
1042         return ERROR_OK;
1043 }
1044
1045 static int xmc4xxx_temp_unprotect(struct flash_bank *bank, int user_level)
1046 {
1047         struct xmc4xxx_flash_bank *fb;
1048         int res = ERROR_OK;
1049         uint32_t status = 0;
1050
1051         struct xmc4xxx_command_seq temp_unprot_seq[6] = {
1052                 {FLASH_CMD_TEMP_UNPROT_1, 0xAA},
1053                 {FLASH_CMD_TEMP_UNPROT_2, 0x55},
1054                 {FLASH_CMD_TEMP_UNPROT_3, 0xFF}, /* Needs filled in */
1055                 {FLASH_CMD_TEMP_UNPROT_4, 0xFF}, /* Needs filled in */
1056                 {FLASH_CMD_TEMP_UNPROT_5, 0xFF}, /* Needs filled in */
1057                 {FLASH_CMD_TEMP_UNPROT_6, 0x05}
1058         };
1059
1060         if (user_level < 0 || user_level > 2) {
1061                 LOG_ERROR("Invalid user level, must be 0-2");
1062                 return ERROR_FAIL;
1063         }
1064
1065         fb = bank->driver_priv;
1066
1067         /* Fill in the user level and passwords */
1068         temp_unprot_seq[2].magic = user_level;
1069         temp_unprot_seq[3].magic = fb->pw1;
1070         temp_unprot_seq[4].magic = fb->pw2;
1071
1072         res = xmc4xxx_write_command_sequence(bank, temp_unprot_seq,
1073                                              ARRAY_SIZE(temp_unprot_seq));
1074         if (res != ERROR_OK) {
1075                 LOG_ERROR("Unable to write temp unprotect sequence");
1076                 return res;
1077         }
1078
1079         res = xmc4xxx_get_flash_status(bank, &status);
1080         if (res != ERROR_OK)
1081                 return res;
1082
1083         if (status & FSR_WPRODIS0) {
1084                 LOG_INFO("Flash is temporarily unprotected");
1085         } else {
1086                 LOG_INFO("Unable to disable flash protection");
1087                 res = ERROR_FAIL;
1088         }
1089
1090
1091         return res;
1092 }
1093
1094 static int xmc4xxx_flash_unprotect(struct flash_bank *bank, int32_t level)
1095 {
1096         uint32_t addr;
1097         int res;
1098
1099         if ((level < 0) || (level > 1)) {
1100                 LOG_ERROR("Invalid user level. Must be 0-1");
1101                 return ERROR_FAIL;
1102         }
1103
1104         switch (level) {
1105         case 0:
1106                 addr = UCB0_BASE;
1107                 break;
1108         case 1:
1109                 addr = UCB1_BASE;
1110                 break;
1111         }
1112
1113         res = xmc4xxx_erase_sector(bank, addr, true);
1114
1115         if (res != ERROR_OK)
1116                 LOG_ERROR("Error erasing user configuration block");
1117
1118         return res;
1119 }
1120
1121 /* Reference: "XMC4500 Flash Protection.pptx" app note */
1122 static int xmc4xxx_flash_protect(struct flash_bank *bank, int level, bool read_protect,
1123                                  int first, int last)
1124 {
1125         /* User configuration block buffers */
1126         uint8_t ucp0_buf[8 * sizeof(uint32_t)] = {0};
1127         uint32_t ucb_base = 0;
1128         uint32_t procon = 0;
1129         int res = ERROR_OK;
1130         uint32_t status = 0;
1131         bool proin = false;
1132
1133         struct xmc4xxx_flash_bank *fb = bank->driver_priv;
1134
1135         /* Read protect only works for user 0, make sure we don't try
1136          * to do something silly */
1137         if (level != 0 && read_protect) {
1138                 LOG_ERROR("Read protection is for user level 0 only!");
1139                 return ERROR_FAIL;
1140         }
1141
1142         /* Check to see if protection is already installed for the
1143          * specified user level.  If it is, the user configuration
1144          * block will need to be erased before we can continue */
1145
1146         /* Grab the flash status register*/
1147         res = xmc4xxx_get_flash_status(bank, &status);
1148         if (res != ERROR_OK)
1149                 return res;
1150
1151         switch (level) {
1152         case 0:
1153                 if ((status & FSR_RPROIN_MASK) || (status & FSR_WPROIN0_MASK))
1154                         proin = true;
1155                 break;
1156         case 1:
1157                 if (status & FSR_WPROIN1_MASK)
1158                         proin = true;
1159                 break;
1160         case 2:
1161                 if (status & FSR_WPROIN2_MASK)
1162                         proin = true;
1163                 break;
1164         }
1165
1166         if (proin) {
1167                 LOG_ERROR("Flash protection is installed for user %d"
1168                           " and must be removed before continuing", level);
1169                 return ERROR_FAIL;
1170         }
1171
1172         /* If this device has 12 flash sectors, protection for
1173          * sectors 10 & 11 are handled jointly. If we are trying to
1174          * write all sectors, we should decrement
1175          * last to ensure we don't write to a register bit that
1176          * doesn't exist*/
1177         if ((bank->num_sectors == 12) && (last == 12))
1178                 last--;
1179
1180         /*  We need to fill out the procon register representation
1181          *   that we will be writing to the device */
1182         for (int i = first; i <= last; i++)
1183                 procon |= 1 << i;
1184
1185         /* If read protection is requested, set the appropriate bit
1186          * (we checked that this is allowed above) */
1187         if (read_protect)
1188                 procon |= PROCON_RPRO_MASK;
1189
1190         LOG_DEBUG("Setting flash protection with procon:");
1191         LOG_DEBUG("PROCON: %"PRIx32, procon);
1192
1193         /* First we need to copy in the procon register to the buffer
1194          * we're going to attempt to write.  This is written twice */
1195         target_buffer_set_u32(bank->target, &ucp0_buf[0 * 4], procon);
1196         target_buffer_set_u32(bank->target, &ucp0_buf[2 * 4], procon);
1197
1198         /* Now we must copy in both flash passwords.  As with the
1199          * procon data, this must be written twice (4 total words
1200          * worth of data) */
1201         target_buffer_set_u32(bank->target, &ucp0_buf[4 * 4], fb->pw1);
1202         target_buffer_set_u32(bank->target, &ucp0_buf[5 * 4], fb->pw2);
1203         target_buffer_set_u32(bank->target, &ucp0_buf[6 * 4], fb->pw1);
1204         target_buffer_set_u32(bank->target, &ucp0_buf[7 * 4], fb->pw2);
1205
1206         /* Finally, (if requested) we copy in the confirmation
1207          * code so that the protection is permanent and will
1208          * require a password to undo. */
1209         target_buffer_set_u32(bank->target, &ucp0_buf[0 * 4], FLASH_PROTECT_CONFIRMATION_CODE);
1210         target_buffer_set_u32(bank->target, &ucp0_buf[2 * 4], FLASH_PROTECT_CONFIRMATION_CODE);
1211
1212         /* Now that the data is copied into place, we must write
1213          * these pages into flash */
1214
1215         /* The user configuration block base depends on what level of
1216          * protection we're trying to install, select the proper one */
1217         switch (level) {
1218         case 0:
1219                 ucb_base = UCB0_BASE;
1220                 break;
1221         case 1:
1222                 ucb_base = UCB1_BASE;
1223                 break;
1224         case 2:
1225                 ucb_base = UCB2_BASE;
1226                 break;
1227         }
1228
1229         /* Write the user config pages */
1230         res = xmc4xxx_write_page(bank, ucp0_buf, ucb_base, true);
1231         if (res != ERROR_OK) {
1232                 LOG_ERROR("Error writing user configuration block 0");
1233                 return res;
1234         }
1235
1236         return ERROR_OK;
1237 }
1238
1239 static int xmc4xxx_protect(struct flash_bank *bank, int set, int first, int last)
1240 {
1241         int ret;
1242         struct xmc4xxx_flash_bank *fb = bank->driver_priv;
1243
1244         /* Check for flash passwords */
1245         if (!fb->pw_set) {
1246                 LOG_ERROR("Flash passwords not set, use xmc4xxx flash_password to set them");
1247                 return ERROR_FAIL;
1248         }
1249
1250         /* We want to clear flash protection temporarily*/
1251         if (set == 0) {
1252                 LOG_WARNING("Flash protection will be temporarily disabled"
1253                             " for all pages (User 0 only)!");
1254                 ret = xmc4xxx_temp_unprotect(bank, 0);
1255                 return ret;
1256         }
1257
1258         /* Install write protection for user 0 on the specified pages */
1259         ret = xmc4xxx_flash_protect(bank, 0, false, first, last);
1260
1261         return ret;
1262 }
1263
1264 static int xmc4xxx_protect_check(struct flash_bank *bank)
1265 {
1266         int ret;
1267         uint32_t protection[3] = {0};
1268         struct xmc4xxx_flash_bank *fb = bank->driver_priv;
1269
1270         ret = target_read_u32(bank->target, FLASH_REG_FLASH0_PROCON0, &protection[0]);
1271         if (ret != ERROR_OK) {
1272                 LOG_ERROR("Unable to read flash User0 protection register");
1273                 return ret;
1274         }
1275
1276         ret = target_read_u32(bank->target, FLASH_REG_FLASH0_PROCON1, &protection[1]);
1277         if (ret != ERROR_OK) {
1278                 LOG_ERROR("Unable to read flash User1 protection register");
1279                 return ret;
1280         }
1281
1282         ret = target_read_u32(bank->target, FLASH_REG_FLASH0_PROCON2, &protection[2]);
1283         if (ret != ERROR_OK) {
1284                 LOG_ERROR("Unable to read flash User2 protection register");
1285                 return ret;
1286         }
1287
1288         int sectors = bank->num_sectors;
1289
1290         /* On devices with 12 sectors, sectors 10 & 11 are ptected
1291          * together instead of individually */
1292         if (sectors == 12)
1293                 sectors--;
1294
1295         /* Clear the protection status */
1296         for (int i = 0; i < bank->num_sectors; i++) {
1297                 bank->sectors[i].is_protected = 0;
1298                 fb->write_prot_otp[i] = false;
1299         }
1300         fb->read_protected = false;
1301
1302         /* The xmc4xxx series supports 3 levels of user protection
1303          * (User0, User1 (low priority), and User 2(OTP), we need to
1304          * check all 3 */
1305         for (unsigned int i = 0; i < ARRAY_SIZE(protection); i++) {
1306
1307                 /* Check for write protection on every available
1308                 *  sector */
1309                 for (int j = 0; j < sectors; j++) {
1310                         int set = (protection[i] & (1 << j)) ? 1 : 0;
1311                         bank->sectors[j].is_protected |= set;
1312
1313                         /* Handle sector 11 */
1314                         if (j == 10)
1315                                 bank->sectors[j + 1].is_protected |= set;
1316
1317                         /* User 2 indicates this protection is
1318                          * permanent, make note in the private driver structure */
1319                         if (i == 2 && set) {
1320                                 fb->write_prot_otp[j] = true;
1321
1322                                 /* Handle sector 11 */
1323                                 if (j == 10)
1324                                         fb->write_prot_otp[j + 1] = true;
1325                         }
1326
1327                 }
1328         }
1329
1330         /* XMC4xxx also supports read proptection, make a note
1331          * in the private driver structure */
1332         if (protection[0] & PROCON_RPRO_MASK)
1333                 fb->read_protected = true;
1334
1335         return ERROR_OK;
1336 }
1337
1338 FLASH_BANK_COMMAND_HANDLER(xmc4xxx_flash_bank_command)
1339 {
1340         bank->driver_priv = malloc(sizeof(struct xmc4xxx_flash_bank));
1341
1342         if (!bank->driver_priv)
1343                 return ERROR_FLASH_OPERATION_FAILED;
1344
1345         (void)memset(bank->driver_priv, 0, sizeof(struct xmc4xxx_flash_bank));
1346
1347         return ERROR_OK;
1348 }
1349
1350 COMMAND_HANDLER(xmc4xxx_handle_flash_password_command)
1351 {
1352         int res;
1353         struct flash_bank *bank;
1354
1355         if (CMD_ARGC < 3)
1356                 return ERROR_COMMAND_SYNTAX_ERROR;
1357
1358         res = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1359         if (res != ERROR_OK)
1360                 return res;
1361
1362         struct xmc4xxx_flash_bank *fb = bank->driver_priv;
1363
1364         errno = 0;
1365
1366         /* We skip over the flash bank */
1367         fb->pw1 = strtol(CMD_ARGV[1], NULL, 16);
1368
1369         if (errno)
1370                 return ERROR_COMMAND_SYNTAX_ERROR;
1371
1372         fb->pw2 = strtol(CMD_ARGV[2], NULL, 16);
1373
1374         if (errno)
1375                 return ERROR_COMMAND_SYNTAX_ERROR;
1376
1377         fb->pw_set = true;
1378
1379         command_print(CMD_CTX, "XMC4xxx flash passwords set to:\n");
1380         command_print(CMD_CTX, "-0x%08"PRIx32"\n", fb->pw1);
1381         command_print(CMD_CTX, "-0x%08"PRIx32"\n", fb->pw2);
1382         return ERROR_OK;
1383 }
1384
1385 COMMAND_HANDLER(xmc4xxx_handle_flash_unprotect_command)
1386 {
1387         struct flash_bank *bank;
1388         int res;
1389         int32_t level;
1390
1391         if (CMD_ARGC < 2)
1392                 return ERROR_COMMAND_SYNTAX_ERROR;
1393
1394         res = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
1395         if (res != ERROR_OK)
1396                 return res;
1397
1398         COMMAND_PARSE_NUMBER(s32, CMD_ARGV[1], level);
1399
1400         res = xmc4xxx_flash_unprotect(bank, level);
1401
1402         return res;
1403 }
1404
1405 static const struct command_registration xmc4xxx_exec_command_handlers[] = {
1406         {
1407                 .name = "flash_password",
1408                 .handler = xmc4xxx_handle_flash_password_command,
1409                 .mode = COMMAND_EXEC,
1410                 .usage = "bank_id password1 password2",
1411                 .help = "Set the flash passwords used for protect operations. "
1412                 "Passwords should be in standard hex form (0x00000000). "
1413                 "(You must call this before any other protect commands) "
1414                 "NOTE: The xmc4xxx's UCB area only allows for FOUR cycles. "
1415                 "Please use protection carefully!",
1416         },
1417         {
1418                 .name = "flash_unprotect",
1419                 .handler = xmc4xxx_handle_flash_unprotect_command,
1420                 .mode = COMMAND_EXEC,
1421                 .usage = "bank_id user_level[0-1]",
1422                 .help = "Permanently Removes flash protection (read and write) "
1423                 "for the specified user level",
1424         },      COMMAND_REGISTRATION_DONE
1425 };
1426
1427 static const struct command_registration xmc4xxx_command_handlers[] = {
1428         {
1429                 .name = "xmc4xxx",
1430                 .mode = COMMAND_ANY,
1431                 .help = "xmc4xxx flash command group",
1432                 .usage = "",
1433                 .chain = xmc4xxx_exec_command_handlers,
1434         },
1435         COMMAND_REGISTRATION_DONE
1436 };
1437
1438 struct flash_driver xmc4xxx_flash = {
1439         .name = "xmc4xxx",
1440         .commands = xmc4xxx_command_handlers,
1441         .flash_bank_command = xmc4xxx_flash_bank_command,
1442         .erase = xmc4xxx_erase,
1443         .write = xmc4xxx_write,
1444         .read = default_flash_read,
1445         .probe = xmc4xxx_probe,
1446         .auto_probe = xmc4xxx_probe,
1447         .erase_check = xmc4xxx_flash_blank_check,
1448         .info = xmc4xxx_get_info_command,
1449         .protect_check = xmc4xxx_protect_check,
1450         .protect = xmc4xxx_protect,
1451 };