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