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