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