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