ARM DPM: share debug reason logic
[fw/openocd] / src / target / arm11.c
1 /***************************************************************************
2  *   Copyright (C) 2008 digenius technology GmbH.                          *
3  *   Michael Bruck                                                         *
4  *                                                                         *
5  *   Copyright (C) 2008,2009 Oyvind Harboe oyvind.harboe@zylin.com         *
6  *                                                                         *
7  *   Copyright (C) 2008 Georg Acher <acher@in.tum.de>                      *
8  *                                                                         *
9  *   This program is free software; you can redistribute it and/or modify  *
10  *   it under the terms of the GNU General Public License as published by  *
11  *   the Free Software Foundation; either version 2 of the License, or     *
12  *   (at your option) any later version.                                   *
13  *                                                                         *
14  *   This program is distributed in the hope that it will be useful,       *
15  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
16  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
17  *   GNU General Public License for more details.                          *
18  *                                                                         *
19  *   You should have received a copy of the GNU General Public License     *
20  *   along with this program; if not, write to the                         *
21  *   Free Software Foundation, Inc.,                                       *
22  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
23  ***************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include "etm.h"
30 #include "breakpoints.h"
31 #include "arm11_dbgtap.h"
32 #include "arm_simulator.h"
33 #include <helper/time_support.h>
34 #include "target_type.h"
35 #include "algorithm.h"
36 #include "register.h"
37
38
39 #if 0
40 #define _DEBUG_INSTRUCTION_EXECUTION_
41 #endif
42
43
44 /* FIXME none of these flags should be global to all ARM11 cores!
45  * Most of them shouldn't exist at all, once the code works...
46  */
47 static bool arm11_config_memwrite_burst = true;
48 static bool arm11_config_memwrite_error_fatal = true;
49 static uint32_t arm11_vcr = 0;
50 static bool arm11_config_step_irq_enable = false;
51 static bool arm11_config_hardware_step = false;
52
53 static int arm11_step(struct target *target, int current,
54                 uint32_t address, int handle_breakpoints);
55
56
57 /** Check and if necessary take control of the system
58  *
59  * \param arm11         Target state variable.
60  */
61 static int arm11_check_init(struct arm11_common *arm11)
62 {
63         CHECK_RETVAL(arm11_read_DSCR(arm11));
64         LOG_DEBUG("DSCR %08x", (unsigned) arm11->dscr);
65
66         if (!(arm11->dscr & DSCR_HALT_DBG_MODE))
67         {
68                 LOG_DEBUG("Bringing target into debug mode");
69
70                 arm11->dscr |= DSCR_HALT_DBG_MODE;
71                 arm11_write_DSCR(arm11, arm11->dscr);
72
73                 /* add further reset initialization here */
74
75                 arm11->simulate_reset_on_next_halt = true;
76
77                 if (arm11->dscr & DSCR_CORE_HALTED)
78                 {
79                         /** \todo TODO: this needs further scrutiny because
80                           * arm11_debug_entry() never gets called.  (WHY NOT?)
81                           * As a result we don't read the actual register states from
82                           * the target.
83                           */
84
85                         arm11->arm.target->state = TARGET_HALTED;
86                         arm_dpm_report_dscr(arm11->arm.dpm, arm11->dscr);
87                 }
88                 else
89                 {
90                         arm11->arm.target->state = TARGET_RUNNING;
91                         arm11->arm.target->debug_reason = DBG_REASON_NOTHALTED;
92                 }
93
94                 arm11_sc7_clear_vbw(arm11);
95         }
96
97         return ERROR_OK;
98 }
99
100 /**
101  * Save processor state.  This is called after a HALT instruction
102  * succeeds, and on other occasions the processor enters debug mode
103  * (breakpoint, watchpoint, etc).  Caller has updated arm11->dscr.
104  */
105 static int arm11_debug_entry(struct arm11_common *arm11)
106 {
107         int retval;
108
109         arm11->arm.target->state = TARGET_HALTED;
110         arm_dpm_report_dscr(arm11->arm.dpm, arm11->dscr);
111
112         /* REVISIT entire cache should already be invalid !!! */
113         register_cache_invalidate(arm11->arm.core_cache);
114
115         /* See e.g. ARM1136 TRM, "14.8.4 Entering Debug state" */
116
117         /* maybe save wDTR (pending DCC write to debug SW, e.g. libdcc) */
118         arm11->is_wdtr_saved = !!(arm11->dscr & DSCR_DTR_TX_FULL);
119         if (arm11->is_wdtr_saved)
120         {
121                 arm11_add_debug_SCAN_N(arm11, 0x05, ARM11_TAP_DEFAULT);
122
123                 arm11_add_IR(arm11, ARM11_INTEST, ARM11_TAP_DEFAULT);
124
125                 struct scan_field       chain5_fields[3];
126
127                 arm11_setup_field(arm11, 32, NULL,
128                                 &arm11->saved_wdtr, chain5_fields + 0);
129                 arm11_setup_field(arm11,  1, NULL, NULL,                chain5_fields + 1);
130                 arm11_setup_field(arm11,  1, NULL, NULL,                chain5_fields + 2);
131
132                 arm11_add_dr_scan_vc(ARRAY_SIZE(chain5_fields), chain5_fields, TAP_DRPAUSE);
133
134         }
135
136         /* DSCR: set the Execute ARM instruction enable bit.
137          *
138          * ARM1176 spec says this is needed only for wDTR/rDTR's "ITR mode",
139          * but not to issue ITRs(?).  The ARMv7 arch spec says it's required
140          * for executing instructions via ITR.
141          */
142         arm11_write_DSCR(arm11, DSCR_ITR_EN | arm11->dscr);
143
144
145         /* From the spec:
146            Before executing any instruction in debug state you have to drain the write buffer.
147            This ensures that no imprecise Data Aborts can return at a later point:*/
148
149         /** \todo TODO: Test drain write buffer. */
150
151 #if 0
152         while (1)
153         {
154                 /* MRC p14,0,R0,c5,c10,0 */
155                 //      arm11_run_instr_no_data1(arm11, /*0xee150e1a*/0xe320f000);
156
157                 /* mcr     15, 0, r0, cr7, cr10, {4} */
158                 arm11_run_instr_no_data1(arm11, 0xee070f9a);
159
160                 uint32_t dscr = arm11_read_DSCR(arm11);
161
162                 LOG_DEBUG("DRAIN, DSCR %08x", dscr);
163
164                 if (dscr & ARM11_DSCR_STICKY_IMPRECISE_DATA_ABORT)
165                 {
166                         arm11_run_instr_no_data1(arm11, 0xe320f000);
167
168                         dscr = arm11_read_DSCR(arm11);
169
170                         LOG_DEBUG("DRAIN, DSCR %08x (DONE)", dscr);
171
172                         break;
173                 }
174         }
175 #endif
176
177         /* Save registers.
178          *
179          * NOTE:  ARM1136 TRM suggests saving just R0 here now, then
180          * CPSR and PC after the rDTR stuff.  We do it all at once.
181          */
182         retval = arm_dpm_read_current_registers(&arm11->dpm);
183         if (retval != ERROR_OK)
184                 LOG_ERROR("DPM REG READ -- fail %d", retval);
185
186         retval = arm11_run_instr_data_prepare(arm11);
187         if (retval != ERROR_OK)
188                 return retval;
189
190         /* maybe save rDTR (pending DCC read from debug SW, e.g. libdcc) */
191         arm11->is_rdtr_saved = !!(arm11->dscr & DSCR_DTR_RX_FULL);
192         if (arm11->is_rdtr_saved)
193         {
194                 /* MRC p14,0,R0,c0,c5,0 (move rDTR -> r0 (-> wDTR -> local var)) */
195                 retval = arm11_run_instr_data_from_core_via_r0(arm11,
196                                 0xEE100E15, &arm11->saved_rdtr);
197                 if (retval != ERROR_OK)
198                         return retval;
199         }
200
201         /* REVISIT Now that we've saved core state, there's may also
202          * be MMU and cache state to care about ...
203          */
204
205         if (arm11->simulate_reset_on_next_halt)
206         {
207                 arm11->simulate_reset_on_next_halt = false;
208
209                 LOG_DEBUG("Reset c1 Control Register");
210
211                 /* Write 0 (reset value) to Control register 0 to disable MMU/Cache etc. */
212
213                 /* MCR p15,0,R0,c1,c0,0 */
214                 retval = arm11_run_instr_data_to_core_via_r0(arm11, 0xee010f10, 0);
215                 if (retval != ERROR_OK)
216                         return retval;
217
218         }
219
220         retval = arm11_run_instr_data_finish(arm11);
221         if (retval != ERROR_OK)
222                 return retval;
223
224         return ERROR_OK;
225 }
226
227 /**
228  * Restore processor state.  This is called in preparation for
229  * the RESTART function.
230  */
231 static int arm11_leave_debug_state(struct arm11_common *arm11, bool bpwp)
232 {
233         int retval;
234
235         /* See e.g. ARM1136 TRM, "14.8.5 Leaving Debug state" */
236
237         /* NOTE:  the ARM1136 TRM suggests restoring all registers
238          * except R0/PC/CPSR right now.  Instead, we do them all
239          * at once, just a bit later on.
240          */
241
242         /* REVISIT once we start caring about MMU and cache state,
243          * address it here ...
244          */
245
246         /* spec says clear wDTR and rDTR; we assume they are clear as
247            otherwise our programming would be sloppy */
248         {
249                 CHECK_RETVAL(arm11_read_DSCR(arm11));
250
251                 if (arm11->dscr & (DSCR_DTR_RX_FULL | DSCR_DTR_TX_FULL))
252                 {
253                         /*
254                         The wDTR/rDTR two registers that are used to send/receive data to/from
255                         the core in tandem with corresponding instruction codes that are
256                         written into the core. The RDTR FULL/WDTR FULL flag indicates that the
257                         registers hold data that was written by one side (CPU or JTAG) and not
258                         read out by the other side.
259                         */
260                         LOG_ERROR("wDTR/rDTR inconsistent (DSCR %08x)",
261                                         (unsigned) arm11->dscr);
262                         return ERROR_FAIL;
263                 }
264         }
265
266         /* maybe restore original wDTR */
267         if (arm11->is_wdtr_saved)
268         {
269                 retval = arm11_run_instr_data_prepare(arm11);
270                 if (retval != ERROR_OK)
271                         return retval;
272
273                 /* MCR p14,0,R0,c0,c5,0 */
274                 retval = arm11_run_instr_data_to_core_via_r0(arm11,
275                                 0xee000e15, arm11->saved_wdtr);
276                 if (retval != ERROR_OK)
277                         return retval;
278
279                 retval = arm11_run_instr_data_finish(arm11);
280                 if (retval != ERROR_OK)
281                         return retval;
282         }
283
284         /* restore CPSR, PC, and R0 ... after flushing any modified
285          * registers.
286          */
287         retval = arm_dpm_write_dirty_registers(&arm11->dpm, bpwp);
288
289         register_cache_invalidate(arm11->arm.core_cache);
290
291         /* restore DSCR */
292         arm11_write_DSCR(arm11, arm11->dscr);
293
294         /* maybe restore rDTR */
295         if (arm11->is_rdtr_saved)
296         {
297                 arm11_add_debug_SCAN_N(arm11, 0x05, ARM11_TAP_DEFAULT);
298
299                 arm11_add_IR(arm11, ARM11_EXTEST, ARM11_TAP_DEFAULT);
300
301                 struct scan_field       chain5_fields[3];
302
303                 uint8_t                 Ready           = 0;    /* ignored */
304                 uint8_t                 Valid           = 0;    /* ignored */
305
306                 arm11_setup_field(arm11, 32, &arm11->saved_rdtr,
307                                 NULL, chain5_fields + 0);
308                 arm11_setup_field(arm11,  1, &Ready,    NULL, chain5_fields + 1);
309                 arm11_setup_field(arm11,  1, &Valid,    NULL, chain5_fields + 2);
310
311                 arm11_add_dr_scan_vc(ARRAY_SIZE(chain5_fields), chain5_fields, TAP_DRPAUSE);
312         }
313
314         /* now processor is ready to RESTART */
315
316         return ERROR_OK;
317 }
318
319 /* poll current target status */
320 static int arm11_poll(struct target *target)
321 {
322         int retval;
323         struct arm11_common *arm11 = target_to_arm11(target);
324
325         CHECK_RETVAL(arm11_check_init(arm11));
326
327         if (arm11->dscr & DSCR_CORE_HALTED)
328         {
329                 if (target->state != TARGET_HALTED)
330                 {
331                         enum target_state old_state = target->state;
332
333                         LOG_DEBUG("enter TARGET_HALTED");
334                         retval = arm11_debug_entry(arm11);
335                         if (retval != ERROR_OK)
336                                 return retval;
337
338                         target_call_event_callbacks(target,
339                                 old_state == TARGET_DEBUG_RUNNING ? TARGET_EVENT_DEBUG_HALTED : TARGET_EVENT_HALTED);
340                 }
341         }
342         else
343         {
344                 if (target->state != TARGET_RUNNING && target->state != TARGET_DEBUG_RUNNING)
345                 {
346                         LOG_DEBUG("enter TARGET_RUNNING");
347                         target->state                   = TARGET_RUNNING;
348                         target->debug_reason    = DBG_REASON_NOTHALTED;
349                 }
350         }
351
352         return ERROR_OK;
353 }
354 /* architecture specific status reply */
355 static int arm11_arch_state(struct target *target)
356 {
357         int retval;
358
359         retval = armv4_5_arch_state(target);
360
361         /* REVISIT also display ARM11-specific MMU and cache status ... */
362
363         return retval;
364 }
365
366 /* target request support */
367 static int arm11_target_request_data(struct target *target,
368                 uint32_t size, uint8_t *buffer)
369 {
370         LOG_WARNING("Not implemented: %s", __func__);
371
372         return ERROR_FAIL;
373 }
374
375 /* target execution control */
376 static int arm11_halt(struct target *target)
377 {
378         struct arm11_common *arm11 = target_to_arm11(target);
379
380         LOG_DEBUG("target->state: %s",
381                 target_state_name(target));
382
383         if (target->state == TARGET_UNKNOWN)
384         {
385                 arm11->simulate_reset_on_next_halt = true;
386         }
387
388         if (target->state == TARGET_HALTED)
389         {
390                 LOG_DEBUG("target was already halted");
391                 return ERROR_OK;
392         }
393
394         arm11_add_IR(arm11, ARM11_HALT, TAP_IDLE);
395
396         CHECK_RETVAL(jtag_execute_queue());
397
398         int i = 0;
399
400         while (1)
401         {
402                 CHECK_RETVAL(arm11_read_DSCR(arm11));
403
404                 if (arm11->dscr & DSCR_CORE_HALTED)
405                         break;
406
407
408                 long long then = 0;
409                 if (i == 1000)
410                 {
411                         then = timeval_ms();
412                 }
413                 if (i >= 1000)
414                 {
415                         if ((timeval_ms()-then) > 1000)
416                         {
417                                 LOG_WARNING("Timeout (1000ms) waiting for instructions to complete");
418                                 return ERROR_FAIL;
419                         }
420                 }
421                 i++;
422         }
423
424         enum target_state old_state     = target->state;
425
426         arm11_debug_entry(arm11);
427
428         CHECK_RETVAL(
429                 target_call_event_callbacks(target,
430                         old_state == TARGET_DEBUG_RUNNING ? TARGET_EVENT_DEBUG_HALTED : TARGET_EVENT_HALTED));
431
432         return ERROR_OK;
433 }
434
435 static uint32_t
436 arm11_nextpc(struct arm11_common *arm11, int current, uint32_t address)
437 {
438         void *value = arm11->arm.core_cache->reg_list[15].value;
439
440         if (!current)
441                 buf_set_u32(value, 0, 32, address);
442         else
443                 address = buf_get_u32(value, 0, 32);
444
445         return address;
446 }
447
448 static int arm11_resume(struct target *target, int current,
449                 uint32_t address, int handle_breakpoints, int debug_execution)
450 {
451         //        LOG_DEBUG("current %d  address %08x  handle_breakpoints %d  debug_execution %d",
452         //      current, address, handle_breakpoints, debug_execution);
453
454         struct arm11_common *arm11 = target_to_arm11(target);
455
456         LOG_DEBUG("target->state: %s",
457                 target_state_name(target));
458
459
460         if (target->state != TARGET_HALTED)
461         {
462                 LOG_ERROR("Target not halted");
463                 return ERROR_TARGET_NOT_HALTED;
464         }
465
466         address = arm11_nextpc(arm11, current, address);
467
468         LOG_DEBUG("RESUME PC %08" PRIx32 "%s", address, !current ? "!" : "");
469
470         /* clear breakpoints/watchpoints and VCR*/
471         arm11_sc7_clear_vbw(arm11);
472
473         if (!debug_execution)
474                 target_free_all_working_areas(target);
475
476         /* Set up breakpoints */
477         if (handle_breakpoints)
478         {
479                 /* check if one matches PC and step over it if necessary */
480
481                 struct breakpoint *     bp;
482
483                 for (bp = target->breakpoints; bp; bp = bp->next)
484                 {
485                         if (bp->address == address)
486                         {
487                                 LOG_DEBUG("must step over %08" PRIx32 "", bp->address);
488                                 arm11_step(target, 1, 0, 0);
489                                 break;
490                         }
491                 }
492
493                 /* set all breakpoints */
494
495                 unsigned brp_num = 0;
496
497                 for (bp = target->breakpoints; bp; bp = bp->next)
498                 {
499                         struct arm11_sc7_action brp[2];
500
501                         brp[0].write    = 1;
502                         brp[0].address  = ARM11_SC7_BVR0 + brp_num;
503                         brp[0].value    = bp->address;
504                         brp[1].write    = 1;
505                         brp[1].address  = ARM11_SC7_BCR0 + brp_num;
506                         brp[1].value    = 0x1 | (3 << 1) | (0x0F << 5) | (0 << 14) | (0 << 16) | (0 << 20) | (0 << 21);
507
508                         arm11_sc7_run(arm11, brp, ARRAY_SIZE(brp));
509
510                         LOG_DEBUG("Add BP %d at %08" PRIx32, brp_num,
511                                         bp->address);
512
513                         brp_num++;
514                 }
515
516                 arm11_sc7_set_vcr(arm11, arm11_vcr);
517         }
518
519         arm11_leave_debug_state(arm11, handle_breakpoints);
520
521         arm11_add_IR(arm11, ARM11_RESTART, TAP_IDLE);
522
523         CHECK_RETVAL(jtag_execute_queue());
524
525         int i = 0;
526         while (1)
527         {
528                 CHECK_RETVAL(arm11_read_DSCR(arm11));
529
530                 LOG_DEBUG("DSCR %08x", (unsigned) arm11->dscr);
531
532                 if (arm11->dscr & DSCR_CORE_RESTARTED)
533                         break;
534
535
536                 long long then = 0;
537                 if (i == 1000)
538                 {
539                         then = timeval_ms();
540                 }
541                 if (i >= 1000)
542                 {
543                         if ((timeval_ms()-then) > 1000)
544                         {
545                                 LOG_WARNING("Timeout (1000ms) waiting for instructions to complete");
546                                 return ERROR_FAIL;
547                         }
548                 }
549                 i++;
550         }
551
552         target->debug_reason = DBG_REASON_NOTHALTED;
553         if (!debug_execution)
554                 target->state = TARGET_RUNNING;
555         else
556                 target->state = TARGET_DEBUG_RUNNING;
557         CHECK_RETVAL(target_call_event_callbacks(target, TARGET_EVENT_RESUMED));
558
559         return ERROR_OK;
560 }
561
562 static int arm11_step(struct target *target, int current,
563                 uint32_t address, int handle_breakpoints)
564 {
565         LOG_DEBUG("target->state: %s",
566                 target_state_name(target));
567
568         if (target->state != TARGET_HALTED)
569         {
570                 LOG_WARNING("target was not halted");
571                 return ERROR_TARGET_NOT_HALTED;
572         }
573
574         struct arm11_common *arm11 = target_to_arm11(target);
575
576         address = arm11_nextpc(arm11, current, address);
577
578         LOG_DEBUG("STEP PC %08" PRIx32 "%s", address, !current ? "!" : "");
579
580
581         /** \todo TODO: Thumb not supported here */
582
583         uint32_t        next_instruction;
584
585         CHECK_RETVAL(arm11_read_memory_word(arm11, address, &next_instruction));
586
587         /* skip over BKPT */
588         if ((next_instruction & 0xFFF00070) == 0xe1200070)
589         {
590                 address = arm11_nextpc(arm11, 0, address + 4);
591                 LOG_DEBUG("Skipping BKPT");
592         }
593         /* skip over Wait for interrupt / Standby */
594         /* mcr  15, 0, r?, cr7, cr0, {4} */
595         else if ((next_instruction & 0xFFFF0FFF) == 0xee070f90)
596         {
597                 address = arm11_nextpc(arm11, 0, address + 4);
598                 LOG_DEBUG("Skipping WFI");
599         }
600         /* ignore B to self */
601         else if ((next_instruction & 0xFEFFFFFF) == 0xeafffffe)
602         {
603                 LOG_DEBUG("Not stepping jump to self");
604         }
605         else
606         {
607                 /** \todo TODO: check if break-/watchpoints make any sense at all in combination
608                 * with this. */
609
610                 /** \todo TODO: check if disabling IRQs might be a good idea here. Alternatively
611                 * the VCR might be something worth looking into. */
612
613
614                 /* Set up breakpoint for stepping */
615
616                 struct arm11_sc7_action brp[2];
617
618                 brp[0].write    = 1;
619                 brp[0].address  = ARM11_SC7_BVR0;
620                 brp[1].write    = 1;
621                 brp[1].address  = ARM11_SC7_BCR0;
622
623                 if (arm11_config_hardware_step)
624                 {
625                         /* Hardware single stepping ("instruction address
626                          * mismatch") is used if enabled.  It's not quite
627                          * exactly "run one instruction"; "branch to here"
628                          * loops won't break, neither will some other cases,
629                          * but it's probably the best default.
630                          *
631                          * Hardware single stepping isn't supported on v6
632                          * debug modules.  ARM1176 and v7 can support it...
633                          *
634                          * FIXME Thumb stepping likely needs to use 0x03
635                          * or 0xc0 byte masks, not 0x0f.
636                          */
637                          brp[0].value   = address;
638                          brp[1].value   = 0x1 | (3 << 1) | (0x0F << 5)
639                                         | (0 << 14) | (0 << 16) | (0 << 20)
640                                         | (2 << 21);
641                 } else
642                 {
643                         /* Sets a breakpoint on the next PC, as calculated
644                          * by instruction set simulation.
645                          *
646                          * REVISIT stepping Thumb on ARM1156 requires Thumb2
647                          * support from the simulator.
648                          */
649                         uint32_t next_pc;
650                         int retval;
651
652                         retval = arm_simulate_step(target, &next_pc);
653                         if (retval != ERROR_OK)
654                                 return retval;
655
656                         brp[0].value    = next_pc;
657                         brp[1].value    = 0x1 | (3 << 1) | (0x0F << 5)
658                                         | (0 << 14) | (0 << 16) | (0 << 20)
659                                         | (0 << 21);
660                 }
661
662                 CHECK_RETVAL(arm11_sc7_run(arm11, brp, ARRAY_SIZE(brp)));
663
664                 /* resume */
665
666
667                 if (arm11_config_step_irq_enable)
668                         /* this disable should be redundant ... */
669                         arm11->dscr &= ~DSCR_INT_DIS;
670                 else
671                         arm11->dscr |= DSCR_INT_DIS;
672
673
674                 CHECK_RETVAL(arm11_leave_debug_state(arm11, handle_breakpoints));
675
676                 arm11_add_IR(arm11, ARM11_RESTART, TAP_IDLE);
677
678                 CHECK_RETVAL(jtag_execute_queue());
679
680                 /* wait for halt */
681                 int i = 0;
682
683                 while (1)
684                 {
685                         const uint32_t mask = DSCR_CORE_RESTARTED
686                                         | DSCR_CORE_HALTED;
687
688                         CHECK_RETVAL(arm11_read_DSCR(arm11));
689                         LOG_DEBUG("DSCR %08x e", (unsigned) arm11->dscr);
690
691                         if ((arm11->dscr & mask) == mask)
692                                 break;
693
694                         long long then = 0;
695                         if (i == 1000)
696                         {
697                                 then = timeval_ms();
698                         }
699                         if (i >= 1000)
700                         {
701                                 if ((timeval_ms()-then) > 1000)
702                                 {
703                                         LOG_WARNING("Timeout (1000ms) waiting for instructions to complete");
704                                         return ERROR_FAIL;
705                                 }
706                         }
707                         i++;
708                 }
709
710                 /* clear breakpoint */
711                 arm11_sc7_clear_vbw(arm11);
712
713                 /* save state */
714                 CHECK_RETVAL(arm11_debug_entry(arm11));
715
716                 /* restore default state */
717                 arm11->dscr &= ~DSCR_INT_DIS;
718
719         }
720
721         target->debug_reason = DBG_REASON_SINGLESTEP;
722
723         CHECK_RETVAL(target_call_event_callbacks(target, TARGET_EVENT_HALTED));
724
725         return ERROR_OK;
726 }
727
728 static int arm11_assert_reset(struct target *target)
729 {
730         int retval;
731         struct arm11_common *arm11 = target_to_arm11(target);
732
733         retval = arm11_check_init(arm11);
734         if (retval != ERROR_OK)
735                 return retval;
736
737         target->state = TARGET_UNKNOWN;
738
739         /* we would very much like to reset into the halted, state,
740          * but resetting and halting is second best... */
741         if (target->reset_halt)
742         {
743                 CHECK_RETVAL(target_halt(target));
744         }
745
746
747         /* srst is funny. We can not do *anything* else while it's asserted
748          * and it has unkonwn side effects. Make sure no other code runs
749          * meanwhile.
750          *
751          * Code below assumes srst:
752          *
753          * - Causes power-on-reset (but of what parts of the system?). Bug
754          * in arm11?
755          *
756          * - Messes us TAP state without asserting trst.
757          *
758          * - There is another bug in the arm11 core. When you generate an access to
759          * external logic (for example ddr controller via AHB bus) and that block
760          * is not configured (perhaps it is still held in reset), that transaction
761          * will never complete. This will hang arm11 core but it will also hang
762          * JTAG controller. Nothing, short of srst assertion will bring it out of
763          * this.
764          *
765          * Mysteries:
766          *
767          * - What should the PC be after an srst reset when starting in the halted
768          * state?
769          */
770
771         jtag_add_reset(0, 1);
772         jtag_add_reset(0, 0);
773
774         /* How long do we have to wait? */
775         jtag_add_sleep(5000);
776
777         /* un-mess up TAP state */
778         jtag_add_tlr();
779
780         retval = jtag_execute_queue();
781         if (retval != ERROR_OK)
782         {
783                 return retval;
784         }
785
786         return ERROR_OK;
787 }
788
789 static int arm11_deassert_reset(struct target *target)
790 {
791         return ERROR_OK;
792 }
793
794 static int arm11_soft_reset_halt(struct target *target)
795 {
796         LOG_WARNING("Not implemented: %s", __func__);
797
798         return ERROR_FAIL;
799 }
800
801 /* target memory access
802  * size: 1 = byte (8bit), 2 = half-word (16bit), 4 = word (32bit)
803  * count: number of items of <size>
804  *
805  * arm11_config_memrw_no_increment - in the future we may want to be able
806  * to read/write a range of data to a "port". a "port" is an action on
807  * read memory address for some peripheral.
808  */
809 static int arm11_read_memory_inner(struct target *target,
810                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer,
811                 bool arm11_config_memrw_no_increment)
812 {
813         /** \todo TODO: check if buffer cast to uint32_t* and uint16_t* might cause alignment problems */
814         int retval;
815
816         if (target->state != TARGET_HALTED)
817         {
818                 LOG_WARNING("target was not halted");
819                 return ERROR_TARGET_NOT_HALTED;
820         }
821
822         LOG_DEBUG("ADDR %08" PRIx32 "  SIZE %08" PRIx32 "  COUNT %08" PRIx32 "", address, size, count);
823
824         struct arm11_common *arm11 = target_to_arm11(target);
825
826         retval = arm11_run_instr_data_prepare(arm11);
827         if (retval != ERROR_OK)
828                 return retval;
829
830         /* MRC p14,0,r0,c0,c5,0 */
831         retval = arm11_run_instr_data_to_core1(arm11, 0xee100e15, address);
832         if (retval != ERROR_OK)
833                 return retval;
834
835         switch (size)
836         {
837         case 1:
838                 arm11->arm.core_cache->reg_list[1].dirty = true;
839
840                 for (size_t i = 0; i < count; i++)
841                 {
842                         /* ldrb    r1, [r0], #1 */
843                         /* ldrb    r1, [r0] */
844                         arm11_run_instr_no_data1(arm11,
845                                         !arm11_config_memrw_no_increment ? 0xe4d01001 : 0xe5d01000);
846
847                         uint32_t res;
848                         /* MCR p14,0,R1,c0,c5,0 */
849                         arm11_run_instr_data_from_core(arm11, 0xEE001E15, &res, 1);
850
851                         *buffer++ = res;
852                 }
853
854                 break;
855
856         case 2:
857                 {
858                         arm11->arm.core_cache->reg_list[1].dirty = true;
859
860                         for (size_t i = 0; i < count; i++)
861                         {
862                                 /* ldrh    r1, [r0], #2 */
863                                 arm11_run_instr_no_data1(arm11,
864                                         !arm11_config_memrw_no_increment ? 0xe0d010b2 : 0xe1d010b0);
865
866                                 uint32_t res;
867
868                                 /* MCR p14,0,R1,c0,c5,0 */
869                                 arm11_run_instr_data_from_core(arm11, 0xEE001E15, &res, 1);
870
871                                 uint16_t svalue = res;
872                                 memcpy(buffer + i * sizeof(uint16_t), &svalue, sizeof(uint16_t));
873                         }
874
875                         break;
876                 }
877
878         case 4:
879                 {
880                 uint32_t instr = !arm11_config_memrw_no_increment ? 0xecb05e01 : 0xed905e00;
881                 /** \todo TODO: buffer cast to uint32_t* causes alignment warnings */
882                 uint32_t *words = (uint32_t *)buffer;
883
884                 /* LDC p14,c5,[R0],#4 */
885                 /* LDC p14,c5,[R0] */
886                 arm11_run_instr_data_from_core(arm11, instr, words, count);
887                 break;
888                 }
889         }
890
891         return arm11_run_instr_data_finish(arm11);
892 }
893
894 static int arm11_read_memory(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
895 {
896         return arm11_read_memory_inner(target, address, size, count, buffer, false);
897 }
898
899 /*
900 * no_increment - in the future we may want to be able
901 * to read/write a range of data to a "port". a "port" is an action on
902 * read memory address for some peripheral.
903 */
904 static int arm11_write_memory_inner(struct target *target,
905                 uint32_t address, uint32_t size,
906                 uint32_t count, uint8_t *buffer,
907                 bool no_increment)
908 {
909         int retval;
910
911         if (target->state != TARGET_HALTED)
912         {
913                 LOG_WARNING("target was not halted");
914                 return ERROR_TARGET_NOT_HALTED;
915         }
916
917         LOG_DEBUG("ADDR %08" PRIx32 "  SIZE %08" PRIx32 "  COUNT %08" PRIx32 "", address, size, count);
918
919         struct arm11_common *arm11 = target_to_arm11(target);
920
921         retval = arm11_run_instr_data_prepare(arm11);
922         if (retval != ERROR_OK)
923                 return retval;
924
925         /* MRC p14,0,r0,c0,c5,0 */
926         retval = arm11_run_instr_data_to_core1(arm11, 0xee100e15, address);
927         if (retval != ERROR_OK)
928                 return retval;
929
930         /* burst writes are not used for single words as those may well be
931          * reset init script writes.
932          *
933          * The other advantage is that as burst writes are default, we'll
934          * now exercise both burst and non-burst code paths with the
935          * default settings, increasing code coverage.
936          */
937         bool burst = arm11_config_memwrite_burst && (count > 1);
938
939         switch (size)
940         {
941         case 1:
942                 {
943                         arm11->arm.core_cache->reg_list[1].dirty = true;
944
945                         for (size_t i = 0; i < count; i++)
946                         {
947                                 /* MRC p14,0,r1,c0,c5,0 */
948                                 retval = arm11_run_instr_data_to_core1(arm11, 0xee101e15, *buffer++);
949                                 if (retval != ERROR_OK)
950                                         return retval;
951
952                                 /* strb    r1, [r0], #1 */
953                                 /* strb    r1, [r0] */
954                                 retval = arm11_run_instr_no_data1(arm11,
955                                         !no_increment
956                                                 ? 0xe4c01001
957                                                 : 0xe5c01000);
958                                 if (retval != ERROR_OK)
959                                         return retval;
960                         }
961
962                         break;
963                 }
964
965         case 2:
966                 {
967                         arm11->arm.core_cache->reg_list[1].dirty = true;
968
969                         for (size_t i = 0; i < count; i++)
970                         {
971                                 uint16_t value;
972                                 memcpy(&value, buffer + i * sizeof(uint16_t), sizeof(uint16_t));
973
974                                 /* MRC p14,0,r1,c0,c5,0 */
975                                 retval = arm11_run_instr_data_to_core1(arm11, 0xee101e15, value);
976                                 if (retval != ERROR_OK)
977                                         return retval;
978
979                                 /* strh    r1, [r0], #2 */
980                                 /* strh    r1, [r0] */
981                                 retval = arm11_run_instr_no_data1(arm11,
982                                         !no_increment
983                                                 ? 0xe0c010b2
984                                                 : 0xe1c010b0);
985                                 if (retval != ERROR_OK)
986                                         return retval;
987                         }
988
989                         break;
990                 }
991
992         case 4: {
993                 uint32_t instr = !no_increment ? 0xeca05e01 : 0xed805e00;
994
995                 /** \todo TODO: buffer cast to uint32_t* causes alignment warnings */
996                 uint32_t *words = (uint32_t*)buffer;
997
998                 if (!burst)
999                 {
1000                         /* STC p14,c5,[R0],#4 */
1001                         /* STC p14,c5,[R0]*/
1002                         retval = arm11_run_instr_data_to_core(arm11, instr, words, count);
1003                         if (retval != ERROR_OK)
1004                                 return retval;
1005                 }
1006                 else
1007                 {
1008                         /* STC p14,c5,[R0],#4 */
1009                         /* STC p14,c5,[R0]*/
1010                         retval = arm11_run_instr_data_to_core_noack(arm11, instr, words, count);
1011                         if (retval != ERROR_OK)
1012                                 return retval;
1013                 }
1014
1015                 break;
1016         }
1017         }
1018
1019         /* r0 verification */
1020         if (!no_increment)
1021         {
1022                 uint32_t r0;
1023
1024                 /* MCR p14,0,R0,c0,c5,0 */
1025                 retval = arm11_run_instr_data_from_core(arm11, 0xEE000E15, &r0, 1);
1026                 if (retval != ERROR_OK)
1027                         return retval;
1028
1029                 if (address + size * count != r0)
1030                 {
1031                         LOG_ERROR("Data transfer failed. Expected end "
1032                                         "address 0x%08x, got 0x%08x",
1033                                         (unsigned) (address + size * count),
1034                                         (unsigned) r0);
1035
1036                         if (burst)
1037                                 LOG_ERROR("use 'arm11 memwrite burst disable' to disable fast burst mode");
1038
1039                         if (arm11_config_memwrite_error_fatal)
1040                                 return ERROR_FAIL;
1041                 }
1042         }
1043
1044         return arm11_run_instr_data_finish(arm11);
1045 }
1046
1047 static int arm11_write_memory(struct target *target,
1048                 uint32_t address, uint32_t size,
1049                 uint32_t count, uint8_t *buffer)
1050 {
1051         /* pointer increment matters only for multi-unit writes ...
1052          * not e.g. to a "reset the chip" controller.
1053          */
1054         return arm11_write_memory_inner(target, address, size,
1055                         count, buffer, count == 1);
1056 }
1057
1058 /* write target memory in multiples of 4 byte, optimized for writing large quantities of data */
1059 static int arm11_bulk_write_memory(struct target *target,
1060                 uint32_t address, uint32_t count, uint8_t *buffer)
1061 {
1062         if (target->state != TARGET_HALTED)
1063         {
1064                 LOG_WARNING("target was not halted");
1065                 return ERROR_TARGET_NOT_HALTED;
1066         }
1067
1068         return arm11_write_memory(target, address, 4, count, buffer);
1069 }
1070
1071 /* target break-/watchpoint control
1072 * rw: 0 = write, 1 = read, 2 = access
1073 */
1074 static int arm11_add_breakpoint(struct target *target,
1075                 struct breakpoint *breakpoint)
1076 {
1077         struct arm11_common *arm11 = target_to_arm11(target);
1078
1079 #if 0
1080         if (breakpoint->type == BKPT_SOFT)
1081         {
1082                 LOG_INFO("sw breakpoint requested, but software breakpoints not enabled");
1083                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1084         }
1085 #endif
1086
1087         if (!arm11->free_brps)
1088         {
1089                 LOG_DEBUG("no breakpoint unit available for hardware breakpoint");
1090                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1091         }
1092
1093         if (breakpoint->length != 4)
1094         {
1095                 LOG_DEBUG("only breakpoints of four bytes length supported");
1096                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1097         }
1098
1099         arm11->free_brps--;
1100
1101         return ERROR_OK;
1102 }
1103
1104 static int arm11_remove_breakpoint(struct target *target,
1105                 struct breakpoint *breakpoint)
1106 {
1107         struct arm11_common *arm11 = target_to_arm11(target);
1108
1109         arm11->free_brps++;
1110
1111         return ERROR_OK;
1112 }
1113
1114 static int arm11_target_create(struct target *target, Jim_Interp *interp)
1115 {
1116         struct arm11_common *arm11;
1117
1118         if (target->tap == NULL)
1119                 return ERROR_FAIL;
1120
1121         if (target->tap->ir_length != 5)
1122         {
1123                 LOG_ERROR("'target arm11' expects IR LENGTH = 5");
1124                 return ERROR_COMMAND_SYNTAX_ERROR;
1125         }
1126
1127         arm11 = calloc(1, sizeof *arm11);
1128         if (!arm11)
1129                 return ERROR_FAIL;
1130
1131         armv4_5_init_arch_info(target, &arm11->arm);
1132
1133         arm11->jtag_info.tap = target->tap;
1134         arm11->jtag_info.scann_size = 5;
1135         arm11->jtag_info.scann_instr = ARM11_SCAN_N;
1136         /* cur_scan_chain == 0 */
1137         arm11->jtag_info.intest_instr = ARM11_INTEST;
1138
1139         return ERROR_OK;
1140 }
1141
1142 static int arm11_init_target(struct command_context *cmd_ctx,
1143                 struct target *target)
1144 {
1145         /* Initialize anything we can set up without talking to the target */
1146         return ERROR_OK;
1147 }
1148
1149 /* talk to the target and set things up */
1150 static int arm11_examine(struct target *target)
1151 {
1152         int retval;
1153         char *type;
1154         struct arm11_common *arm11 = target_to_arm11(target);
1155         uint32_t didr, device_id;
1156         uint8_t implementor;
1157
1158         /* FIXME split into do-first-time and do-every-time logic ... */
1159
1160         /* check IDCODE */
1161
1162         arm11_add_IR(arm11, ARM11_IDCODE, ARM11_TAP_DEFAULT);
1163
1164         struct scan_field               idcode_field;
1165
1166         arm11_setup_field(arm11, 32, NULL, &device_id, &idcode_field);
1167
1168         arm11_add_dr_scan_vc(1, &idcode_field, TAP_DRPAUSE);
1169
1170         /* check DIDR */
1171
1172         arm11_add_debug_SCAN_N(arm11, 0x00, ARM11_TAP_DEFAULT);
1173
1174         arm11_add_IR(arm11, ARM11_INTEST, ARM11_TAP_DEFAULT);
1175
1176         struct scan_field               chain0_fields[2];
1177
1178         arm11_setup_field(arm11, 32, NULL, &didr, chain0_fields + 0);
1179         arm11_setup_field(arm11,  8, NULL, &implementor, chain0_fields + 1);
1180
1181         arm11_add_dr_scan_vc(ARRAY_SIZE(chain0_fields), chain0_fields, TAP_IDLE);
1182
1183         CHECK_RETVAL(jtag_execute_queue());
1184
1185         switch (device_id & 0x0FFFF000)
1186         {
1187         case 0x07B36000:
1188                 type = "ARM1136";
1189                 break;
1190         case 0x07B56000:
1191                 type = "ARM1156";
1192                 break;
1193         case 0x07B76000:
1194                 arm11->arm.core_type = ARM_MODE_MON;
1195                 type = "ARM1176";
1196                 break;
1197         default:
1198                 LOG_ERROR("'target arm11' expects IDCODE 0x*7B*7****");
1199                 return ERROR_FAIL;
1200         }
1201         LOG_INFO("found %s", type);
1202
1203         /* unlikely this could ever fail, but ... */
1204         switch ((didr >> 16) & 0x0F) {
1205         case ARM11_DEBUG_V6:
1206         case ARM11_DEBUG_V61:           /* supports security extensions */
1207                 break;
1208         default:
1209                 LOG_ERROR("Only ARM v6 and v6.1 debug supported.");
1210                 return ERROR_FAIL;
1211         }
1212
1213         arm11->brp = ((didr >> 24) & 0x0F) + 1;
1214         arm11->wrp = ((didr >> 28) & 0x0F) + 1;
1215
1216         /** \todo TODO: reserve one brp slot if we allow breakpoints during step */
1217         arm11->free_brps = arm11->brp;
1218
1219         LOG_DEBUG("IDCODE %08" PRIx32 " IMPLEMENTOR %02x DIDR %08" PRIx32,
1220                         device_id, implementor, didr);
1221
1222         /* as a side-effect this reads DSCR and thus
1223          * clears the ARM11_DSCR_STICKY_PRECISE_DATA_ABORT / Sticky Precise Data Abort Flag
1224          * as suggested by the spec.
1225          */
1226
1227         retval = arm11_check_init(arm11);
1228         if (retval != ERROR_OK)
1229                 return retval;
1230
1231         /* Build register cache "late", after target_init(), since we
1232          * want to know if this core supports Secure Monitor mode.
1233          */
1234         if (!target_was_examined(target))
1235                 retval = arm11_dpm_init(arm11, didr);
1236
1237         /* ETM on ARM11 still uses original scanchain 6 access mode */
1238         if (arm11->arm.etm && !target_was_examined(target)) {
1239                 *register_get_last_cache_p(&target->reg_cache) =
1240                         etm_build_reg_cache(target, &arm11->jtag_info,
1241                                         arm11->arm.etm);
1242                 retval = etm_setup(target);
1243         }
1244
1245         target_set_examined(target);
1246
1247         return ERROR_OK;
1248 }
1249
1250
1251 /* FIXME all these BOOL_WRAPPER things should be modifying
1252  * per-instance state, not shared state; ditto the vector
1253  * catch register support.  Scan chains with multiple cores
1254  * should be able to say "work with this core like this,
1255  * that core like that".  Example, ARM11 MPCore ...
1256  */
1257
1258 #define ARM11_BOOL_WRAPPER(name, print_name)    \
1259                 COMMAND_HANDLER(arm11_handle_bool_##name) \
1260                 { \
1261                         return CALL_COMMAND_HANDLER(handle_command_parse_bool, \
1262                                         &arm11_config_##name, print_name); \
1263                 }
1264
1265 ARM11_BOOL_WRAPPER(memwrite_burst, "memory write burst mode")
1266 ARM11_BOOL_WRAPPER(memwrite_error_fatal, "fatal error mode for memory writes")
1267 ARM11_BOOL_WRAPPER(step_irq_enable, "IRQs while stepping")
1268 ARM11_BOOL_WRAPPER(hardware_step, "hardware single step")
1269
1270 COMMAND_HANDLER(arm11_handle_vcr)
1271 {
1272         switch (CMD_ARGC) {
1273         case 0:
1274                 break;
1275         case 1:
1276                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], arm11_vcr);
1277                 break;
1278         default:
1279                 return ERROR_COMMAND_SYNTAX_ERROR;
1280         }
1281
1282         LOG_INFO("VCR 0x%08" PRIx32 "", arm11_vcr);
1283         return ERROR_OK;
1284 }
1285
1286 static const struct command_registration arm11_mw_command_handlers[] = {
1287         {
1288                 .name = "burst",
1289                 .handler = &arm11_handle_bool_memwrite_burst,
1290                 .mode = COMMAND_ANY,
1291                 .help = "Enable/Disable non-standard but fast burst mode"
1292                         " (default: enabled)",
1293         },
1294         {
1295                 .name = "error_fatal",
1296                 .handler = &arm11_handle_bool_memwrite_error_fatal,
1297                 .mode = COMMAND_ANY,
1298                 .help = "Terminate program if transfer error was found"
1299                         " (default: enabled)",
1300         },
1301         COMMAND_REGISTRATION_DONE
1302 };
1303 static const struct command_registration arm11_any_command_handlers[] = {
1304         {
1305                 /* "hardware_step" is only here to check if the default
1306                  * simulate + breakpoint implementation is broken.
1307                  * TEMPORARY! NOT DOCUMENTED! */
1308                 .name = "hardware_step",
1309                 .handler = &arm11_handle_bool_hardware_step,
1310                 .mode = COMMAND_ANY,
1311                 .help = "DEBUG ONLY - Hardware single stepping"
1312                         " (default: disabled)",
1313                 .usage = "(enable|disable)",
1314         },
1315         {
1316                 .name = "memwrite",
1317                 .mode = COMMAND_ANY,
1318                 .help = "memwrite command group",
1319                 .chain = arm11_mw_command_handlers,
1320         },
1321         {
1322                 .name = "step_irq_enable",
1323                 .handler = &arm11_handle_bool_step_irq_enable,
1324                 .mode = COMMAND_ANY,
1325                 .help = "Enable interrupts while stepping"
1326                         " (default: disabled)",
1327         },
1328         {
1329                 .name = "vcr",
1330                 .handler = &arm11_handle_vcr,
1331                 .mode = COMMAND_ANY,
1332                 .help = "Control (Interrupt) Vector Catch Register",
1333         },
1334         COMMAND_REGISTRATION_DONE
1335 };
1336 static const struct command_registration arm11_command_handlers[] = {
1337         {
1338                 .chain = arm_command_handlers,
1339         },
1340         {
1341                 .chain = etm_command_handlers,
1342         },
1343         {
1344                 .name = "arm11",
1345                 .mode = COMMAND_ANY,
1346                 .help = "ARM11 command group",
1347                 .chain = arm11_any_command_handlers,
1348         },
1349         COMMAND_REGISTRATION_DONE
1350 };
1351
1352 /** Holds methods for ARM11xx targets. */
1353 struct target_type arm11_target = {
1354         .name =                 "arm11",
1355
1356         .poll =                 arm11_poll,
1357         .arch_state =           arm11_arch_state,
1358
1359         .target_request_data =  arm11_target_request_data,
1360
1361         .halt =                 arm11_halt,
1362         .resume =               arm11_resume,
1363         .step =                 arm11_step,
1364
1365         .assert_reset =         arm11_assert_reset,
1366         .deassert_reset =       arm11_deassert_reset,
1367         .soft_reset_halt =      arm11_soft_reset_halt,
1368
1369         .get_gdb_reg_list =     armv4_5_get_gdb_reg_list,
1370
1371         .read_memory =          arm11_read_memory,
1372         .write_memory =         arm11_write_memory,
1373
1374         .bulk_write_memory =    arm11_bulk_write_memory,
1375
1376         .checksum_memory =      arm_checksum_memory,
1377         .blank_check_memory =   arm_blank_check_memory,
1378
1379         .add_breakpoint =       arm11_add_breakpoint,
1380         .remove_breakpoint =    arm11_remove_breakpoint,
1381
1382         .run_algorithm =        armv4_5_run_algorithm,
1383
1384         .commands =             arm11_command_handlers,
1385         .target_create =        arm11_target_create,
1386         .init_target =          arm11_init_target,
1387         .examine =              arm11_examine,
1388 };