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