d4affa6831fdcd202031d99d9817b72dae0df03c
[fw/openocd] / src / target / cortex_m.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2006 by Magnus Lundin                                   *
6  *   lundin@mlu.mine.nu                                                    *
7  *                                                                         *
8  *   Copyright (C) 2008 by Spencer Oliver                                  *
9  *   spen@spen-soft.co.uk                                                  *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
23  *                                                                         *
24  *                                                                         *
25  *   Cortex-M3(tm) TRM, ARM DDI 0337E (r1p1) and 0337G (r2p0)              *
26  *                                                                         *
27  ***************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #include "jtag/interface.h"
33 #include "breakpoints.h"
34 #include "cortex_m.h"
35 #include "target_request.h"
36 #include "target_type.h"
37 #include "arm_adi_v5.h"
38 #include "arm_disassembler.h"
39 #include "register.h"
40 #include "arm_opcodes.h"
41 #include "arm_semihosting.h"
42 #include <helper/time_support.h>
43 #include <rtt/rtt.h>
44
45 /* NOTE:  most of this should work fine for the Cortex-M1 and
46  * Cortex-M0 cores too, although they're ARMv6-M not ARMv7-M.
47  * Some differences:  M0/M1 doesn't have FPB remapping or the
48  * DWT tracing/profiling support.  (So the cycle counter will
49  * not be usable; the other stuff isn't currently used here.)
50  *
51  * Although there are some workarounds for errata seen only in r0p0
52  * silicon, such old parts are hard to find and thus not much tested
53  * any longer.
54  */
55
56 /* Supported Cortex-M Cores */
57 static const struct cortex_m_part_info cortex_m_parts[] = {
58         {
59                 .partno = CORTEX_M0_PARTNO,
60                 .name = "Cortex-M0",
61                 .arch = ARM_ARCH_V6M,
62         },
63         {
64                 .partno = CORTEX_M0P_PARTNO,
65                 .name = "Cortex-M0+",
66                 .arch = ARM_ARCH_V6M,
67         },
68         {
69                 .partno = CORTEX_M1_PARTNO,
70                 .name = "Cortex-M1",
71                 .arch = ARM_ARCH_V6M,
72         },
73         {
74                 .partno = CORTEX_M3_PARTNO,
75                 .name = "Cortex-M3",
76                 .arch = ARM_ARCH_V7M,
77                 .flags = CORTEX_M_F_TAR_AUTOINCR_BLOCK_4K,
78         },
79         {
80                 .partno = CORTEX_M4_PARTNO,
81                 .name = "Cortex-M4",
82                 .arch = ARM_ARCH_V7M,
83                 .flags = CORTEX_M_F_HAS_FPV4 | CORTEX_M_F_TAR_AUTOINCR_BLOCK_4K,
84         },
85         {
86                 .partno = CORTEX_M7_PARTNO,
87                 .name = "Cortex-M7",
88                 .arch = ARM_ARCH_V7M,
89                 .flags = CORTEX_M_F_HAS_FPV5,
90         },
91         {
92                 .partno = CORTEX_M23_PARTNO,
93                 .name = "Cortex-M23",
94                 .arch = ARM_ARCH_V8M,
95         },
96         {
97                 .partno = CORTEX_M33_PARTNO,
98                 .name = "Cortex-M33",
99                 .arch = ARM_ARCH_V8M,
100                 .flags = CORTEX_M_F_HAS_FPV5,
101         },
102         {
103                 .partno = CORTEX_M35P_PARTNO,
104                 .name = "Cortex-M35P",
105                 .arch = ARM_ARCH_V8M,
106                 .flags = CORTEX_M_F_HAS_FPV5,
107         },
108         {
109                 .partno = CORTEX_M55_PARTNO,
110                 .name = "Cortex-M55",
111                 .arch = ARM_ARCH_V8M,
112                 .flags = CORTEX_M_F_HAS_FPV5,
113         },
114 };
115
116 /* forward declarations */
117 static int cortex_m_store_core_reg_u32(struct target *target,
118                 uint32_t num, uint32_t value);
119 static void cortex_m_dwt_free(struct target *target);
120
121 static int cortex_m_load_core_reg_u32(struct target *target,
122                 uint32_t regsel, uint32_t *value)
123 {
124         struct armv7m_common *armv7m = target_to_armv7m(target);
125         int retval;
126         uint32_t dcrdr;
127
128         /* because the DCB_DCRDR is used for the emulated dcc channel
129          * we have to save/restore the DCB_DCRDR when used */
130         if (target->dbg_msg_enabled) {
131                 retval = mem_ap_read_u32(armv7m->debug_ap, DCB_DCRDR, &dcrdr);
132                 if (retval != ERROR_OK)
133                         return retval;
134         }
135
136         retval = mem_ap_write_u32(armv7m->debug_ap, DCB_DCRSR, regsel);
137         if (retval != ERROR_OK)
138                 return retval;
139
140         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DCRDR, value);
141         if (retval != ERROR_OK)
142                 return retval;
143
144         if (target->dbg_msg_enabled) {
145                 /* restore DCB_DCRDR - this needs to be in a separate
146                  * transaction otherwise the emulated DCC channel breaks */
147                 if (retval == ERROR_OK)
148                         retval = mem_ap_write_atomic_u32(armv7m->debug_ap, DCB_DCRDR, dcrdr);
149         }
150
151         return retval;
152 }
153
154 static int cortex_m_store_core_reg_u32(struct target *target,
155                 uint32_t regsel, uint32_t value)
156 {
157         struct armv7m_common *armv7m = target_to_armv7m(target);
158         int retval;
159         uint32_t dcrdr;
160
161         /* because the DCB_DCRDR is used for the emulated dcc channel
162          * we have to save/restore the DCB_DCRDR when used */
163         if (target->dbg_msg_enabled) {
164                 retval = mem_ap_read_u32(armv7m->debug_ap, DCB_DCRDR, &dcrdr);
165                 if (retval != ERROR_OK)
166                         return retval;
167         }
168
169         retval = mem_ap_write_u32(armv7m->debug_ap, DCB_DCRDR, value);
170         if (retval != ERROR_OK)
171                 return retval;
172
173         retval = mem_ap_write_atomic_u32(armv7m->debug_ap, DCB_DCRSR, regsel | DCRSR_WNR);
174         if (retval != ERROR_OK)
175                 return retval;
176
177         if (target->dbg_msg_enabled) {
178                 /* restore DCB_DCRDR - this needs to be in a separate
179                  * transaction otherwise the emulated DCC channel breaks */
180                 if (retval == ERROR_OK)
181                         retval = mem_ap_write_atomic_u32(armv7m->debug_ap, DCB_DCRDR, dcrdr);
182         }
183
184         return retval;
185 }
186
187 static int cortex_m_write_debug_halt_mask(struct target *target,
188         uint32_t mask_on, uint32_t mask_off)
189 {
190         struct cortex_m_common *cortex_m = target_to_cm(target);
191         struct armv7m_common *armv7m = &cortex_m->armv7m;
192
193         /* mask off status bits */
194         cortex_m->dcb_dhcsr &= ~((0xFFFFul << 16) | mask_off);
195         /* create new register mask */
196         cortex_m->dcb_dhcsr |= DBGKEY | C_DEBUGEN | mask_on;
197
198         return mem_ap_write_atomic_u32(armv7m->debug_ap, DCB_DHCSR, cortex_m->dcb_dhcsr);
199 }
200
201 static int cortex_m_set_maskints(struct target *target, bool mask)
202 {
203         struct cortex_m_common *cortex_m = target_to_cm(target);
204         if (!!(cortex_m->dcb_dhcsr & C_MASKINTS) != mask)
205                 return cortex_m_write_debug_halt_mask(target, mask ? C_MASKINTS : 0, mask ? 0 : C_MASKINTS);
206         else
207                 return ERROR_OK;
208 }
209
210 static int cortex_m_set_maskints_for_halt(struct target *target)
211 {
212         struct cortex_m_common *cortex_m = target_to_cm(target);
213         switch (cortex_m->isrmasking_mode) {
214                 case CORTEX_M_ISRMASK_AUTO:
215                         /* interrupts taken at resume, whether for step or run -> no mask */
216                         return cortex_m_set_maskints(target, false);
217
218                 case CORTEX_M_ISRMASK_OFF:
219                         /* interrupts never masked */
220                         return cortex_m_set_maskints(target, false);
221
222                 case CORTEX_M_ISRMASK_ON:
223                         /* interrupts always masked */
224                         return cortex_m_set_maskints(target, true);
225
226                 case CORTEX_M_ISRMASK_STEPONLY:
227                         /* interrupts masked for single step only -> mask now if MASKINTS
228                          * erratum, otherwise only mask before stepping */
229                         return cortex_m_set_maskints(target, cortex_m->maskints_erratum);
230         }
231         return ERROR_OK;
232 }
233
234 static int cortex_m_set_maskints_for_run(struct target *target)
235 {
236         switch (target_to_cm(target)->isrmasking_mode) {
237                 case CORTEX_M_ISRMASK_AUTO:
238                         /* interrupts taken at resume, whether for step or run -> no mask */
239                         return cortex_m_set_maskints(target, false);
240
241                 case CORTEX_M_ISRMASK_OFF:
242                         /* interrupts never masked */
243                         return cortex_m_set_maskints(target, false);
244
245                 case CORTEX_M_ISRMASK_ON:
246                         /* interrupts always masked */
247                         return cortex_m_set_maskints(target, true);
248
249                 case CORTEX_M_ISRMASK_STEPONLY:
250                         /* interrupts masked for single step only -> no mask */
251                         return cortex_m_set_maskints(target, false);
252         }
253         return ERROR_OK;
254 }
255
256 static int cortex_m_set_maskints_for_step(struct target *target)
257 {
258         switch (target_to_cm(target)->isrmasking_mode) {
259                 case CORTEX_M_ISRMASK_AUTO:
260                         /* the auto-interrupt should already be done -> mask */
261                         return cortex_m_set_maskints(target, true);
262
263                 case CORTEX_M_ISRMASK_OFF:
264                         /* interrupts never masked */
265                         return cortex_m_set_maskints(target, false);
266
267                 case CORTEX_M_ISRMASK_ON:
268                         /* interrupts always masked */
269                         return cortex_m_set_maskints(target, true);
270
271                 case CORTEX_M_ISRMASK_STEPONLY:
272                         /* interrupts masked for single step only -> mask */
273                         return cortex_m_set_maskints(target, true);
274         }
275         return ERROR_OK;
276 }
277
278 static int cortex_m_clear_halt(struct target *target)
279 {
280         struct cortex_m_common *cortex_m = target_to_cm(target);
281         struct armv7m_common *armv7m = &cortex_m->armv7m;
282         int retval;
283
284         /* clear step if any */
285         cortex_m_write_debug_halt_mask(target, C_HALT, C_STEP);
286
287         /* Read Debug Fault Status Register */
288         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, NVIC_DFSR, &cortex_m->nvic_dfsr);
289         if (retval != ERROR_OK)
290                 return retval;
291
292         /* Clear Debug Fault Status */
293         retval = mem_ap_write_atomic_u32(armv7m->debug_ap, NVIC_DFSR, cortex_m->nvic_dfsr);
294         if (retval != ERROR_OK)
295                 return retval;
296         LOG_DEBUG(" NVIC_DFSR 0x%" PRIx32 "", cortex_m->nvic_dfsr);
297
298         return ERROR_OK;
299 }
300
301 static int cortex_m_single_step_core(struct target *target)
302 {
303         struct cortex_m_common *cortex_m = target_to_cm(target);
304         int retval;
305
306         /* Mask interrupts before clearing halt, if not done already.  This avoids
307          * Erratum 377497 (fixed in r1p0) where setting MASKINTS while clearing
308          * HALT can put the core into an unknown state.
309          */
310         if (!(cortex_m->dcb_dhcsr & C_MASKINTS)) {
311                 retval = cortex_m_write_debug_halt_mask(target, C_MASKINTS, 0);
312                 if (retval != ERROR_OK)
313                         return retval;
314         }
315         retval = cortex_m_write_debug_halt_mask(target, C_STEP, C_HALT);
316         if (retval != ERROR_OK)
317                 return retval;
318         LOG_DEBUG(" ");
319
320         /* restore dhcsr reg */
321         cortex_m_clear_halt(target);
322
323         return ERROR_OK;
324 }
325
326 static int cortex_m_enable_fpb(struct target *target)
327 {
328         int retval = target_write_u32(target, FP_CTRL, 3);
329         if (retval != ERROR_OK)
330                 return retval;
331
332         /* check the fpb is actually enabled */
333         uint32_t fpctrl;
334         retval = target_read_u32(target, FP_CTRL, &fpctrl);
335         if (retval != ERROR_OK)
336                 return retval;
337
338         if (fpctrl & 1)
339                 return ERROR_OK;
340
341         return ERROR_FAIL;
342 }
343
344 static int cortex_m_endreset_event(struct target *target)
345 {
346         int retval;
347         uint32_t dcb_demcr;
348         struct cortex_m_common *cortex_m = target_to_cm(target);
349         struct armv7m_common *armv7m = &cortex_m->armv7m;
350         struct adiv5_dap *swjdp = cortex_m->armv7m.arm.dap;
351         struct cortex_m_fp_comparator *fp_list = cortex_m->fp_comparator_list;
352         struct cortex_m_dwt_comparator *dwt_list = cortex_m->dwt_comparator_list;
353
354         /* REVISIT The four debug monitor bits are currently ignored... */
355         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DEMCR, &dcb_demcr);
356         if (retval != ERROR_OK)
357                 return retval;
358         LOG_DEBUG("DCB_DEMCR = 0x%8.8" PRIx32 "", dcb_demcr);
359
360         /* this register is used for emulated dcc channel */
361         retval = mem_ap_write_u32(armv7m->debug_ap, DCB_DCRDR, 0);
362         if (retval != ERROR_OK)
363                 return retval;
364
365         /* Enable debug requests */
366         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DHCSR, &cortex_m->dcb_dhcsr);
367         if (retval != ERROR_OK)
368                 return retval;
369         if (!(cortex_m->dcb_dhcsr & C_DEBUGEN)) {
370                 retval = cortex_m_write_debug_halt_mask(target, 0, C_HALT | C_STEP | C_MASKINTS);
371                 if (retval != ERROR_OK)
372                         return retval;
373         }
374
375         /* Restore proper interrupt masking setting for running CPU. */
376         cortex_m_set_maskints_for_run(target);
377
378         /* Enable features controlled by ITM and DWT blocks, and catch only
379          * the vectors we were told to pay attention to.
380          *
381          * Target firmware is responsible for all fault handling policy
382          * choices *EXCEPT* explicitly scripted overrides like "vector_catch"
383          * or manual updates to the NVIC SHCSR and CCR registers.
384          */
385         retval = mem_ap_write_u32(armv7m->debug_ap, DCB_DEMCR, TRCENA | armv7m->demcr);
386         if (retval != ERROR_OK)
387                 return retval;
388
389         /* Paranoia: evidently some (early?) chips don't preserve all the
390          * debug state (including FPB, DWT, etc) across reset...
391          */
392
393         /* Enable FPB */
394         retval = cortex_m_enable_fpb(target);
395         if (retval != ERROR_OK) {
396                 LOG_ERROR("Failed to enable the FPB");
397                 return retval;
398         }
399
400         cortex_m->fpb_enabled = true;
401
402         /* Restore FPB registers */
403         for (unsigned int i = 0; i < cortex_m->fp_num_code + cortex_m->fp_num_lit; i++) {
404                 retval = target_write_u32(target, fp_list[i].fpcr_address, fp_list[i].fpcr_value);
405                 if (retval != ERROR_OK)
406                         return retval;
407         }
408
409         /* Restore DWT registers */
410         for (unsigned int i = 0; i < cortex_m->dwt_num_comp; i++) {
411                 retval = target_write_u32(target, dwt_list[i].dwt_comparator_address + 0,
412                                 dwt_list[i].comp);
413                 if (retval != ERROR_OK)
414                         return retval;
415                 retval = target_write_u32(target, dwt_list[i].dwt_comparator_address + 4,
416                                 dwt_list[i].mask);
417                 if (retval != ERROR_OK)
418                         return retval;
419                 retval = target_write_u32(target, dwt_list[i].dwt_comparator_address + 8,
420                                 dwt_list[i].function);
421                 if (retval != ERROR_OK)
422                         return retval;
423         }
424         retval = dap_run(swjdp);
425         if (retval != ERROR_OK)
426                 return retval;
427
428         register_cache_invalidate(armv7m->arm.core_cache);
429
430         /* make sure we have latest dhcsr flags */
431         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DHCSR, &cortex_m->dcb_dhcsr);
432
433         return retval;
434 }
435
436 static int cortex_m_examine_debug_reason(struct target *target)
437 {
438         struct cortex_m_common *cortex_m = target_to_cm(target);
439
440         /* THIS IS NOT GOOD, TODO - better logic for detection of debug state reason
441          * only check the debug reason if we don't know it already */
442
443         if ((target->debug_reason != DBG_REASON_DBGRQ)
444                 && (target->debug_reason != DBG_REASON_SINGLESTEP)) {
445                 if (cortex_m->nvic_dfsr & DFSR_BKPT) {
446                         target->debug_reason = DBG_REASON_BREAKPOINT;
447                         if (cortex_m->nvic_dfsr & DFSR_DWTTRAP)
448                                 target->debug_reason = DBG_REASON_WPTANDBKPT;
449                 } else if (cortex_m->nvic_dfsr & DFSR_DWTTRAP)
450                         target->debug_reason = DBG_REASON_WATCHPOINT;
451                 else if (cortex_m->nvic_dfsr & DFSR_VCATCH)
452                         target->debug_reason = DBG_REASON_BREAKPOINT;
453                 else if (cortex_m->nvic_dfsr & DFSR_EXTERNAL)
454                         target->debug_reason = DBG_REASON_DBGRQ;
455                 else    /* HALTED */
456                         target->debug_reason = DBG_REASON_UNDEFINED;
457         }
458
459         return ERROR_OK;
460 }
461
462 static int cortex_m_examine_exception_reason(struct target *target)
463 {
464         uint32_t shcsr = 0, except_sr = 0, cfsr = -1, except_ar = -1;
465         struct armv7m_common *armv7m = target_to_armv7m(target);
466         struct adiv5_dap *swjdp = armv7m->arm.dap;
467         int retval;
468
469         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_SHCSR, &shcsr);
470         if (retval != ERROR_OK)
471                 return retval;
472         switch (armv7m->exception_number) {
473                 case 2: /* NMI */
474                         break;
475                 case 3: /* Hard Fault */
476                         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, NVIC_HFSR, &except_sr);
477                         if (retval != ERROR_OK)
478                                 return retval;
479                         if (except_sr & 0x40000000) {
480                                 retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_CFSR, &cfsr);
481                                 if (retval != ERROR_OK)
482                                         return retval;
483                         }
484                         break;
485                 case 4: /* Memory Management */
486                         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_CFSR, &except_sr);
487                         if (retval != ERROR_OK)
488                                 return retval;
489                         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_MMFAR, &except_ar);
490                         if (retval != ERROR_OK)
491                                 return retval;
492                         break;
493                 case 5: /* Bus Fault */
494                         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_CFSR, &except_sr);
495                         if (retval != ERROR_OK)
496                                 return retval;
497                         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_BFAR, &except_ar);
498                         if (retval != ERROR_OK)
499                                 return retval;
500                         break;
501                 case 6: /* Usage Fault */
502                         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_CFSR, &except_sr);
503                         if (retval != ERROR_OK)
504                                 return retval;
505                         break;
506                 case 7: /* Secure Fault */
507                         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_SFSR, &except_sr);
508                         if (retval != ERROR_OK)
509                                 return retval;
510                         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_SFAR, &except_ar);
511                         if (retval != ERROR_OK)
512                                 return retval;
513                         break;
514                 case 11:        /* SVCall */
515                         break;
516                 case 12:        /* Debug Monitor */
517                         retval = mem_ap_read_u32(armv7m->debug_ap, NVIC_DFSR, &except_sr);
518                         if (retval != ERROR_OK)
519                                 return retval;
520                         break;
521                 case 14:        /* PendSV */
522                         break;
523                 case 15:        /* SysTick */
524                         break;
525                 default:
526                         except_sr = 0;
527                         break;
528         }
529         retval = dap_run(swjdp);
530         if (retval == ERROR_OK)
531                 LOG_DEBUG("%s SHCSR 0x%" PRIx32 ", SR 0x%" PRIx32
532                         ", CFSR 0x%" PRIx32 ", AR 0x%" PRIx32,
533                         armv7m_exception_string(armv7m->exception_number),
534                         shcsr, except_sr, cfsr, except_ar);
535         return retval;
536 }
537
538 static int cortex_m_debug_entry(struct target *target)
539 {
540         int i;
541         uint32_t xPSR;
542         int retval;
543         struct cortex_m_common *cortex_m = target_to_cm(target);
544         struct armv7m_common *armv7m = &cortex_m->armv7m;
545         struct arm *arm = &armv7m->arm;
546         struct reg *r;
547
548         LOG_DEBUG(" ");
549
550         /* Do this really early to minimize the window where the MASKINTS erratum
551          * can pile up pending interrupts. */
552         cortex_m_set_maskints_for_halt(target);
553
554         cortex_m_clear_halt(target);
555         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DHCSR, &cortex_m->dcb_dhcsr);
556         if (retval != ERROR_OK)
557                 return retval;
558
559         retval = armv7m->examine_debug_reason(target);
560         if (retval != ERROR_OK)
561                 return retval;
562
563         /* examine PE security state */
564         bool secure_state = false;
565         if (armv7m->arm.arch == ARM_ARCH_V8M) {
566                 uint32_t dscsr;
567
568                 retval = mem_ap_read_u32(armv7m->debug_ap, DCB_DSCSR, &dscsr);
569                 if (retval != ERROR_OK)
570                         return retval;
571
572                 secure_state = (dscsr & DSCSR_CDS) == DSCSR_CDS;
573         }
574
575         /* Examine target state and mode
576          * First load register accessible through core debug port */
577         int num_regs = arm->core_cache->num_regs;
578
579         for (i = 0; i < num_regs; i++) {
580                 r = &armv7m->arm.core_cache->reg_list[i];
581                 if (r->exist && !r->valid)
582                         arm->read_core_reg(target, r, i, ARM_MODE_ANY);
583         }
584
585         r = arm->cpsr;
586         xPSR = buf_get_u32(r->value, 0, 32);
587
588         /* Are we in an exception handler */
589         if (xPSR & 0x1FF) {
590                 armv7m->exception_number = (xPSR & 0x1FF);
591
592                 arm->core_mode = ARM_MODE_HANDLER;
593                 arm->map = armv7m_msp_reg_map;
594         } else {
595                 unsigned control = buf_get_u32(arm->core_cache
596                                 ->reg_list[ARMV7M_CONTROL].value, 0, 3);
597
598                 /* is this thread privileged? */
599                 arm->core_mode = control & 1
600                         ? ARM_MODE_USER_THREAD
601                         : ARM_MODE_THREAD;
602
603                 /* which stack is it using? */
604                 if (control & 2)
605                         arm->map = armv7m_psp_reg_map;
606                 else
607                         arm->map = armv7m_msp_reg_map;
608
609                 armv7m->exception_number = 0;
610         }
611
612         if (armv7m->exception_number)
613                 cortex_m_examine_exception_reason(target);
614
615         LOG_DEBUG("entered debug state in core mode: %s at PC 0x%" PRIx32 ", cpu in %s state, target->state: %s",
616                 arm_mode_name(arm->core_mode),
617                 buf_get_u32(arm->pc->value, 0, 32),
618                 secure_state ? "Secure" : "Non-Secure",
619                 target_state_name(target));
620
621         if (armv7m->post_debug_entry) {
622                 retval = armv7m->post_debug_entry(target);
623                 if (retval != ERROR_OK)
624                         return retval;
625         }
626
627         return ERROR_OK;
628 }
629
630 static int cortex_m_poll(struct target *target)
631 {
632         int detected_failure = ERROR_OK;
633         int retval = ERROR_OK;
634         enum target_state prev_target_state = target->state;
635         struct cortex_m_common *cortex_m = target_to_cm(target);
636         struct armv7m_common *armv7m = &cortex_m->armv7m;
637
638         /* Read from Debug Halting Control and Status Register */
639         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DHCSR, &cortex_m->dcb_dhcsr);
640         if (retval != ERROR_OK) {
641                 target->state = TARGET_UNKNOWN;
642                 return retval;
643         }
644
645         /* Recover from lockup.  See ARMv7-M architecture spec,
646          * section B1.5.15 "Unrecoverable exception cases".
647          */
648         if (cortex_m->dcb_dhcsr & S_LOCKUP) {
649                 LOG_ERROR("%s -- clearing lockup after double fault",
650                         target_name(target));
651                 cortex_m_write_debug_halt_mask(target, C_HALT, 0);
652                 target->debug_reason = DBG_REASON_DBGRQ;
653
654                 /* We have to execute the rest (the "finally" equivalent, but
655                  * still throw this exception again).
656                  */
657                 detected_failure = ERROR_FAIL;
658
659                 /* refresh status bits */
660                 retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DHCSR, &cortex_m->dcb_dhcsr);
661                 if (retval != ERROR_OK)
662                         return retval;
663         }
664
665         if (cortex_m->dcb_dhcsr & S_RESET_ST) {
666                 if (target->state != TARGET_RESET) {
667                         target->state = TARGET_RESET;
668                         LOG_INFO("%s: external reset detected", target_name(target));
669                 }
670                 return ERROR_OK;
671         }
672
673         if (target->state == TARGET_RESET) {
674                 /* Cannot switch context while running so endreset is
675                  * called with target->state == TARGET_RESET
676                  */
677                 LOG_DEBUG("Exit from reset with dcb_dhcsr 0x%" PRIx32,
678                         cortex_m->dcb_dhcsr);
679                 retval = cortex_m_endreset_event(target);
680                 if (retval != ERROR_OK) {
681                         target->state = TARGET_UNKNOWN;
682                         return retval;
683                 }
684                 target->state = TARGET_RUNNING;
685                 prev_target_state = TARGET_RUNNING;
686         }
687
688         if (cortex_m->dcb_dhcsr & S_HALT) {
689                 target->state = TARGET_HALTED;
690
691                 if ((prev_target_state == TARGET_RUNNING) || (prev_target_state == TARGET_RESET)) {
692                         retval = cortex_m_debug_entry(target);
693                         if (retval != ERROR_OK)
694                                 return retval;
695
696                         if (arm_semihosting(target, &retval) != 0)
697                                 return retval;
698
699                         target_call_event_callbacks(target, TARGET_EVENT_HALTED);
700                 }
701                 if (prev_target_state == TARGET_DEBUG_RUNNING) {
702                         LOG_DEBUG(" ");
703                         retval = cortex_m_debug_entry(target);
704                         if (retval != ERROR_OK)
705                                 return retval;
706
707                         target_call_event_callbacks(target, TARGET_EVENT_DEBUG_HALTED);
708                 }
709         }
710
711         if (target->state == TARGET_UNKNOWN) {
712                 /* check if processor is retiring instructions or sleeping */
713                 if (cortex_m->dcb_dhcsr & S_RETIRE_ST || cortex_m->dcb_dhcsr & S_SLEEP) {
714                         target->state = TARGET_RUNNING;
715                         retval = ERROR_OK;
716                 }
717         }
718
719         /* Check that target is truly halted, since the target could be resumed externally */
720         if ((prev_target_state == TARGET_HALTED) && !(cortex_m->dcb_dhcsr & S_HALT)) {
721                 /* registers are now invalid */
722                 register_cache_invalidate(armv7m->arm.core_cache);
723
724                 target->state = TARGET_RUNNING;
725                 LOG_WARNING("%s: external resume detected", target_name(target));
726                 target_call_event_callbacks(target, TARGET_EVENT_RESUMED);
727                 retval = ERROR_OK;
728         }
729
730         /* Did we detect a failure condition that we cleared? */
731         if (detected_failure != ERROR_OK)
732                 retval = detected_failure;
733         return retval;
734 }
735
736 static int cortex_m_halt(struct target *target)
737 {
738         LOG_DEBUG("target->state: %s",
739                 target_state_name(target));
740
741         if (target->state == TARGET_HALTED) {
742                 LOG_DEBUG("target was already halted");
743                 return ERROR_OK;
744         }
745
746         if (target->state == TARGET_UNKNOWN)
747                 LOG_WARNING("target was in unknown state when halt was requested");
748
749         if (target->state == TARGET_RESET) {
750                 if ((jtag_get_reset_config() & RESET_SRST_PULLS_TRST) && jtag_get_srst()) {
751                         LOG_ERROR("can't request a halt while in reset if nSRST pulls nTRST");
752                         return ERROR_TARGET_FAILURE;
753                 } else {
754                         /* we came here in a reset_halt or reset_init sequence
755                          * debug entry was already prepared in cortex_m3_assert_reset()
756                          */
757                         target->debug_reason = DBG_REASON_DBGRQ;
758
759                         return ERROR_OK;
760                 }
761         }
762
763         /* Write to Debug Halting Control and Status Register */
764         cortex_m_write_debug_halt_mask(target, C_HALT, 0);
765
766         /* Do this really early to minimize the window where the MASKINTS erratum
767          * can pile up pending interrupts. */
768         cortex_m_set_maskints_for_halt(target);
769
770         target->debug_reason = DBG_REASON_DBGRQ;
771
772         return ERROR_OK;
773 }
774
775 static int cortex_m_soft_reset_halt(struct target *target)
776 {
777         struct cortex_m_common *cortex_m = target_to_cm(target);
778         struct armv7m_common *armv7m = &cortex_m->armv7m;
779         int retval, timeout = 0;
780
781         /* on single cortex_m MCU soft_reset_halt should be avoided as same functionality
782          * can be obtained by using 'reset halt' and 'cortex_m reset_config vectreset'.
783          * As this reset only uses VC_CORERESET it would only ever reset the cortex_m
784          * core, not the peripherals */
785         LOG_DEBUG("soft_reset_halt is discouraged, please use 'reset halt' instead.");
786
787         if (!cortex_m->vectreset_supported) {
788                 LOG_ERROR("VECTRESET is not supported on this Cortex-M core");
789                 return ERROR_FAIL;
790         }
791
792         /* Set C_DEBUGEN */
793         retval = cortex_m_write_debug_halt_mask(target, 0, C_STEP | C_MASKINTS);
794         if (retval != ERROR_OK)
795                 return retval;
796
797         /* Enter debug state on reset; restore DEMCR in endreset_event() */
798         retval = mem_ap_write_u32(armv7m->debug_ap, DCB_DEMCR,
799                         TRCENA | VC_HARDERR | VC_BUSERR | VC_CORERESET);
800         if (retval != ERROR_OK)
801                 return retval;
802
803         /* Request a core-only reset */
804         retval = mem_ap_write_atomic_u32(armv7m->debug_ap, NVIC_AIRCR,
805                         AIRCR_VECTKEY | AIRCR_VECTRESET);
806         if (retval != ERROR_OK)
807                 return retval;
808         target->state = TARGET_RESET;
809
810         /* registers are now invalid */
811         register_cache_invalidate(cortex_m->armv7m.arm.core_cache);
812
813         while (timeout < 100) {
814                 retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DHCSR, &cortex_m->dcb_dhcsr);
815                 if (retval == ERROR_OK) {
816                         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, NVIC_DFSR,
817                                         &cortex_m->nvic_dfsr);
818                         if (retval != ERROR_OK)
819                                 return retval;
820                         if ((cortex_m->dcb_dhcsr & S_HALT)
821                                 && (cortex_m->nvic_dfsr & DFSR_VCATCH)) {
822                                 LOG_DEBUG("system reset-halted, DHCSR 0x%08" PRIx32 ", DFSR 0x%08" PRIx32,
823                                         cortex_m->dcb_dhcsr, cortex_m->nvic_dfsr);
824                                 cortex_m_poll(target);
825                                 /* FIXME restore user's vector catch config */
826                                 return ERROR_OK;
827                         } else
828                                 LOG_DEBUG("waiting for system reset-halt, "
829                                         "DHCSR 0x%08" PRIx32 ", %d ms",
830                                         cortex_m->dcb_dhcsr, timeout);
831                 }
832                 timeout++;
833                 alive_sleep(1);
834         }
835
836         return ERROR_OK;
837 }
838
839 void cortex_m_enable_breakpoints(struct target *target)
840 {
841         struct breakpoint *breakpoint = target->breakpoints;
842
843         /* set any pending breakpoints */
844         while (breakpoint) {
845                 if (!breakpoint->set)
846                         cortex_m_set_breakpoint(target, breakpoint);
847                 breakpoint = breakpoint->next;
848         }
849 }
850
851 static int cortex_m_resume(struct target *target, int current,
852         target_addr_t address, int handle_breakpoints, int debug_execution)
853 {
854         struct armv7m_common *armv7m = target_to_armv7m(target);
855         struct breakpoint *breakpoint = NULL;
856         uint32_t resume_pc;
857         struct reg *r;
858
859         if (target->state != TARGET_HALTED) {
860                 LOG_WARNING("target not halted");
861                 return ERROR_TARGET_NOT_HALTED;
862         }
863
864         if (!debug_execution) {
865                 target_free_all_working_areas(target);
866                 cortex_m_enable_breakpoints(target);
867                 cortex_m_enable_watchpoints(target);
868         }
869
870         if (debug_execution) {
871                 r = armv7m->arm.core_cache->reg_list + ARMV7M_PRIMASK;
872
873                 /* Disable interrupts */
874                 /* We disable interrupts in the PRIMASK register instead of
875                  * masking with C_MASKINTS.  This is probably the same issue
876                  * as Cortex-M3 Erratum 377493 (fixed in r1p0):  C_MASKINTS
877                  * in parallel with disabled interrupts can cause local faults
878                  * to not be taken.
879                  *
880                  * This breaks non-debug (application) execution if not
881                  * called from armv7m_start_algorithm() which saves registers.
882                  */
883                 buf_set_u32(r->value, 0, 1, 1);
884                 r->dirty = true;
885                 r->valid = true;
886
887                 /* Make sure we are in Thumb mode, set xPSR.T bit */
888                 /* armv7m_start_algorithm() initializes entire xPSR register.
889                  * This duplicity handles the case when cortex_m_resume()
890                  * is used with the debug_execution flag directly,
891                  * not called through armv7m_start_algorithm().
892                  */
893                 r = armv7m->arm.cpsr;
894                 buf_set_u32(r->value, 24, 1, 1);
895                 r->dirty = true;
896                 r->valid = true;
897         }
898
899         /* current = 1: continue on current pc, otherwise continue at <address> */
900         r = armv7m->arm.pc;
901         if (!current) {
902                 buf_set_u32(r->value, 0, 32, address);
903                 r->dirty = true;
904                 r->valid = true;
905         }
906
907         /* if we halted last time due to a bkpt instruction
908          * then we have to manually step over it, otherwise
909          * the core will break again */
910
911         if (!breakpoint_find(target, buf_get_u32(r->value, 0, 32))
912                 && !debug_execution)
913                 armv7m_maybe_skip_bkpt_inst(target, NULL);
914
915         resume_pc = buf_get_u32(r->value, 0, 32);
916
917         armv7m_restore_context(target);
918
919         /* the front-end may request us not to handle breakpoints */
920         if (handle_breakpoints) {
921                 /* Single step past breakpoint at current address */
922                 breakpoint = breakpoint_find(target, resume_pc);
923                 if (breakpoint) {
924                         LOG_DEBUG("unset breakpoint at " TARGET_ADDR_FMT " (ID: %" PRIu32 ")",
925                                 breakpoint->address,
926                                 breakpoint->unique_id);
927                         cortex_m_unset_breakpoint(target, breakpoint);
928                         cortex_m_single_step_core(target);
929                         cortex_m_set_breakpoint(target, breakpoint);
930                 }
931         }
932
933         /* Restart core */
934         cortex_m_set_maskints_for_run(target);
935         cortex_m_write_debug_halt_mask(target, 0, C_HALT);
936
937         target->debug_reason = DBG_REASON_NOTHALTED;
938
939         /* registers are now invalid */
940         register_cache_invalidate(armv7m->arm.core_cache);
941
942         if (!debug_execution) {
943                 target->state = TARGET_RUNNING;
944                 target_call_event_callbacks(target, TARGET_EVENT_RESUMED);
945                 LOG_DEBUG("target resumed at 0x%" PRIx32 "", resume_pc);
946         } else {
947                 target->state = TARGET_DEBUG_RUNNING;
948                 target_call_event_callbacks(target, TARGET_EVENT_DEBUG_RESUMED);
949                 LOG_DEBUG("target debug resumed at 0x%" PRIx32 "", resume_pc);
950         }
951
952         return ERROR_OK;
953 }
954
955 /* int irqstepcount = 0; */
956 static int cortex_m_step(struct target *target, int current,
957         target_addr_t address, int handle_breakpoints)
958 {
959         struct cortex_m_common *cortex_m = target_to_cm(target);
960         struct armv7m_common *armv7m = &cortex_m->armv7m;
961         struct breakpoint *breakpoint = NULL;
962         struct reg *pc = armv7m->arm.pc;
963         bool bkpt_inst_found = false;
964         int retval;
965         bool isr_timed_out = false;
966
967         if (target->state != TARGET_HALTED) {
968                 LOG_WARNING("target not halted");
969                 return ERROR_TARGET_NOT_HALTED;
970         }
971
972         /* current = 1: continue on current pc, otherwise continue at <address> */
973         if (!current) {
974                 buf_set_u32(pc->value, 0, 32, address);
975                 pc->dirty = true;
976                 pc->valid = true;
977         }
978
979         uint32_t pc_value = buf_get_u32(pc->value, 0, 32);
980
981         /* the front-end may request us not to handle breakpoints */
982         if (handle_breakpoints) {
983                 breakpoint = breakpoint_find(target, pc_value);
984                 if (breakpoint)
985                         cortex_m_unset_breakpoint(target, breakpoint);
986         }
987
988         armv7m_maybe_skip_bkpt_inst(target, &bkpt_inst_found);
989
990         target->debug_reason = DBG_REASON_SINGLESTEP;
991
992         armv7m_restore_context(target);
993
994         target_call_event_callbacks(target, TARGET_EVENT_RESUMED);
995
996         /* if no bkpt instruction is found at pc then we can perform
997          * a normal step, otherwise we have to manually step over the bkpt
998          * instruction - as such simulate a step */
999         if (bkpt_inst_found == false) {
1000                 if (cortex_m->isrmasking_mode != CORTEX_M_ISRMASK_AUTO) {
1001                         /* Automatic ISR masking mode off: Just step over the next
1002                          * instruction, with interrupts on or off as appropriate. */
1003                         cortex_m_set_maskints_for_step(target);
1004                         cortex_m_write_debug_halt_mask(target, C_STEP, C_HALT);
1005                 } else {
1006                         /* Process interrupts during stepping in a way they don't interfere
1007                          * debugging.
1008                          *
1009                          * Principle:
1010                          *
1011                          * Set a temporary break point at the current pc and let the core run
1012                          * with interrupts enabled. Pending interrupts get served and we run
1013                          * into the breakpoint again afterwards. Then we step over the next
1014                          * instruction with interrupts disabled.
1015                          *
1016                          * If the pending interrupts don't complete within time, we leave the
1017                          * core running. This may happen if the interrupts trigger faster
1018                          * than the core can process them or the handler doesn't return.
1019                          *
1020                          * If no more breakpoints are available we simply do a step with
1021                          * interrupts enabled.
1022                          *
1023                          */
1024
1025                         /* 2012-09-29 ph
1026                          *
1027                          * If a break point is already set on the lower half word then a break point on
1028                          * the upper half word will not break again when the core is restarted. So we
1029                          * just step over the instruction with interrupts disabled.
1030                          *
1031                          * The documentation has no information about this, it was found by observation
1032                          * on STM32F1 and STM32F2. Proper explanation welcome. STM32F0 doesn't seem to
1033                          * suffer from this problem.
1034                          *
1035                          * To add some confusion: pc_value has bit 0 always set, while the breakpoint
1036                          * address has it always cleared. The former is done to indicate thumb mode
1037                          * to gdb.
1038                          *
1039                          */
1040                         if ((pc_value & 0x02) && breakpoint_find(target, pc_value & ~0x03)) {
1041                                 LOG_DEBUG("Stepping over next instruction with interrupts disabled");
1042                                 cortex_m_write_debug_halt_mask(target, C_HALT | C_MASKINTS, 0);
1043                                 cortex_m_write_debug_halt_mask(target, C_STEP, C_HALT);
1044                                 /* Re-enable interrupts if appropriate */
1045                                 cortex_m_write_debug_halt_mask(target, C_HALT, 0);
1046                                 cortex_m_set_maskints_for_halt(target);
1047                         } else {
1048
1049                                 /* Set a temporary break point */
1050                                 if (breakpoint) {
1051                                         retval = cortex_m_set_breakpoint(target, breakpoint);
1052                                 } else {
1053                                         enum breakpoint_type type = BKPT_HARD;
1054                                         if (cortex_m->fp_rev == 0 && pc_value > 0x1FFFFFFF) {
1055                                                 /* FPB rev.1 cannot handle such addr, try BKPT instr */
1056                                                 type = BKPT_SOFT;
1057                                         }
1058                                         retval = breakpoint_add(target, pc_value, 2, type);
1059                                 }
1060
1061                                 bool tmp_bp_set = (retval == ERROR_OK);
1062
1063                                 /* No more breakpoints left, just do a step */
1064                                 if (!tmp_bp_set) {
1065                                         cortex_m_set_maskints_for_step(target);
1066                                         cortex_m_write_debug_halt_mask(target, C_STEP, C_HALT);
1067                                         /* Re-enable interrupts if appropriate */
1068                                         cortex_m_write_debug_halt_mask(target, C_HALT, 0);
1069                                         cortex_m_set_maskints_for_halt(target);
1070                                 } else {
1071                                         /* Start the core */
1072                                         LOG_DEBUG("Starting core to serve pending interrupts");
1073                                         int64_t t_start = timeval_ms();
1074                                         cortex_m_set_maskints_for_run(target);
1075                                         cortex_m_write_debug_halt_mask(target, 0, C_HALT | C_STEP);
1076
1077                                         /* Wait for pending handlers to complete or timeout */
1078                                         do {
1079                                                 retval = mem_ap_read_atomic_u32(armv7m->debug_ap,
1080                                                                 DCB_DHCSR,
1081                                                                 &cortex_m->dcb_dhcsr);
1082                                                 if (retval != ERROR_OK) {
1083                                                         target->state = TARGET_UNKNOWN;
1084                                                         return retval;
1085                                                 }
1086                                                 isr_timed_out = ((timeval_ms() - t_start) > 500);
1087                                         } while (!((cortex_m->dcb_dhcsr & S_HALT) || isr_timed_out));
1088
1089                                         /* only remove breakpoint if we created it */
1090                                         if (breakpoint)
1091                                                 cortex_m_unset_breakpoint(target, breakpoint);
1092                                         else {
1093                                                 /* Remove the temporary breakpoint */
1094                                                 breakpoint_remove(target, pc_value);
1095                                         }
1096
1097                                         if (isr_timed_out) {
1098                                                 LOG_DEBUG("Interrupt handlers didn't complete within time, "
1099                                                         "leaving target running");
1100                                         } else {
1101                                                 /* Step over next instruction with interrupts disabled */
1102                                                 cortex_m_set_maskints_for_step(target);
1103                                                 cortex_m_write_debug_halt_mask(target,
1104                                                         C_HALT | C_MASKINTS,
1105                                                         0);
1106                                                 cortex_m_write_debug_halt_mask(target, C_STEP, C_HALT);
1107                                                 /* Re-enable interrupts if appropriate */
1108                                                 cortex_m_write_debug_halt_mask(target, C_HALT, 0);
1109                                                 cortex_m_set_maskints_for_halt(target);
1110                                         }
1111                                 }
1112                         }
1113                 }
1114         }
1115
1116         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DHCSR, &cortex_m->dcb_dhcsr);
1117         if (retval != ERROR_OK)
1118                 return retval;
1119
1120         /* registers are now invalid */
1121         register_cache_invalidate(armv7m->arm.core_cache);
1122
1123         if (breakpoint)
1124                 cortex_m_set_breakpoint(target, breakpoint);
1125
1126         if (isr_timed_out) {
1127                 /* Leave the core running. The user has to stop execution manually. */
1128                 target->debug_reason = DBG_REASON_NOTHALTED;
1129                 target->state = TARGET_RUNNING;
1130                 return ERROR_OK;
1131         }
1132
1133         LOG_DEBUG("target stepped dcb_dhcsr = 0x%" PRIx32
1134                 " nvic_icsr = 0x%" PRIx32,
1135                 cortex_m->dcb_dhcsr, cortex_m->nvic_icsr);
1136
1137         retval = cortex_m_debug_entry(target);
1138         if (retval != ERROR_OK)
1139                 return retval;
1140         target_call_event_callbacks(target, TARGET_EVENT_HALTED);
1141
1142         LOG_DEBUG("target stepped dcb_dhcsr = 0x%" PRIx32
1143                 " nvic_icsr = 0x%" PRIx32,
1144                 cortex_m->dcb_dhcsr, cortex_m->nvic_icsr);
1145
1146         return ERROR_OK;
1147 }
1148
1149 static int cortex_m_assert_reset(struct target *target)
1150 {
1151         struct cortex_m_common *cortex_m = target_to_cm(target);
1152         struct armv7m_common *armv7m = &cortex_m->armv7m;
1153         enum cortex_m_soft_reset_config reset_config = cortex_m->soft_reset_config;
1154
1155         LOG_DEBUG("target->state: %s",
1156                 target_state_name(target));
1157
1158         enum reset_types jtag_reset_config = jtag_get_reset_config();
1159
1160         if (target_has_event_action(target, TARGET_EVENT_RESET_ASSERT)) {
1161                 /* allow scripts to override the reset event */
1162
1163                 target_handle_event(target, TARGET_EVENT_RESET_ASSERT);
1164                 register_cache_invalidate(cortex_m->armv7m.arm.core_cache);
1165                 target->state = TARGET_RESET;
1166
1167                 return ERROR_OK;
1168         }
1169
1170         /* some cores support connecting while srst is asserted
1171          * use that mode is it has been configured */
1172
1173         bool srst_asserted = false;
1174
1175         if (!target_was_examined(target)) {
1176                 if (jtag_reset_config & RESET_HAS_SRST) {
1177                         adapter_assert_reset();
1178                         if (target->reset_halt)
1179                                 LOG_ERROR("Target not examined, will not halt after reset!");
1180                         return ERROR_OK;
1181                 } else {
1182                         LOG_ERROR("Target not examined, reset NOT asserted!");
1183                         return ERROR_FAIL;
1184                 }
1185         }
1186
1187         if ((jtag_reset_config & RESET_HAS_SRST) &&
1188             (jtag_reset_config & RESET_SRST_NO_GATING)) {
1189                 adapter_assert_reset();
1190                 srst_asserted = true;
1191         }
1192
1193         /* Enable debug requests */
1194         int retval;
1195         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DHCSR, &cortex_m->dcb_dhcsr);
1196         /* Store important errors instead of failing and proceed to reset assert */
1197
1198         if (retval != ERROR_OK || !(cortex_m->dcb_dhcsr & C_DEBUGEN))
1199                 retval = cortex_m_write_debug_halt_mask(target, 0, C_HALT | C_STEP | C_MASKINTS);
1200
1201         /* If the processor is sleeping in a WFI or WFE instruction, the
1202          * C_HALT bit must be asserted to regain control */
1203         if (retval == ERROR_OK && (cortex_m->dcb_dhcsr & S_SLEEP))
1204                 retval = cortex_m_write_debug_halt_mask(target, C_HALT, 0);
1205
1206         mem_ap_write_u32(armv7m->debug_ap, DCB_DCRDR, 0);
1207         /* Ignore less important errors */
1208
1209         if (!target->reset_halt) {
1210                 /* Set/Clear C_MASKINTS in a separate operation */
1211                 cortex_m_set_maskints_for_run(target);
1212
1213                 /* clear any debug flags before resuming */
1214                 cortex_m_clear_halt(target);
1215
1216                 /* clear C_HALT in dhcsr reg */
1217                 cortex_m_write_debug_halt_mask(target, 0, C_HALT);
1218         } else {
1219                 /* Halt in debug on reset; endreset_event() restores DEMCR.
1220                  *
1221                  * REVISIT catching BUSERR presumably helps to defend against
1222                  * bad vector table entries.  Should this include MMERR or
1223                  * other flags too?
1224                  */
1225                 int retval2;
1226                 retval2 = mem_ap_write_atomic_u32(armv7m->debug_ap, DCB_DEMCR,
1227                                 TRCENA | VC_HARDERR | VC_BUSERR | VC_CORERESET);
1228                 if (retval != ERROR_OK || retval2 != ERROR_OK)
1229                         LOG_INFO("AP write error, reset will not halt");
1230         }
1231
1232         if (jtag_reset_config & RESET_HAS_SRST) {
1233                 /* default to asserting srst */
1234                 if (!srst_asserted)
1235                         adapter_assert_reset();
1236
1237                 /* srst is asserted, ignore AP access errors */
1238                 retval = ERROR_OK;
1239         } else {
1240                 /* Use a standard Cortex-M3 software reset mechanism.
1241                  * We default to using VECTRESET as it is supported on all current cores
1242                  * (except Cortex-M0, M0+ and M1 which support SYSRESETREQ only!)
1243                  * This has the disadvantage of not resetting the peripherals, so a
1244                  * reset-init event handler is needed to perform any peripheral resets.
1245                  */
1246                 if (!cortex_m->vectreset_supported
1247                                 && reset_config == CORTEX_M_RESET_VECTRESET) {
1248                         reset_config = CORTEX_M_RESET_SYSRESETREQ;
1249                         LOG_WARNING("VECTRESET is not supported on this Cortex-M core, using SYSRESETREQ instead.");
1250                         LOG_WARNING("Set 'cortex_m reset_config sysresetreq'.");
1251                 }
1252
1253                 LOG_DEBUG("Using Cortex-M %s", (reset_config == CORTEX_M_RESET_SYSRESETREQ)
1254                         ? "SYSRESETREQ" : "VECTRESET");
1255
1256                 if (reset_config == CORTEX_M_RESET_VECTRESET) {
1257                         LOG_WARNING("Only resetting the Cortex-M core, use a reset-init event "
1258                                 "handler to reset any peripherals or configure hardware srst support.");
1259                 }
1260
1261                 int retval3;
1262                 retval3 = mem_ap_write_atomic_u32(armv7m->debug_ap, NVIC_AIRCR,
1263                                 AIRCR_VECTKEY | ((reset_config == CORTEX_M_RESET_SYSRESETREQ)
1264                                 ? AIRCR_SYSRESETREQ : AIRCR_VECTRESET));
1265                 if (retval3 != ERROR_OK)
1266                         LOG_DEBUG("Ignoring AP write error right after reset");
1267
1268                 retval3 = dap_dp_init_or_reconnect(armv7m->debug_ap->dap);
1269                 if (retval3 != ERROR_OK) {
1270                         LOG_ERROR("DP initialisation failed");
1271                         /* The error return value must not be propagated in this case.
1272                          * SYSRESETREQ or VECTRESET have been possibly triggered
1273                          * so reset processing should continue */
1274                 } else {
1275                         /* I do not know why this is necessary, but it
1276                          * fixes strange effects (step/resume cause NMI
1277                          * after reset) on LM3S6918 -- Michael Schwingen
1278                          */
1279                         uint32_t tmp;
1280                         mem_ap_read_atomic_u32(armv7m->debug_ap, NVIC_AIRCR, &tmp);
1281                 }
1282         }
1283
1284         target->state = TARGET_RESET;
1285         jtag_sleep(50000);
1286
1287         register_cache_invalidate(cortex_m->armv7m.arm.core_cache);
1288
1289         /* now return stored error code if any */
1290         if (retval != ERROR_OK)
1291                 return retval;
1292
1293         if (target->reset_halt) {
1294                 retval = target_halt(target);
1295                 if (retval != ERROR_OK)
1296                         return retval;
1297         }
1298
1299         return ERROR_OK;
1300 }
1301
1302 static int cortex_m_deassert_reset(struct target *target)
1303 {
1304         struct armv7m_common *armv7m = &target_to_cm(target)->armv7m;
1305
1306         LOG_DEBUG("target->state: %s",
1307                 target_state_name(target));
1308
1309         /* deassert reset lines */
1310         adapter_deassert_reset();
1311
1312         enum reset_types jtag_reset_config = jtag_get_reset_config();
1313
1314         if ((jtag_reset_config & RESET_HAS_SRST) &&
1315             !(jtag_reset_config & RESET_SRST_NO_GATING) &&
1316                 target_was_examined(target)) {
1317
1318                 int retval = dap_dp_init_or_reconnect(armv7m->debug_ap->dap);
1319                 if (retval != ERROR_OK) {
1320                         LOG_ERROR("DP initialisation failed");
1321                         return retval;
1322                 }
1323         }
1324
1325         return ERROR_OK;
1326 }
1327
1328 int cortex_m_set_breakpoint(struct target *target, struct breakpoint *breakpoint)
1329 {
1330         int retval;
1331         unsigned int fp_num = 0;
1332         struct cortex_m_common *cortex_m = target_to_cm(target);
1333         struct cortex_m_fp_comparator *comparator_list = cortex_m->fp_comparator_list;
1334
1335         if (breakpoint->set) {
1336                 LOG_WARNING("breakpoint (BPID: %" PRIu32 ") already set", breakpoint->unique_id);
1337                 return ERROR_OK;
1338         }
1339
1340         if (breakpoint->type == BKPT_HARD) {
1341                 uint32_t fpcr_value;
1342                 while (comparator_list[fp_num].used && (fp_num < cortex_m->fp_num_code))
1343                         fp_num++;
1344                 if (fp_num >= cortex_m->fp_num_code) {
1345                         LOG_ERROR("Can not find free FPB Comparator!");
1346                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1347                 }
1348                 breakpoint->set = fp_num + 1;
1349                 fpcr_value = breakpoint->address | 1;
1350                 if (cortex_m->fp_rev == 0) {
1351                         if (breakpoint->address > 0x1FFFFFFF) {
1352                                 LOG_ERROR("Cortex-M Flash Patch Breakpoint rev.1 cannot handle HW breakpoint above address 0x1FFFFFFE");
1353                                 return ERROR_FAIL;
1354                         }
1355                         uint32_t hilo;
1356                         hilo = (breakpoint->address & 0x2) ? FPCR_REPLACE_BKPT_HIGH : FPCR_REPLACE_BKPT_LOW;
1357                         fpcr_value = (fpcr_value & 0x1FFFFFFC) | hilo | 1;
1358                 } else if (cortex_m->fp_rev > 1) {
1359                         LOG_ERROR("Unhandled Cortex-M Flash Patch Breakpoint architecture revision");
1360                         return ERROR_FAIL;
1361                 }
1362                 comparator_list[fp_num].used = true;
1363                 comparator_list[fp_num].fpcr_value = fpcr_value;
1364                 target_write_u32(target, comparator_list[fp_num].fpcr_address,
1365                         comparator_list[fp_num].fpcr_value);
1366                 LOG_DEBUG("fpc_num %i fpcr_value 0x%" PRIx32 "",
1367                         fp_num,
1368                         comparator_list[fp_num].fpcr_value);
1369                 if (!cortex_m->fpb_enabled) {
1370                         LOG_DEBUG("FPB wasn't enabled, do it now");
1371                         retval = cortex_m_enable_fpb(target);
1372                         if (retval != ERROR_OK) {
1373                                 LOG_ERROR("Failed to enable the FPB");
1374                                 return retval;
1375                         }
1376
1377                         cortex_m->fpb_enabled = true;
1378                 }
1379         } else if (breakpoint->type == BKPT_SOFT) {
1380                 uint8_t code[4];
1381
1382                 /* NOTE: on ARMv6-M and ARMv7-M, BKPT(0xab) is used for
1383                  * semihosting; don't use that.  Otherwise the BKPT
1384                  * parameter is arbitrary.
1385                  */
1386                 buf_set_u32(code, 0, 32, ARMV5_T_BKPT(0x11));
1387                 retval = target_read_memory(target,
1388                                 breakpoint->address & 0xFFFFFFFE,
1389                                 breakpoint->length, 1,
1390                                 breakpoint->orig_instr);
1391                 if (retval != ERROR_OK)
1392                         return retval;
1393                 retval = target_write_memory(target,
1394                                 breakpoint->address & 0xFFFFFFFE,
1395                                 breakpoint->length, 1,
1396                                 code);
1397                 if (retval != ERROR_OK)
1398                         return retval;
1399                 breakpoint->set = true;
1400         }
1401
1402         LOG_DEBUG("BPID: %" PRIu32 ", Type: %d, Address: " TARGET_ADDR_FMT " Length: %d (set=%d)",
1403                 breakpoint->unique_id,
1404                 (int)(breakpoint->type),
1405                 breakpoint->address,
1406                 breakpoint->length,
1407                 breakpoint->set);
1408
1409         return ERROR_OK;
1410 }
1411
1412 int cortex_m_unset_breakpoint(struct target *target, struct breakpoint *breakpoint)
1413 {
1414         int retval;
1415         struct cortex_m_common *cortex_m = target_to_cm(target);
1416         struct cortex_m_fp_comparator *comparator_list = cortex_m->fp_comparator_list;
1417
1418         if (breakpoint->set <= 0) {
1419                 LOG_WARNING("breakpoint not set");
1420                 return ERROR_OK;
1421         }
1422
1423         LOG_DEBUG("BPID: %" PRIu32 ", Type: %d, Address: " TARGET_ADDR_FMT " Length: %d (set=%d)",
1424                 breakpoint->unique_id,
1425                 (int)(breakpoint->type),
1426                 breakpoint->address,
1427                 breakpoint->length,
1428                 breakpoint->set);
1429
1430         if (breakpoint->type == BKPT_HARD) {
1431                 unsigned int fp_num = breakpoint->set - 1;
1432                 if (fp_num >= cortex_m->fp_num_code) {
1433                         LOG_DEBUG("Invalid FP Comparator number in breakpoint");
1434                         return ERROR_OK;
1435                 }
1436                 comparator_list[fp_num].used = false;
1437                 comparator_list[fp_num].fpcr_value = 0;
1438                 target_write_u32(target, comparator_list[fp_num].fpcr_address,
1439                         comparator_list[fp_num].fpcr_value);
1440         } else {
1441                 /* restore original instruction (kept in target endianness) */
1442                 retval = target_write_memory(target, breakpoint->address & 0xFFFFFFFE,
1443                                         breakpoint->length, 1,
1444                                         breakpoint->orig_instr);
1445                 if (retval != ERROR_OK)
1446                         return retval;
1447         }
1448         breakpoint->set = false;
1449
1450         return ERROR_OK;
1451 }
1452
1453 int cortex_m_add_breakpoint(struct target *target, struct breakpoint *breakpoint)
1454 {
1455         if (breakpoint->length == 3) {
1456                 LOG_DEBUG("Using a two byte breakpoint for 32bit Thumb-2 request");
1457                 breakpoint->length = 2;
1458         }
1459
1460         if ((breakpoint->length != 2)) {
1461                 LOG_INFO("only breakpoints of two bytes length supported");
1462                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1463         }
1464
1465         return cortex_m_set_breakpoint(target, breakpoint);
1466 }
1467
1468 int cortex_m_remove_breakpoint(struct target *target, struct breakpoint *breakpoint)
1469 {
1470         if (!breakpoint->set)
1471                 return ERROR_OK;
1472
1473         return cortex_m_unset_breakpoint(target, breakpoint);
1474 }
1475
1476 static int cortex_m_set_watchpoint(struct target *target, struct watchpoint *watchpoint)
1477 {
1478         unsigned int dwt_num = 0;
1479         struct cortex_m_common *cortex_m = target_to_cm(target);
1480
1481         /* REVISIT Don't fully trust these "not used" records ... users
1482          * may set up breakpoints by hand, e.g. dual-address data value
1483          * watchpoint using comparator #1; comparator #0 matching cycle
1484          * count; send data trace info through ITM and TPIU; etc
1485          */
1486         struct cortex_m_dwt_comparator *comparator;
1487
1488         for (comparator = cortex_m->dwt_comparator_list;
1489                 comparator->used && dwt_num < cortex_m->dwt_num_comp;
1490                 comparator++, dwt_num++)
1491                 continue;
1492         if (dwt_num >= cortex_m->dwt_num_comp) {
1493                 LOG_ERROR("Can not find free DWT Comparator");
1494                 return ERROR_FAIL;
1495         }
1496         comparator->used = true;
1497         watchpoint->set = dwt_num + 1;
1498
1499         comparator->comp = watchpoint->address;
1500         target_write_u32(target, comparator->dwt_comparator_address + 0,
1501                 comparator->comp);
1502
1503         if ((cortex_m->dwt_devarch & 0x1FFFFF) != DWT_DEVARCH_ARMV8M) {
1504                 uint32_t mask = 0, temp;
1505
1506                 /* watchpoint params were validated earlier */
1507                 temp = watchpoint->length;
1508                 while (temp) {
1509                         temp >>= 1;
1510                         mask++;
1511                 }
1512                 mask--;
1513
1514                 comparator->mask = mask;
1515                 target_write_u32(target, comparator->dwt_comparator_address + 4,
1516                         comparator->mask);
1517
1518                 switch (watchpoint->rw) {
1519                 case WPT_READ:
1520                         comparator->function = 5;
1521                         break;
1522                 case WPT_WRITE:
1523                         comparator->function = 6;
1524                         break;
1525                 case WPT_ACCESS:
1526                         comparator->function = 7;
1527                         break;
1528                 }
1529         } else {
1530                 uint32_t data_size = watchpoint->length >> 1;
1531                 comparator->mask = (watchpoint->length >> 1) | 1;
1532
1533                 switch (watchpoint->rw) {
1534                 case WPT_ACCESS:
1535                         comparator->function = 4;
1536                         break;
1537                 case WPT_WRITE:
1538                         comparator->function = 5;
1539                         break;
1540                 case WPT_READ:
1541                         comparator->function = 6;
1542                         break;
1543                 }
1544                 comparator->function = comparator->function | (1 << 4) |
1545                                 (data_size << 10);
1546         }
1547
1548         target_write_u32(target, comparator->dwt_comparator_address + 8,
1549                 comparator->function);
1550
1551         LOG_DEBUG("Watchpoint (ID %d) DWT%d 0x%08x 0x%x 0x%05x",
1552                 watchpoint->unique_id, dwt_num,
1553                 (unsigned) comparator->comp,
1554                 (unsigned) comparator->mask,
1555                 (unsigned) comparator->function);
1556         return ERROR_OK;
1557 }
1558
1559 static int cortex_m_unset_watchpoint(struct target *target, struct watchpoint *watchpoint)
1560 {
1561         struct cortex_m_common *cortex_m = target_to_cm(target);
1562         struct cortex_m_dwt_comparator *comparator;
1563
1564         if (watchpoint->set <= 0) {
1565                 LOG_WARNING("watchpoint (wpid: %d) not set",
1566                         watchpoint->unique_id);
1567                 return ERROR_OK;
1568         }
1569
1570         unsigned int dwt_num = watchpoint->set - 1;
1571
1572         LOG_DEBUG("Watchpoint (ID %d) DWT%d address: 0x%08x clear",
1573                 watchpoint->unique_id, dwt_num,
1574                 (unsigned) watchpoint->address);
1575
1576         if (dwt_num >= cortex_m->dwt_num_comp) {
1577                 LOG_DEBUG("Invalid DWT Comparator number in watchpoint");
1578                 return ERROR_OK;
1579         }
1580
1581         comparator = cortex_m->dwt_comparator_list + dwt_num;
1582         comparator->used = false;
1583         comparator->function = 0;
1584         target_write_u32(target, comparator->dwt_comparator_address + 8,
1585                 comparator->function);
1586
1587         watchpoint->set = false;
1588
1589         return ERROR_OK;
1590 }
1591
1592 int cortex_m_add_watchpoint(struct target *target, struct watchpoint *watchpoint)
1593 {
1594         struct cortex_m_common *cortex_m = target_to_cm(target);
1595
1596         if (cortex_m->dwt_comp_available < 1) {
1597                 LOG_DEBUG("no comparators?");
1598                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1599         }
1600
1601         /* hardware doesn't support data value masking */
1602         if (watchpoint->mask != ~(uint32_t)0) {
1603                 LOG_DEBUG("watchpoint value masks not supported");
1604                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1605         }
1606
1607         /* hardware allows address masks of up to 32K */
1608         unsigned mask;
1609
1610         for (mask = 0; mask < 16; mask++) {
1611                 if ((1u << mask) == watchpoint->length)
1612                         break;
1613         }
1614         if (mask == 16) {
1615                 LOG_DEBUG("unsupported watchpoint length");
1616                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1617         }
1618         if (watchpoint->address & ((1 << mask) - 1)) {
1619                 LOG_DEBUG("watchpoint address is unaligned");
1620                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1621         }
1622
1623         /* Caller doesn't seem to be able to describe watching for data
1624          * values of zero; that flags "no value".
1625          *
1626          * REVISIT This DWT may well be able to watch for specific data
1627          * values.  Requires comparator #1 to set DATAVMATCH and match
1628          * the data, and another comparator (DATAVADDR0) matching addr.
1629          */
1630         if (watchpoint->value) {
1631                 LOG_DEBUG("data value watchpoint not YET supported");
1632                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1633         }
1634
1635         cortex_m->dwt_comp_available--;
1636         LOG_DEBUG("dwt_comp_available: %d", cortex_m->dwt_comp_available);
1637
1638         return ERROR_OK;
1639 }
1640
1641 int cortex_m_remove_watchpoint(struct target *target, struct watchpoint *watchpoint)
1642 {
1643         struct cortex_m_common *cortex_m = target_to_cm(target);
1644
1645         /* REVISIT why check? DWT can be updated with core running ... */
1646         if (target->state != TARGET_HALTED) {
1647                 LOG_WARNING("target not halted");
1648                 return ERROR_TARGET_NOT_HALTED;
1649         }
1650
1651         if (watchpoint->set)
1652                 cortex_m_unset_watchpoint(target, watchpoint);
1653
1654         cortex_m->dwt_comp_available++;
1655         LOG_DEBUG("dwt_comp_available: %d", cortex_m->dwt_comp_available);
1656
1657         return ERROR_OK;
1658 }
1659
1660 int cortex_m_hit_watchpoint(struct target *target, struct watchpoint **hit_watchpoint)
1661 {
1662         if (target->debug_reason != DBG_REASON_WATCHPOINT)
1663                 return ERROR_FAIL;
1664
1665         struct cortex_m_common *cortex_m = target_to_cm(target);
1666
1667         for (struct watchpoint *wp = target->watchpoints; wp; wp = wp->next) {
1668                 if (!wp->set)
1669                         continue;
1670
1671                 unsigned int dwt_num = wp->set - 1;
1672                 struct cortex_m_dwt_comparator *comparator = cortex_m->dwt_comparator_list + dwt_num;
1673
1674                 uint32_t dwt_function;
1675                 int retval = target_read_u32(target, comparator->dwt_comparator_address + 8, &dwt_function);
1676                 if (retval != ERROR_OK)
1677                         return ERROR_FAIL;
1678
1679                 /* check the MATCHED bit */
1680                 if (dwt_function & BIT(24)) {
1681                         *hit_watchpoint = wp;
1682                         return ERROR_OK;
1683                 }
1684         }
1685
1686         return ERROR_FAIL;
1687 }
1688
1689 void cortex_m_enable_watchpoints(struct target *target)
1690 {
1691         struct watchpoint *watchpoint = target->watchpoints;
1692
1693         /* set any pending watchpoints */
1694         while (watchpoint) {
1695                 if (!watchpoint->set)
1696                         cortex_m_set_watchpoint(target, watchpoint);
1697                 watchpoint = watchpoint->next;
1698         }
1699 }
1700
1701 static int cortex_m_read_memory(struct target *target, target_addr_t address,
1702         uint32_t size, uint32_t count, uint8_t *buffer)
1703 {
1704         struct armv7m_common *armv7m = target_to_armv7m(target);
1705
1706         if (armv7m->arm.arch == ARM_ARCH_V6M) {
1707                 /* armv6m does not handle unaligned memory access */
1708                 if (((size == 4) && (address & 0x3u)) || ((size == 2) && (address & 0x1u)))
1709                         return ERROR_TARGET_UNALIGNED_ACCESS;
1710         }
1711
1712         return mem_ap_read_buf(armv7m->debug_ap, buffer, size, count, address);
1713 }
1714
1715 static int cortex_m_write_memory(struct target *target, target_addr_t address,
1716         uint32_t size, uint32_t count, const uint8_t *buffer)
1717 {
1718         struct armv7m_common *armv7m = target_to_armv7m(target);
1719
1720         if (armv7m->arm.arch == ARM_ARCH_V6M) {
1721                 /* armv6m does not handle unaligned memory access */
1722                 if (((size == 4) && (address & 0x3u)) || ((size == 2) && (address & 0x1u)))
1723                         return ERROR_TARGET_UNALIGNED_ACCESS;
1724         }
1725
1726         return mem_ap_write_buf(armv7m->debug_ap, buffer, size, count, address);
1727 }
1728
1729 static int cortex_m_init_target(struct command_context *cmd_ctx,
1730         struct target *target)
1731 {
1732         armv7m_build_reg_cache(target);
1733         arm_semihosting_init(target);
1734         return ERROR_OK;
1735 }
1736
1737 void cortex_m_deinit_target(struct target *target)
1738 {
1739         struct cortex_m_common *cortex_m = target_to_cm(target);
1740
1741         free(cortex_m->fp_comparator_list);
1742
1743         cortex_m_dwt_free(target);
1744         armv7m_free_reg_cache(target);
1745
1746         free(target->private_config);
1747         free(cortex_m);
1748 }
1749
1750 int cortex_m_profiling(struct target *target, uint32_t *samples,
1751                               uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1752 {
1753         struct timeval timeout, now;
1754         struct armv7m_common *armv7m = target_to_armv7m(target);
1755         uint32_t reg_value;
1756         int retval;
1757
1758         retval = target_read_u32(target, DWT_PCSR, &reg_value);
1759         if (retval != ERROR_OK) {
1760                 LOG_ERROR("Error while reading PCSR");
1761                 return retval;
1762         }
1763         if (reg_value == 0) {
1764                 LOG_INFO("PCSR sampling not supported on this processor.");
1765                 return target_profiling_default(target, samples, max_num_samples, num_samples, seconds);
1766         }
1767
1768         gettimeofday(&timeout, NULL);
1769         timeval_add_time(&timeout, seconds, 0);
1770
1771         LOG_INFO("Starting Cortex-M profiling. Sampling DWT_PCSR as fast as we can...");
1772
1773         /* Make sure the target is running */
1774         target_poll(target);
1775         if (target->state == TARGET_HALTED)
1776                 retval = target_resume(target, 1, 0, 0, 0);
1777
1778         if (retval != ERROR_OK) {
1779                 LOG_ERROR("Error while resuming target");
1780                 return retval;
1781         }
1782
1783         uint32_t sample_count = 0;
1784
1785         for (;;) {
1786                 if (armv7m && armv7m->debug_ap) {
1787                         uint32_t read_count = max_num_samples - sample_count;
1788                         if (read_count > 1024)
1789                                 read_count = 1024;
1790
1791                         retval = mem_ap_read_buf_noincr(armv7m->debug_ap,
1792                                                 (void *)&samples[sample_count],
1793                                                 4, read_count, DWT_PCSR);
1794                         sample_count += read_count;
1795                 } else {
1796                         target_read_u32(target, DWT_PCSR, &samples[sample_count++]);
1797                 }
1798
1799                 if (retval != ERROR_OK) {
1800                         LOG_ERROR("Error while reading PCSR");
1801                         return retval;
1802                 }
1803
1804
1805                 gettimeofday(&now, NULL);
1806                 if (sample_count >= max_num_samples || timeval_compare(&now, &timeout) > 0) {
1807                         LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1808                         break;
1809                 }
1810         }
1811
1812         *num_samples = sample_count;
1813         return retval;
1814 }
1815
1816
1817 /* REVISIT cache valid/dirty bits are unmaintained.  We could set "valid"
1818  * on r/w if the core is not running, and clear on resume or reset ... or
1819  * at least, in a post_restore_context() method.
1820  */
1821
1822 struct dwt_reg_state {
1823         struct target *target;
1824         uint32_t addr;
1825         uint8_t value[4];               /* scratch/cache */
1826 };
1827
1828 static int cortex_m_dwt_get_reg(struct reg *reg)
1829 {
1830         struct dwt_reg_state *state = reg->arch_info;
1831
1832         uint32_t tmp;
1833         int retval = target_read_u32(state->target, state->addr, &tmp);
1834         if (retval != ERROR_OK)
1835                 return retval;
1836
1837         buf_set_u32(state->value, 0, 32, tmp);
1838         return ERROR_OK;
1839 }
1840
1841 static int cortex_m_dwt_set_reg(struct reg *reg, uint8_t *buf)
1842 {
1843         struct dwt_reg_state *state = reg->arch_info;
1844
1845         return target_write_u32(state->target, state->addr,
1846                         buf_get_u32(buf, 0, reg->size));
1847 }
1848
1849 struct dwt_reg {
1850         uint32_t addr;
1851         const char *name;
1852         unsigned size;
1853 };
1854
1855 static const struct dwt_reg dwt_base_regs[] = {
1856         { DWT_CTRL, "dwt_ctrl", 32, },
1857         /* NOTE that Erratum 532314 (fixed r2p0) affects CYCCNT:  it wrongly
1858          * increments while the core is asleep.
1859          */
1860         { DWT_CYCCNT, "dwt_cyccnt", 32, },
1861         /* plus some 8 bit counters, useful for profiling with TPIU */
1862 };
1863
1864 static const struct dwt_reg dwt_comp[] = {
1865 #define DWT_COMPARATOR(i) \
1866                 { DWT_COMP0 + 0x10 * (i), "dwt_" #i "_comp", 32, }, \
1867                 { DWT_MASK0 + 0x10 * (i), "dwt_" #i "_mask", 4, }, \
1868                 { DWT_FUNCTION0 + 0x10 * (i), "dwt_" #i "_function", 32, }
1869         DWT_COMPARATOR(0),
1870         DWT_COMPARATOR(1),
1871         DWT_COMPARATOR(2),
1872         DWT_COMPARATOR(3),
1873         DWT_COMPARATOR(4),
1874         DWT_COMPARATOR(5),
1875         DWT_COMPARATOR(6),
1876         DWT_COMPARATOR(7),
1877         DWT_COMPARATOR(8),
1878         DWT_COMPARATOR(9),
1879         DWT_COMPARATOR(10),
1880         DWT_COMPARATOR(11),
1881         DWT_COMPARATOR(12),
1882         DWT_COMPARATOR(13),
1883         DWT_COMPARATOR(14),
1884         DWT_COMPARATOR(15),
1885 #undef DWT_COMPARATOR
1886 };
1887
1888 static const struct reg_arch_type dwt_reg_type = {
1889         .get = cortex_m_dwt_get_reg,
1890         .set = cortex_m_dwt_set_reg,
1891 };
1892
1893 static void cortex_m_dwt_addreg(struct target *t, struct reg *r, const struct dwt_reg *d)
1894 {
1895         struct dwt_reg_state *state;
1896
1897         state = calloc(1, sizeof(*state));
1898         if (!state)
1899                 return;
1900         state->addr = d->addr;
1901         state->target = t;
1902
1903         r->name = d->name;
1904         r->size = d->size;
1905         r->value = state->value;
1906         r->arch_info = state;
1907         r->type = &dwt_reg_type;
1908 }
1909
1910 static void cortex_m_dwt_setup(struct cortex_m_common *cm, struct target *target)
1911 {
1912         uint32_t dwtcr;
1913         struct reg_cache *cache;
1914         struct cortex_m_dwt_comparator *comparator;
1915         int reg;
1916
1917         target_read_u32(target, DWT_CTRL, &dwtcr);
1918         LOG_DEBUG("DWT_CTRL: 0x%" PRIx32, dwtcr);
1919         if (!dwtcr) {
1920                 LOG_DEBUG("no DWT");
1921                 return;
1922         }
1923
1924         target_read_u32(target, DWT_DEVARCH, &cm->dwt_devarch);
1925         LOG_DEBUG("DWT_DEVARCH: 0x%" PRIx32, cm->dwt_devarch);
1926
1927         cm->dwt_num_comp = (dwtcr >> 28) & 0xF;
1928         cm->dwt_comp_available = cm->dwt_num_comp;
1929         cm->dwt_comparator_list = calloc(cm->dwt_num_comp,
1930                         sizeof(struct cortex_m_dwt_comparator));
1931         if (!cm->dwt_comparator_list) {
1932 fail0:
1933                 cm->dwt_num_comp = 0;
1934                 LOG_ERROR("out of mem");
1935                 return;
1936         }
1937
1938         cache = calloc(1, sizeof(*cache));
1939         if (!cache) {
1940 fail1:
1941                 free(cm->dwt_comparator_list);
1942                 goto fail0;
1943         }
1944         cache->name = "Cortex-M DWT registers";
1945         cache->num_regs = 2 + cm->dwt_num_comp * 3;
1946         cache->reg_list = calloc(cache->num_regs, sizeof(*cache->reg_list));
1947         if (!cache->reg_list) {
1948                 free(cache);
1949                 goto fail1;
1950         }
1951
1952         for (reg = 0; reg < 2; reg++)
1953                 cortex_m_dwt_addreg(target, cache->reg_list + reg,
1954                         dwt_base_regs + reg);
1955
1956         comparator = cm->dwt_comparator_list;
1957         for (unsigned int i = 0; i < cm->dwt_num_comp; i++, comparator++) {
1958                 int j;
1959
1960                 comparator->dwt_comparator_address = DWT_COMP0 + 0x10 * i;
1961                 for (j = 0; j < 3; j++, reg++)
1962                         cortex_m_dwt_addreg(target, cache->reg_list + reg,
1963                                 dwt_comp + 3 * i + j);
1964
1965                 /* make sure we clear any watchpoints enabled on the target */
1966                 target_write_u32(target, comparator->dwt_comparator_address + 8, 0);
1967         }
1968
1969         *register_get_last_cache_p(&target->reg_cache) = cache;
1970         cm->dwt_cache = cache;
1971
1972         LOG_DEBUG("DWT dwtcr 0x%" PRIx32 ", comp %d, watch%s",
1973                 dwtcr, cm->dwt_num_comp,
1974                 (dwtcr & (0xf << 24)) ? " only" : "/trigger");
1975
1976         /* REVISIT:  if num_comp > 1, check whether comparator #1 can
1977          * implement single-address data value watchpoints ... so we
1978          * won't need to check it later, when asked to set one up.
1979          */
1980 }
1981
1982 static void cortex_m_dwt_free(struct target *target)
1983 {
1984         struct cortex_m_common *cm = target_to_cm(target);
1985         struct reg_cache *cache = cm->dwt_cache;
1986
1987         free(cm->dwt_comparator_list);
1988         cm->dwt_comparator_list = NULL;
1989         cm->dwt_num_comp = 0;
1990
1991         if (cache) {
1992                 register_unlink_cache(&target->reg_cache, cache);
1993
1994                 if (cache->reg_list) {
1995                         for (size_t i = 0; i < cache->num_regs; i++)
1996                                 free(cache->reg_list[i].arch_info);
1997                         free(cache->reg_list);
1998                 }
1999                 free(cache);
2000         }
2001         cm->dwt_cache = NULL;
2002 }
2003
2004 #define MVFR0 0xe000ef40
2005 #define MVFR1 0xe000ef44
2006
2007 #define MVFR0_DEFAULT_M4 0x10110021
2008 #define MVFR1_DEFAULT_M4 0x11000011
2009
2010 #define MVFR0_DEFAULT_M7_SP 0x10110021
2011 #define MVFR0_DEFAULT_M7_DP 0x10110221
2012 #define MVFR1_DEFAULT_M7_SP 0x11000011
2013 #define MVFR1_DEFAULT_M7_DP 0x12000011
2014
2015 static int cortex_m_find_mem_ap(struct adiv5_dap *swjdp,
2016                 struct adiv5_ap **debug_ap)
2017 {
2018         if (dap_find_ap(swjdp, AP_TYPE_AHB3_AP, debug_ap) == ERROR_OK)
2019                 return ERROR_OK;
2020
2021         return dap_find_ap(swjdp, AP_TYPE_AHB5_AP, debug_ap);
2022 }
2023
2024 int cortex_m_examine(struct target *target)
2025 {
2026         int retval;
2027         uint32_t cpuid, fpcr, mvfr0, mvfr1;
2028         struct cortex_m_common *cortex_m = target_to_cm(target);
2029         struct adiv5_dap *swjdp = cortex_m->armv7m.arm.dap;
2030         struct armv7m_common *armv7m = target_to_armv7m(target);
2031
2032         /* hla_target shares the examine handler but does not support
2033          * all its calls */
2034         if (!armv7m->is_hla_target) {
2035                 if (cortex_m->apsel == DP_APSEL_INVALID) {
2036                         /* Search for the MEM-AP */
2037                         retval = cortex_m_find_mem_ap(swjdp, &armv7m->debug_ap);
2038                         if (retval != ERROR_OK) {
2039                                 LOG_ERROR("Could not find MEM-AP to control the core");
2040                                 return retval;
2041                         }
2042                 } else {
2043                         armv7m->debug_ap = dap_ap(swjdp, cortex_m->apsel);
2044                 }
2045
2046                 /* Leave (only) generic DAP stuff for debugport_init(); */
2047                 armv7m->debug_ap->memaccess_tck = 8;
2048
2049                 retval = mem_ap_init(armv7m->debug_ap);
2050                 if (retval != ERROR_OK)
2051                         return retval;
2052         }
2053
2054         if (!target_was_examined(target)) {
2055                 target_set_examined(target);
2056
2057                 /* Read from Device Identification Registers */
2058                 retval = target_read_u32(target, CPUID, &cpuid);
2059                 if (retval != ERROR_OK)
2060                         return retval;
2061
2062                 /* Get ARCH and CPU types */
2063                 const enum cortex_m_partno core_partno = (cpuid & ARM_CPUID_PARTNO_MASK) >> ARM_CPUID_PARTNO_POS;
2064
2065                 for (unsigned int n = 0; n < ARRAY_SIZE(cortex_m_parts); n++) {
2066                         if (core_partno == cortex_m_parts[n].partno) {
2067                                 cortex_m->core_info = &cortex_m_parts[n];
2068                                 break;
2069                         }
2070                 }
2071
2072                 if (!cortex_m->core_info) {
2073                         LOG_ERROR("Cortex-M PARTNO 0x%x is unrecognized", core_partno);
2074                         return ERROR_FAIL;
2075                 }
2076
2077                 armv7m->arm.arch = cortex_m->core_info->arch;
2078
2079                 LOG_INFO("%s: %s r%" PRId8 "p%" PRId8 " processor detected",
2080                                 target_name(target),
2081                                 cortex_m->core_info->name,
2082                                 (uint8_t)((cpuid >> 20) & 0xf),
2083                                 (uint8_t)((cpuid >> 0) & 0xf));
2084
2085                 cortex_m->maskints_erratum = false;
2086                 if (core_partno == CORTEX_M7_PARTNO) {
2087                         uint8_t rev, patch;
2088                         rev = (cpuid >> 20) & 0xf;
2089                         patch = (cpuid >> 0) & 0xf;
2090                         if ((rev == 0) && (patch < 2)) {
2091                                 LOG_WARNING("Silicon bug: single stepping may enter pending exception handler!");
2092                                 cortex_m->maskints_erratum = true;
2093                         }
2094                 }
2095                 LOG_DEBUG("cpuid: 0x%8.8" PRIx32 "", cpuid);
2096
2097                 if (cortex_m->core_info->flags & CORTEX_M_F_HAS_FPV4) {
2098                         target_read_u32(target, MVFR0, &mvfr0);
2099                         target_read_u32(target, MVFR1, &mvfr1);
2100
2101                         /* test for floating point feature on Cortex-M4 */
2102                         if ((mvfr0 == MVFR0_DEFAULT_M4) && (mvfr1 == MVFR1_DEFAULT_M4)) {
2103                                 LOG_DEBUG("%s floating point feature FPv4_SP found", cortex_m->core_info->name);
2104                                 armv7m->fp_feature = FPV4_SP;
2105                         }
2106                 } else if (cortex_m->core_info->flags & CORTEX_M_F_HAS_FPV5) {
2107                         target_read_u32(target, MVFR0, &mvfr0);
2108                         target_read_u32(target, MVFR1, &mvfr1);
2109
2110                         /* test for floating point features on Cortex-M7 */
2111                         if ((mvfr0 == MVFR0_DEFAULT_M7_SP) && (mvfr1 == MVFR1_DEFAULT_M7_SP)) {
2112                                 LOG_DEBUG("%s floating point feature FPv5_SP found", cortex_m->core_info->name);
2113                                 armv7m->fp_feature = FPV5_SP;
2114                         } else if ((mvfr0 == MVFR0_DEFAULT_M7_DP) && (mvfr1 == MVFR1_DEFAULT_M7_DP)) {
2115                                 LOG_DEBUG("%s floating point feature FPv5_DP found", cortex_m->core_info->name);
2116                                 armv7m->fp_feature = FPV5_DP;
2117                         }
2118                 }
2119
2120                 /* VECTRESET is supported only on ARMv7-M cores */
2121                 cortex_m->vectreset_supported = armv7m->arm.arch == ARM_ARCH_V7M;
2122
2123                 /* Check for FPU, otherwise mark FPU register as non-existent */
2124                 if (armv7m->fp_feature == FP_NONE)
2125                         for (size_t idx = ARMV7M_FPU_FIRST_REG; idx <= ARMV7M_FPU_LAST_REG; idx++)
2126                                 armv7m->arm.core_cache->reg_list[idx].exist = false;
2127
2128                 if (armv7m->arm.arch != ARM_ARCH_V8M)
2129                         for (size_t idx = ARMV8M_FIRST_REG; idx <= ARMV8M_LAST_REG; idx++)
2130                                 armv7m->arm.core_cache->reg_list[idx].exist = false;
2131
2132                 if (!armv7m->is_hla_target) {
2133                         if (cortex_m->core_info->flags & CORTEX_M_F_TAR_AUTOINCR_BLOCK_4K)
2134                                 /* Cortex-M3/M4 have 4096 bytes autoincrement range,
2135                                  * s. ARM IHI 0031C: MEM-AP 7.2.2 */
2136                                 armv7m->debug_ap->tar_autoincr_block = (1 << 12);
2137                 }
2138
2139                 /* Enable debug requests */
2140                 retval = target_read_u32(target, DCB_DHCSR, &cortex_m->dcb_dhcsr);
2141                 if (retval != ERROR_OK)
2142                         return retval;
2143                 if (!(cortex_m->dcb_dhcsr & C_DEBUGEN)) {
2144                         uint32_t dhcsr = (cortex_m->dcb_dhcsr | C_DEBUGEN) & ~(C_HALT | C_STEP | C_MASKINTS);
2145
2146                         retval = target_write_u32(target, DCB_DHCSR, DBGKEY | (dhcsr & 0x0000FFFFUL));
2147                         if (retval != ERROR_OK)
2148                                 return retval;
2149                         cortex_m->dcb_dhcsr = dhcsr;
2150                 }
2151
2152                 /* Configure trace modules */
2153                 retval = target_write_u32(target, DCB_DEMCR, TRCENA | armv7m->demcr);
2154                 if (retval != ERROR_OK)
2155                         return retval;
2156
2157                 if (armv7m->trace_config.itm_deferred_config)
2158                         armv7m_trace_itm_config(target);
2159
2160                 /* NOTE: FPB and DWT are both optional. */
2161
2162                 /* Setup FPB */
2163                 target_read_u32(target, FP_CTRL, &fpcr);
2164                 /* bits [14:12] and [7:4] */
2165                 cortex_m->fp_num_code = ((fpcr >> 8) & 0x70) | ((fpcr >> 4) & 0xF);
2166                 cortex_m->fp_num_lit = (fpcr >> 8) & 0xF;
2167                 /* Detect flash patch revision, see RM DDI 0403E.b page C1-817.
2168                    Revision is zero base, fp_rev == 1 means Rev.2 ! */
2169                 cortex_m->fp_rev = (fpcr >> 28) & 0xf;
2170                 free(cortex_m->fp_comparator_list);
2171                 cortex_m->fp_comparator_list = calloc(
2172                                 cortex_m->fp_num_code + cortex_m->fp_num_lit,
2173                                 sizeof(struct cortex_m_fp_comparator));
2174                 cortex_m->fpb_enabled = fpcr & 1;
2175                 for (unsigned int i = 0; i < cortex_m->fp_num_code + cortex_m->fp_num_lit; i++) {
2176                         cortex_m->fp_comparator_list[i].type =
2177                                 (i < cortex_m->fp_num_code) ? FPCR_CODE : FPCR_LITERAL;
2178                         cortex_m->fp_comparator_list[i].fpcr_address = FP_COMP0 + 4 * i;
2179
2180                         /* make sure we clear any breakpoints enabled on the target */
2181                         target_write_u32(target, cortex_m->fp_comparator_list[i].fpcr_address, 0);
2182                 }
2183                 LOG_DEBUG("FPB fpcr 0x%" PRIx32 ", numcode %i, numlit %i",
2184                         fpcr,
2185                         cortex_m->fp_num_code,
2186                         cortex_m->fp_num_lit);
2187
2188                 /* Setup DWT */
2189                 cortex_m_dwt_free(target);
2190                 cortex_m_dwt_setup(cortex_m, target);
2191
2192                 /* These hardware breakpoints only work for code in flash! */
2193                 LOG_INFO("%s: target has %d breakpoints, %d watchpoints",
2194                         target_name(target),
2195                         cortex_m->fp_num_code,
2196                         cortex_m->dwt_num_comp);
2197         }
2198
2199         return ERROR_OK;
2200 }
2201
2202 static int cortex_m_dcc_read(struct target *target, uint8_t *value, uint8_t *ctrl)
2203 {
2204         struct armv7m_common *armv7m = target_to_armv7m(target);
2205         uint16_t dcrdr;
2206         uint8_t buf[2];
2207         int retval;
2208
2209         retval = mem_ap_read_buf_noincr(armv7m->debug_ap, buf, 2, 1, DCB_DCRDR);
2210         if (retval != ERROR_OK)
2211                 return retval;
2212
2213         dcrdr = target_buffer_get_u16(target, buf);
2214         *ctrl = (uint8_t)dcrdr;
2215         *value = (uint8_t)(dcrdr >> 8);
2216
2217         LOG_DEBUG("data 0x%x ctrl 0x%x", *value, *ctrl);
2218
2219         /* write ack back to software dcc register
2220          * signify we have read data */
2221         if (dcrdr & (1 << 0)) {
2222                 target_buffer_set_u16(target, buf, 0);
2223                 retval = mem_ap_write_buf_noincr(armv7m->debug_ap, buf, 2, 1, DCB_DCRDR);
2224                 if (retval != ERROR_OK)
2225                         return retval;
2226         }
2227
2228         return ERROR_OK;
2229 }
2230
2231 static int cortex_m_target_request_data(struct target *target,
2232         uint32_t size, uint8_t *buffer)
2233 {
2234         uint8_t data;
2235         uint8_t ctrl;
2236         uint32_t i;
2237
2238         for (i = 0; i < (size * 4); i++) {
2239                 int retval = cortex_m_dcc_read(target, &data, &ctrl);
2240                 if (retval != ERROR_OK)
2241                         return retval;
2242                 buffer[i] = data;
2243         }
2244
2245         return ERROR_OK;
2246 }
2247
2248 static int cortex_m_handle_target_request(void *priv)
2249 {
2250         struct target *target = priv;
2251         if (!target_was_examined(target))
2252                 return ERROR_OK;
2253
2254         if (!target->dbg_msg_enabled)
2255                 return ERROR_OK;
2256
2257         if (target->state == TARGET_RUNNING) {
2258                 uint8_t data;
2259                 uint8_t ctrl;
2260                 int retval;
2261
2262                 retval = cortex_m_dcc_read(target, &data, &ctrl);
2263                 if (retval != ERROR_OK)
2264                         return retval;
2265
2266                 /* check if we have data */
2267                 if (ctrl & (1 << 0)) {
2268                         uint32_t request;
2269
2270                         /* we assume target is quick enough */
2271                         request = data;
2272                         for (int i = 1; i <= 3; i++) {
2273                                 retval = cortex_m_dcc_read(target, &data, &ctrl);
2274                                 if (retval != ERROR_OK)
2275                                         return retval;
2276                                 request |= ((uint32_t)data << (i * 8));
2277                         }
2278                         target_request(target, request);
2279                 }
2280         }
2281
2282         return ERROR_OK;
2283 }
2284
2285 static int cortex_m_init_arch_info(struct target *target,
2286         struct cortex_m_common *cortex_m, struct adiv5_dap *dap)
2287 {
2288         struct armv7m_common *armv7m = &cortex_m->armv7m;
2289
2290         armv7m_init_arch_info(target, armv7m);
2291
2292         /* default reset mode is to use srst if fitted
2293          * if not it will use CORTEX_M3_RESET_VECTRESET */
2294         cortex_m->soft_reset_config = CORTEX_M_RESET_VECTRESET;
2295
2296         armv7m->arm.dap = dap;
2297
2298         /* register arch-specific functions */
2299         armv7m->examine_debug_reason = cortex_m_examine_debug_reason;
2300
2301         armv7m->post_debug_entry = NULL;
2302
2303         armv7m->pre_restore_context = NULL;
2304
2305         armv7m->load_core_reg_u32 = cortex_m_load_core_reg_u32;
2306         armv7m->store_core_reg_u32 = cortex_m_store_core_reg_u32;
2307
2308         target_register_timer_callback(cortex_m_handle_target_request, 1,
2309                 TARGET_TIMER_TYPE_PERIODIC, target);
2310
2311         return ERROR_OK;
2312 }
2313
2314 static int cortex_m_target_create(struct target *target, Jim_Interp *interp)
2315 {
2316         struct adiv5_private_config *pc;
2317
2318         pc = (struct adiv5_private_config *)target->private_config;
2319         if (adiv5_verify_config(pc) != ERROR_OK)
2320                 return ERROR_FAIL;
2321
2322         struct cortex_m_common *cortex_m = calloc(1, sizeof(struct cortex_m_common));
2323         if (!cortex_m) {
2324                 LOG_ERROR("No memory creating target");
2325                 return ERROR_FAIL;
2326         }
2327
2328         cortex_m->common_magic = CORTEX_M_COMMON_MAGIC;
2329         cortex_m->apsel = pc->ap_num;
2330
2331         cortex_m_init_arch_info(target, cortex_m, pc->dap);
2332
2333         return ERROR_OK;
2334 }
2335
2336 /*--------------------------------------------------------------------------*/
2337
2338 static int cortex_m_verify_pointer(struct command_invocation *cmd,
2339         struct cortex_m_common *cm)
2340 {
2341         if (cm->common_magic != CORTEX_M_COMMON_MAGIC) {
2342                 command_print(cmd, "target is not a Cortex-M");
2343                 return ERROR_TARGET_INVALID;
2344         }
2345         return ERROR_OK;
2346 }
2347
2348 /*
2349  * Only stuff below this line should need to verify that its target
2350  * is a Cortex-M3.  Everything else should have indirected through the
2351  * cortexm3_target structure, which is only used with CM3 targets.
2352  */
2353
2354 COMMAND_HANDLER(handle_cortex_m_vector_catch_command)
2355 {
2356         struct target *target = get_current_target(CMD_CTX);
2357         struct cortex_m_common *cortex_m = target_to_cm(target);
2358         struct armv7m_common *armv7m = &cortex_m->armv7m;
2359         uint32_t demcr = 0;
2360         int retval;
2361
2362         static const struct {
2363                 char name[10];
2364                 unsigned mask;
2365         } vec_ids[] = {
2366                 { "hard_err",   VC_HARDERR, },
2367                 { "int_err",    VC_INTERR, },
2368                 { "bus_err",    VC_BUSERR, },
2369                 { "state_err",  VC_STATERR, },
2370                 { "chk_err",    VC_CHKERR, },
2371                 { "nocp_err",   VC_NOCPERR, },
2372                 { "mm_err",     VC_MMERR, },
2373                 { "reset",      VC_CORERESET, },
2374         };
2375
2376         retval = cortex_m_verify_pointer(CMD, cortex_m);
2377         if (retval != ERROR_OK)
2378                 return retval;
2379
2380         if (!target_was_examined(target)) {
2381                 LOG_ERROR("Target not examined yet");
2382                 return ERROR_FAIL;
2383         }
2384
2385         retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DEMCR, &demcr);
2386         if (retval != ERROR_OK)
2387                 return retval;
2388
2389         if (CMD_ARGC > 0) {
2390                 unsigned catch = 0;
2391
2392                 if (CMD_ARGC == 1) {
2393                         if (strcmp(CMD_ARGV[0], "all") == 0) {
2394                                 catch = VC_HARDERR | VC_INTERR | VC_BUSERR
2395                                         | VC_STATERR | VC_CHKERR | VC_NOCPERR
2396                                         | VC_MMERR | VC_CORERESET;
2397                                 goto write;
2398                         } else if (strcmp(CMD_ARGV[0], "none") == 0)
2399                                 goto write;
2400                 }
2401                 while (CMD_ARGC-- > 0) {
2402                         unsigned i;
2403                         for (i = 0; i < ARRAY_SIZE(vec_ids); i++) {
2404                                 if (strcmp(CMD_ARGV[CMD_ARGC], vec_ids[i].name) != 0)
2405                                         continue;
2406                                 catch |= vec_ids[i].mask;
2407                                 break;
2408                         }
2409                         if (i == ARRAY_SIZE(vec_ids)) {
2410                                 LOG_ERROR("No CM3 vector '%s'", CMD_ARGV[CMD_ARGC]);
2411                                 return ERROR_COMMAND_SYNTAX_ERROR;
2412                         }
2413                 }
2414 write:
2415                 /* For now, armv7m->demcr only stores vector catch flags. */
2416                 armv7m->demcr = catch;
2417
2418                 demcr &= ~0xffff;
2419                 demcr |= catch;
2420
2421                 /* write, but don't assume it stuck (why not??) */
2422                 retval = mem_ap_write_u32(armv7m->debug_ap, DCB_DEMCR, demcr);
2423                 if (retval != ERROR_OK)
2424                         return retval;
2425                 retval = mem_ap_read_atomic_u32(armv7m->debug_ap, DCB_DEMCR, &demcr);
2426                 if (retval != ERROR_OK)
2427                         return retval;
2428
2429                 /* FIXME be sure to clear DEMCR on clean server shutdown.
2430                  * Otherwise the vector catch hardware could fire when there's
2431                  * no debugger hooked up, causing much confusion...
2432                  */
2433         }
2434
2435         for (unsigned i = 0; i < ARRAY_SIZE(vec_ids); i++) {
2436                 command_print(CMD, "%9s: %s", vec_ids[i].name,
2437                         (demcr & vec_ids[i].mask) ? "catch" : "ignore");
2438         }
2439
2440         return ERROR_OK;
2441 }
2442
2443 COMMAND_HANDLER(handle_cortex_m_mask_interrupts_command)
2444 {
2445         struct target *target = get_current_target(CMD_CTX);
2446         struct cortex_m_common *cortex_m = target_to_cm(target);
2447         int retval;
2448
2449         static const struct jim_nvp nvp_maskisr_modes[] = {
2450                 { .name = "auto", .value = CORTEX_M_ISRMASK_AUTO },
2451                 { .name = "off", .value = CORTEX_M_ISRMASK_OFF },
2452                 { .name = "on", .value = CORTEX_M_ISRMASK_ON },
2453                 { .name = "steponly", .value = CORTEX_M_ISRMASK_STEPONLY },
2454                 { .name = NULL, .value = -1 },
2455         };
2456         const struct jim_nvp *n;
2457
2458
2459         retval = cortex_m_verify_pointer(CMD, cortex_m);
2460         if (retval != ERROR_OK)
2461                 return retval;
2462
2463         if (target->state != TARGET_HALTED) {
2464                 command_print(CMD, "target must be stopped for \"%s\" command", CMD_NAME);
2465                 return ERROR_OK;
2466         }
2467
2468         if (CMD_ARGC > 0) {
2469                 n = jim_nvp_name2value_simple(nvp_maskisr_modes, CMD_ARGV[0]);
2470                 if (!n->name)
2471                         return ERROR_COMMAND_SYNTAX_ERROR;
2472                 cortex_m->isrmasking_mode = n->value;
2473                 cortex_m_set_maskints_for_halt(target);
2474         }
2475
2476         n = jim_nvp_value2name_simple(nvp_maskisr_modes, cortex_m->isrmasking_mode);
2477         command_print(CMD, "cortex_m interrupt mask %s", n->name);
2478
2479         return ERROR_OK;
2480 }
2481
2482 COMMAND_HANDLER(handle_cortex_m_reset_config_command)
2483 {
2484         struct target *target = get_current_target(CMD_CTX);
2485         struct cortex_m_common *cortex_m = target_to_cm(target);
2486         int retval;
2487         char *reset_config;
2488
2489         retval = cortex_m_verify_pointer(CMD, cortex_m);
2490         if (retval != ERROR_OK)
2491                 return retval;
2492
2493         if (CMD_ARGC > 0) {
2494                 if (strcmp(*CMD_ARGV, "sysresetreq") == 0)
2495                         cortex_m->soft_reset_config = CORTEX_M_RESET_SYSRESETREQ;
2496
2497                 else if (strcmp(*CMD_ARGV, "vectreset") == 0) {
2498                         if (target_was_examined(target)
2499                                         && !cortex_m->vectreset_supported)
2500                                 LOG_WARNING("VECTRESET is not supported on your Cortex-M core!");
2501                         else
2502                                 cortex_m->soft_reset_config = CORTEX_M_RESET_VECTRESET;
2503
2504                 } else
2505                         return ERROR_COMMAND_SYNTAX_ERROR;
2506         }
2507
2508         switch (cortex_m->soft_reset_config) {
2509                 case CORTEX_M_RESET_SYSRESETREQ:
2510                         reset_config = "sysresetreq";
2511                         break;
2512
2513                 case CORTEX_M_RESET_VECTRESET:
2514                         reset_config = "vectreset";
2515                         break;
2516
2517                 default:
2518                         reset_config = "unknown";
2519                         break;
2520         }
2521
2522         command_print(CMD, "cortex_m reset_config %s", reset_config);
2523
2524         return ERROR_OK;
2525 }
2526
2527 static const struct command_registration cortex_m_exec_command_handlers[] = {
2528         {
2529                 .name = "maskisr",
2530                 .handler = handle_cortex_m_mask_interrupts_command,
2531                 .mode = COMMAND_EXEC,
2532                 .help = "mask cortex_m interrupts",
2533                 .usage = "['auto'|'on'|'off'|'steponly']",
2534         },
2535         {
2536                 .name = "vector_catch",
2537                 .handler = handle_cortex_m_vector_catch_command,
2538                 .mode = COMMAND_EXEC,
2539                 .help = "configure hardware vectors to trigger debug entry",
2540                 .usage = "['all'|'none'|('bus_err'|'chk_err'|...)*]",
2541         },
2542         {
2543                 .name = "reset_config",
2544                 .handler = handle_cortex_m_reset_config_command,
2545                 .mode = COMMAND_ANY,
2546                 .help = "configure software reset handling",
2547                 .usage = "['sysresetreq'|'vectreset']",
2548         },
2549         COMMAND_REGISTRATION_DONE
2550 };
2551 static const struct command_registration cortex_m_command_handlers[] = {
2552         {
2553                 .chain = armv7m_command_handlers,
2554         },
2555         {
2556                 .chain = armv7m_trace_command_handlers,
2557         },
2558         /* START_DEPRECATED_TPIU */
2559         {
2560                 .chain = arm_tpiu_deprecated_command_handlers,
2561         },
2562         /* END_DEPRECATED_TPIU */
2563         {
2564                 .name = "cortex_m",
2565                 .mode = COMMAND_EXEC,
2566                 .help = "Cortex-M command group",
2567                 .usage = "",
2568                 .chain = cortex_m_exec_command_handlers,
2569         },
2570         {
2571                 .chain = rtt_target_command_handlers,
2572         },
2573         COMMAND_REGISTRATION_DONE
2574 };
2575
2576 struct target_type cortexm_target = {
2577         .name = "cortex_m",
2578
2579         .poll = cortex_m_poll,
2580         .arch_state = armv7m_arch_state,
2581
2582         .target_request_data = cortex_m_target_request_data,
2583
2584         .halt = cortex_m_halt,
2585         .resume = cortex_m_resume,
2586         .step = cortex_m_step,
2587
2588         .assert_reset = cortex_m_assert_reset,
2589         .deassert_reset = cortex_m_deassert_reset,
2590         .soft_reset_halt = cortex_m_soft_reset_halt,
2591
2592         .get_gdb_arch = arm_get_gdb_arch,
2593         .get_gdb_reg_list = armv7m_get_gdb_reg_list,
2594
2595         .read_memory = cortex_m_read_memory,
2596         .write_memory = cortex_m_write_memory,
2597         .checksum_memory = armv7m_checksum_memory,
2598         .blank_check_memory = armv7m_blank_check_memory,
2599
2600         .run_algorithm = armv7m_run_algorithm,
2601         .start_algorithm = armv7m_start_algorithm,
2602         .wait_algorithm = armv7m_wait_algorithm,
2603
2604         .add_breakpoint = cortex_m_add_breakpoint,
2605         .remove_breakpoint = cortex_m_remove_breakpoint,
2606         .add_watchpoint = cortex_m_add_watchpoint,
2607         .remove_watchpoint = cortex_m_remove_watchpoint,
2608         .hit_watchpoint = cortex_m_hit_watchpoint,
2609
2610         .commands = cortex_m_command_handlers,
2611         .target_create = cortex_m_target_create,
2612         .target_jim_configure = adiv5_jim_configure,
2613         .init_target = cortex_m_init_target,
2614         .examine = cortex_m_examine,
2615         .deinit_target = cortex_m_deinit_target,
2616
2617         .profiling = cortex_m_profiling,
2618 };