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