ARM11: basic watchpoint support
[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         retval = arm11_bpwp_flush(arm11);
290
291         register_cache_invalidate(arm11->arm.core_cache);
292
293         /* restore DSCR */
294         arm11_write_DSCR(arm11, arm11->dscr);
295
296         /* maybe restore rDTR */
297         if (arm11->is_rdtr_saved)
298         {
299                 arm11_add_debug_SCAN_N(arm11, 0x05, ARM11_TAP_DEFAULT);
300
301                 arm11_add_IR(arm11, ARM11_EXTEST, ARM11_TAP_DEFAULT);
302
303                 struct scan_field       chain5_fields[3];
304
305                 uint8_t                 Ready           = 0;    /* ignored */
306                 uint8_t                 Valid           = 0;    /* ignored */
307
308                 arm11_setup_field(arm11, 32, &arm11->saved_rdtr,
309                                 NULL, chain5_fields + 0);
310                 arm11_setup_field(arm11,  1, &Ready,    NULL, chain5_fields + 1);
311                 arm11_setup_field(arm11,  1, &Valid,    NULL, chain5_fields + 2);
312
313                 arm11_add_dr_scan_vc(ARRAY_SIZE(chain5_fields), chain5_fields, TAP_DRPAUSE);
314         }
315
316         /* now processor is ready to RESTART */
317
318         return ERROR_OK;
319 }
320
321 /* poll current target status */
322 static int arm11_poll(struct target *target)
323 {
324         int retval;
325         struct arm11_common *arm11 = target_to_arm11(target);
326
327         CHECK_RETVAL(arm11_check_init(arm11));
328
329         if (arm11->dscr & DSCR_CORE_HALTED)
330         {
331                 if (target->state != TARGET_HALTED)
332                 {
333                         enum target_state old_state = target->state;
334
335                         LOG_DEBUG("enter TARGET_HALTED");
336                         retval = arm11_debug_entry(arm11);
337                         if (retval != ERROR_OK)
338                                 return retval;
339
340                         target_call_event_callbacks(target,
341                                 old_state == TARGET_DEBUG_RUNNING ? TARGET_EVENT_DEBUG_HALTED : TARGET_EVENT_HALTED);
342                 }
343         }
344         else
345         {
346                 if (target->state != TARGET_RUNNING && target->state != TARGET_DEBUG_RUNNING)
347                 {
348                         LOG_DEBUG("enter TARGET_RUNNING");
349                         target->state                   = TARGET_RUNNING;
350                         target->debug_reason    = DBG_REASON_NOTHALTED;
351                 }
352         }
353
354         return ERROR_OK;
355 }
356 /* architecture specific status reply */
357 static int arm11_arch_state(struct target *target)
358 {
359         int retval;
360
361         retval = armv4_5_arch_state(target);
362
363         /* REVISIT also display ARM11-specific MMU and cache status ... */
364
365         return retval;
366 }
367
368 /* target request support */
369 static int arm11_target_request_data(struct target *target,
370                 uint32_t size, uint8_t *buffer)
371 {
372         LOG_WARNING("Not implemented: %s", __func__);
373
374         return ERROR_FAIL;
375 }
376
377 /* target execution control */
378 static int arm11_halt(struct target *target)
379 {
380         struct arm11_common *arm11 = target_to_arm11(target);
381
382         LOG_DEBUG("target->state: %s",
383                 target_state_name(target));
384
385         if (target->state == TARGET_UNKNOWN)
386         {
387                 arm11->simulate_reset_on_next_halt = true;
388         }
389
390         if (target->state == TARGET_HALTED)
391         {
392                 LOG_DEBUG("target was already halted");
393                 return ERROR_OK;
394         }
395
396         arm11_add_IR(arm11, ARM11_HALT, TAP_IDLE);
397
398         CHECK_RETVAL(jtag_execute_queue());
399
400         int i = 0;
401
402         while (1)
403         {
404                 CHECK_RETVAL(arm11_read_DSCR(arm11));
405
406                 if (arm11->dscr & DSCR_CORE_HALTED)
407                         break;
408
409
410                 long long then = 0;
411                 if (i == 1000)
412                 {
413                         then = timeval_ms();
414                 }
415                 if (i >= 1000)
416                 {
417                         if ((timeval_ms()-then) > 1000)
418                         {
419                                 LOG_WARNING("Timeout (1000ms) waiting for instructions to complete");
420                                 return ERROR_FAIL;
421                         }
422                 }
423                 i++;
424         }
425
426         enum target_state old_state     = target->state;
427
428         arm11_debug_entry(arm11);
429
430         CHECK_RETVAL(
431                 target_call_event_callbacks(target,
432                         old_state == TARGET_DEBUG_RUNNING ? TARGET_EVENT_DEBUG_HALTED : TARGET_EVENT_HALTED));
433
434         return ERROR_OK;
435 }
436
437 static uint32_t
438 arm11_nextpc(struct arm11_common *arm11, int current, uint32_t address)
439 {
440         void *value = arm11->arm.core_cache->reg_list[15].value;
441
442         if (!current)
443                 buf_set_u32(value, 0, 32, address);
444         else
445                 address = buf_get_u32(value, 0, 32);
446
447         return address;
448 }
449
450 static int arm11_resume(struct target *target, int current,
451                 uint32_t address, int handle_breakpoints, int debug_execution)
452 {
453         //        LOG_DEBUG("current %d  address %08x  handle_breakpoints %d  debug_execution %d",
454         //      current, address, handle_breakpoints, debug_execution);
455
456         struct arm11_common *arm11 = target_to_arm11(target);
457
458         LOG_DEBUG("target->state: %s",
459                 target_state_name(target));
460
461
462         if (target->state != TARGET_HALTED)
463         {
464                 LOG_ERROR("Target not halted");
465                 return ERROR_TARGET_NOT_HALTED;
466         }
467
468         address = arm11_nextpc(arm11, current, address);
469
470         LOG_DEBUG("RESUME PC %08" PRIx32 "%s", address, !current ? "!" : "");
471
472         /* clear breakpoints/watchpoints and VCR*/
473         arm11_sc7_clear_vbw(arm11);
474
475         if (!debug_execution)
476                 target_free_all_working_areas(target);
477
478         /* Set up breakpoints */
479         if (handle_breakpoints)
480         {
481                 /* check if one matches PC and step over it if necessary */
482
483                 struct breakpoint *     bp;
484
485                 for (bp = target->breakpoints; bp; bp = bp->next)
486                 {
487                         if (bp->address == address)
488                         {
489                                 LOG_DEBUG("must step over %08" PRIx32 "", bp->address);
490                                 arm11_step(target, 1, 0, 0);
491                                 break;
492                         }
493                 }
494
495                 /* set all breakpoints */
496
497                 unsigned brp_num = 0;
498
499                 for (bp = target->breakpoints; bp; bp = bp->next)
500                 {
501                         struct arm11_sc7_action brp[2];
502
503                         brp[0].write    = 1;
504                         brp[0].address  = ARM11_SC7_BVR0 + brp_num;
505                         brp[0].value    = bp->address;
506                         brp[1].write    = 1;
507                         brp[1].address  = ARM11_SC7_BCR0 + brp_num;
508                         brp[1].value    = 0x1 | (3 << 1) | (0x0F << 5) | (0 << 14) | (0 << 16) | (0 << 20) | (0 << 21);
509
510                         arm11_sc7_run(arm11, brp, ARRAY_SIZE(brp));
511
512                         LOG_DEBUG("Add BP %d at %08" PRIx32, brp_num,
513                                         bp->address);
514
515                         brp_num++;
516                 }
517
518                 if (arm11_vcr)
519                         arm11_sc7_set_vcr(arm11, arm11_vcr);
520         }
521
522         arm11_leave_debug_state(arm11, handle_breakpoints);
523
524         arm11_add_IR(arm11, ARM11_RESTART, TAP_IDLE);
525
526         CHECK_RETVAL(jtag_execute_queue());
527
528         int i = 0;
529         while (1)
530         {
531                 CHECK_RETVAL(arm11_read_DSCR(arm11));
532
533                 LOG_DEBUG("DSCR %08x", (unsigned) arm11->dscr);
534
535                 if (arm11->dscr & DSCR_CORE_RESTARTED)
536                         break;
537
538
539                 long long then = 0;
540                 if (i == 1000)
541                 {
542                         then = timeval_ms();
543                 }
544                 if (i >= 1000)
545                 {
546                         if ((timeval_ms()-then) > 1000)
547                         {
548                                 LOG_WARNING("Timeout (1000ms) waiting for instructions to complete");
549                                 return ERROR_FAIL;
550                         }
551                 }
552                 i++;
553         }
554
555         target->debug_reason = DBG_REASON_NOTHALTED;
556         if (!debug_execution)
557                 target->state = TARGET_RUNNING;
558         else
559                 target->state = TARGET_DEBUG_RUNNING;
560         CHECK_RETVAL(target_call_event_callbacks(target, TARGET_EVENT_RESUMED));
561
562         return ERROR_OK;
563 }
564
565 static int arm11_step(struct target *target, int current,
566                 uint32_t address, int handle_breakpoints)
567 {
568         LOG_DEBUG("target->state: %s",
569                 target_state_name(target));
570
571         if (target->state != TARGET_HALTED)
572         {
573                 LOG_WARNING("target was not halted");
574                 return ERROR_TARGET_NOT_HALTED;
575         }
576
577         struct arm11_common *arm11 = target_to_arm11(target);
578
579         address = arm11_nextpc(arm11, current, address);
580
581         LOG_DEBUG("STEP PC %08" PRIx32 "%s", address, !current ? "!" : "");
582
583
584         /** \todo TODO: Thumb not supported here */
585
586         uint32_t        next_instruction;
587
588         CHECK_RETVAL(arm11_read_memory_word(arm11, address, &next_instruction));
589
590         /* skip over BKPT */
591         if ((next_instruction & 0xFFF00070) == 0xe1200070)
592         {
593                 address = arm11_nextpc(arm11, 0, address + 4);
594                 LOG_DEBUG("Skipping BKPT");
595         }
596         /* skip over Wait for interrupt / Standby */
597         /* mcr  15, 0, r?, cr7, cr0, {4} */
598         else if ((next_instruction & 0xFFFF0FFF) == 0xee070f90)
599         {
600                 address = arm11_nextpc(arm11, 0, address + 4);
601                 LOG_DEBUG("Skipping WFI");
602         }
603         /* ignore B to self */
604         else if ((next_instruction & 0xFEFFFFFF) == 0xeafffffe)
605         {
606                 LOG_DEBUG("Not stepping jump to self");
607         }
608         else
609         {
610                 /** \todo TODO: check if break-/watchpoints make any sense at all in combination
611                 * with this. */
612
613                 /** \todo TODO: check if disabling IRQs might be a good idea here. Alternatively
614                 * the VCR might be something worth looking into. */
615
616
617                 /* Set up breakpoint for stepping */
618
619                 struct arm11_sc7_action brp[2];
620
621                 brp[0].write    = 1;
622                 brp[0].address  = ARM11_SC7_BVR0;
623                 brp[1].write    = 1;
624                 brp[1].address  = ARM11_SC7_BCR0;
625
626                 if (arm11_config_hardware_step)
627                 {
628                         /* Hardware single stepping ("instruction address
629                          * mismatch") is used if enabled.  It's not quite
630                          * exactly "run one instruction"; "branch to here"
631                          * loops won't break, neither will some other cases,
632                          * but it's probably the best default.
633                          *
634                          * Hardware single stepping isn't supported on v6
635                          * debug modules.  ARM1176 and v7 can support it...
636                          *
637                          * FIXME Thumb stepping likely needs to use 0x03
638                          * or 0xc0 byte masks, not 0x0f.
639                          */
640                          brp[0].value   = address;
641                          brp[1].value   = 0x1 | (3 << 1) | (0x0F << 5)
642                                         | (0 << 14) | (0 << 16) | (0 << 20)
643                                         | (2 << 21);
644                 } else
645                 {
646                         /* Sets a breakpoint on the next PC, as calculated
647                          * by instruction set simulation.
648                          *
649                          * REVISIT stepping Thumb on ARM1156 requires Thumb2
650                          * support from the simulator.
651                          */
652                         uint32_t next_pc;
653                         int retval;
654
655                         retval = arm_simulate_step(target, &next_pc);
656                         if (retval != ERROR_OK)
657                                 return retval;
658
659                         brp[0].value    = next_pc;
660                         brp[1].value    = 0x1 | (3 << 1) | (0x0F << 5)
661                                         | (0 << 14) | (0 << 16) | (0 << 20)
662                                         | (0 << 21);
663                 }
664
665                 CHECK_RETVAL(arm11_sc7_run(arm11, brp, ARRAY_SIZE(brp)));
666
667                 /* resume */
668
669
670                 if (arm11_config_step_irq_enable)
671                         /* this disable should be redundant ... */
672                         arm11->dscr &= ~DSCR_INT_DIS;
673                 else
674                         arm11->dscr |= DSCR_INT_DIS;
675
676
677                 CHECK_RETVAL(arm11_leave_debug_state(arm11, handle_breakpoints));
678
679                 arm11_add_IR(arm11, ARM11_RESTART, TAP_IDLE);
680
681                 CHECK_RETVAL(jtag_execute_queue());
682
683                 /* wait for halt */
684                 int i = 0;
685
686                 while (1)
687                 {
688                         const uint32_t mask = DSCR_CORE_RESTARTED
689                                         | DSCR_CORE_HALTED;
690
691                         CHECK_RETVAL(arm11_read_DSCR(arm11));
692                         LOG_DEBUG("DSCR %08x e", (unsigned) arm11->dscr);
693
694                         if ((arm11->dscr & mask) == mask)
695                                 break;
696
697                         long long then = 0;
698                         if (i == 1000)
699                         {
700                                 then = timeval_ms();
701                         }
702                         if (i >= 1000)
703                         {
704                                 if ((timeval_ms()-then) > 1000)
705                                 {
706                                         LOG_WARNING("Timeout (1000ms) waiting for instructions to complete");
707                                         return ERROR_FAIL;
708                                 }
709                         }
710                         i++;
711                 }
712
713                 /* clear breakpoint */
714                 arm11_sc7_clear_vbw(arm11);
715
716                 /* save state */
717                 CHECK_RETVAL(arm11_debug_entry(arm11));
718
719                 /* restore default state */
720                 arm11->dscr &= ~DSCR_INT_DIS;
721
722         }
723
724         target->debug_reason = DBG_REASON_SINGLESTEP;
725
726         CHECK_RETVAL(target_call_event_callbacks(target, TARGET_EVENT_HALTED));
727
728         return ERROR_OK;
729 }
730
731 static int arm11_assert_reset(struct target *target)
732 {
733         int retval;
734         struct arm11_common *arm11 = target_to_arm11(target);
735
736         retval = arm11_check_init(arm11);
737         if (retval != ERROR_OK)
738                 return retval;
739
740         target->state = TARGET_UNKNOWN;
741
742         /* we would very much like to reset into the halted, state,
743          * but resetting and halting is second best... */
744         if (target->reset_halt)
745         {
746                 CHECK_RETVAL(target_halt(target));
747         }
748
749
750         /* srst is funny. We can not do *anything* else while it's asserted
751          * and it has unkonwn side effects. Make sure no other code runs
752          * meanwhile.
753          *
754          * Code below assumes srst:
755          *
756          * - Causes power-on-reset (but of what parts of the system?). Bug
757          * in arm11?
758          *
759          * - Messes us TAP state without asserting trst.
760          *
761          * - There is another bug in the arm11 core. When you generate an access to
762          * external logic (for example ddr controller via AHB bus) and that block
763          * is not configured (perhaps it is still held in reset), that transaction
764          * will never complete. This will hang arm11 core but it will also hang
765          * JTAG controller. Nothing, short of srst assertion will bring it out of
766          * this.
767          *
768          * Mysteries:
769          *
770          * - What should the PC be after an srst reset when starting in the halted
771          * state?
772          */
773
774         jtag_add_reset(0, 1);
775         jtag_add_reset(0, 0);
776
777         /* How long do we have to wait? */
778         jtag_add_sleep(5000);
779
780         /* un-mess up TAP state */
781         jtag_add_tlr();
782
783         retval = jtag_execute_queue();
784         if (retval != ERROR_OK)
785         {
786                 return retval;
787         }
788
789         return ERROR_OK;
790 }
791
792 static int arm11_deassert_reset(struct target *target)
793 {
794         return ERROR_OK;
795 }
796
797 static int arm11_soft_reset_halt(struct target *target)
798 {
799         LOG_WARNING("Not implemented: %s", __func__);
800
801         return ERROR_FAIL;
802 }
803
804 /* target memory access
805  * size: 1 = byte (8bit), 2 = half-word (16bit), 4 = word (32bit)
806  * count: number of items of <size>
807  *
808  * arm11_config_memrw_no_increment - in the future we may want to be able
809  * to read/write a range of data to a "port". a "port" is an action on
810  * read memory address for some peripheral.
811  */
812 static int arm11_read_memory_inner(struct target *target,
813                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer,
814                 bool arm11_config_memrw_no_increment)
815 {
816         /** \todo TODO: check if buffer cast to uint32_t* and uint16_t* might cause alignment problems */
817         int retval;
818
819         if (target->state != TARGET_HALTED)
820         {
821                 LOG_WARNING("target was not halted");
822                 return ERROR_TARGET_NOT_HALTED;
823         }
824
825         LOG_DEBUG("ADDR %08" PRIx32 "  SIZE %08" PRIx32 "  COUNT %08" PRIx32 "", address, size, count);
826
827         struct arm11_common *arm11 = target_to_arm11(target);
828
829         retval = arm11_run_instr_data_prepare(arm11);
830         if (retval != ERROR_OK)
831                 return retval;
832
833         /* MRC p14,0,r0,c0,c5,0 */
834         retval = arm11_run_instr_data_to_core1(arm11, 0xee100e15, address);
835         if (retval != ERROR_OK)
836                 return retval;
837
838         switch (size)
839         {
840         case 1:
841                 arm11->arm.core_cache->reg_list[1].dirty = true;
842
843                 for (size_t i = 0; i < count; i++)
844                 {
845                         /* ldrb    r1, [r0], #1 */
846                         /* ldrb    r1, [r0] */
847                         arm11_run_instr_no_data1(arm11,
848                                         !arm11_config_memrw_no_increment ? 0xe4d01001 : 0xe5d01000);
849
850                         uint32_t res;
851                         /* MCR p14,0,R1,c0,c5,0 */
852                         arm11_run_instr_data_from_core(arm11, 0xEE001E15, &res, 1);
853
854                         *buffer++ = res;
855                 }
856
857                 break;
858
859         case 2:
860                 {
861                         arm11->arm.core_cache->reg_list[1].dirty = true;
862
863                         for (size_t i = 0; i < count; i++)
864                         {
865                                 /* ldrh    r1, [r0], #2 */
866                                 arm11_run_instr_no_data1(arm11,
867                                         !arm11_config_memrw_no_increment ? 0xe0d010b2 : 0xe1d010b0);
868
869                                 uint32_t res;
870
871                                 /* MCR p14,0,R1,c0,c5,0 */
872                                 arm11_run_instr_data_from_core(arm11, 0xEE001E15, &res, 1);
873
874                                 uint16_t svalue = res;
875                                 memcpy(buffer + i * sizeof(uint16_t), &svalue, sizeof(uint16_t));
876                         }
877
878                         break;
879                 }
880
881         case 4:
882                 {
883                 uint32_t instr = !arm11_config_memrw_no_increment ? 0xecb05e01 : 0xed905e00;
884                 /** \todo TODO: buffer cast to uint32_t* causes alignment warnings */
885                 uint32_t *words = (uint32_t *)buffer;
886
887                 /* LDC p14,c5,[R0],#4 */
888                 /* LDC p14,c5,[R0] */
889                 arm11_run_instr_data_from_core(arm11, instr, words, count);
890                 break;
891                 }
892         }
893
894         return arm11_run_instr_data_finish(arm11);
895 }
896
897 static int arm11_read_memory(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
898 {
899         return arm11_read_memory_inner(target, address, size, count, buffer, false);
900 }
901
902 /*
903 * no_increment - in the future we may want to be able
904 * to read/write a range of data to a "port". a "port" is an action on
905 * read memory address for some peripheral.
906 */
907 static int arm11_write_memory_inner(struct target *target,
908                 uint32_t address, uint32_t size,
909                 uint32_t count, uint8_t *buffer,
910                 bool no_increment)
911 {
912         int retval;
913
914         if (target->state != TARGET_HALTED)
915         {
916                 LOG_WARNING("target was not halted");
917                 return ERROR_TARGET_NOT_HALTED;
918         }
919
920         LOG_DEBUG("ADDR %08" PRIx32 "  SIZE %08" PRIx32 "  COUNT %08" PRIx32 "", address, size, count);
921
922         struct arm11_common *arm11 = target_to_arm11(target);
923
924         retval = arm11_run_instr_data_prepare(arm11);
925         if (retval != ERROR_OK)
926                 return retval;
927
928         /* MRC p14,0,r0,c0,c5,0 */
929         retval = arm11_run_instr_data_to_core1(arm11, 0xee100e15, address);
930         if (retval != ERROR_OK)
931                 return retval;
932
933         /* burst writes are not used for single words as those may well be
934          * reset init script writes.
935          *
936          * The other advantage is that as burst writes are default, we'll
937          * now exercise both burst and non-burst code paths with the
938          * default settings, increasing code coverage.
939          */
940         bool burst = arm11_config_memwrite_burst && (count > 1);
941
942         switch (size)
943         {
944         case 1:
945                 {
946                         arm11->arm.core_cache->reg_list[1].dirty = true;
947
948                         for (size_t i = 0; i < count; i++)
949                         {
950                                 /* MRC p14,0,r1,c0,c5,0 */
951                                 retval = arm11_run_instr_data_to_core1(arm11, 0xee101e15, *buffer++);
952                                 if (retval != ERROR_OK)
953                                         return retval;
954
955                                 /* strb    r1, [r0], #1 */
956                                 /* strb    r1, [r0] */
957                                 retval = arm11_run_instr_no_data1(arm11,
958                                         !no_increment
959                                                 ? 0xe4c01001
960                                                 : 0xe5c01000);
961                                 if (retval != ERROR_OK)
962                                         return retval;
963                         }
964
965                         break;
966                 }
967
968         case 2:
969                 {
970                         arm11->arm.core_cache->reg_list[1].dirty = true;
971
972                         for (size_t i = 0; i < count; i++)
973                         {
974                                 uint16_t value;
975                                 memcpy(&value, buffer + i * sizeof(uint16_t), sizeof(uint16_t));
976
977                                 /* MRC p14,0,r1,c0,c5,0 */
978                                 retval = arm11_run_instr_data_to_core1(arm11, 0xee101e15, value);
979                                 if (retval != ERROR_OK)
980                                         return retval;
981
982                                 /* strh    r1, [r0], #2 */
983                                 /* strh    r1, [r0] */
984                                 retval = arm11_run_instr_no_data1(arm11,
985                                         !no_increment
986                                                 ? 0xe0c010b2
987                                                 : 0xe1c010b0);
988                                 if (retval != ERROR_OK)
989                                         return retval;
990                         }
991
992                         break;
993                 }
994
995         case 4: {
996                 uint32_t instr = !no_increment ? 0xeca05e01 : 0xed805e00;
997
998                 /** \todo TODO: buffer cast to uint32_t* causes alignment warnings */
999                 uint32_t *words = (uint32_t*)buffer;
1000
1001                 if (!burst)
1002                 {
1003                         /* STC p14,c5,[R0],#4 */
1004                         /* STC p14,c5,[R0]*/
1005                         retval = arm11_run_instr_data_to_core(arm11, instr, words, count);
1006                         if (retval != ERROR_OK)
1007                                 return retval;
1008                 }
1009                 else
1010                 {
1011                         /* STC p14,c5,[R0],#4 */
1012                         /* STC p14,c5,[R0]*/
1013                         retval = arm11_run_instr_data_to_core_noack(arm11, instr, words, count);
1014                         if (retval != ERROR_OK)
1015                                 return retval;
1016                 }
1017
1018                 break;
1019         }
1020         }
1021
1022         /* r0 verification */
1023         if (!no_increment)
1024         {
1025                 uint32_t r0;
1026
1027                 /* MCR p14,0,R0,c0,c5,0 */
1028                 retval = arm11_run_instr_data_from_core(arm11, 0xEE000E15, &r0, 1);
1029                 if (retval != ERROR_OK)
1030                         return retval;
1031
1032                 if (address + size * count != r0)
1033                 {
1034                         LOG_ERROR("Data transfer failed. Expected end "
1035                                         "address 0x%08x, got 0x%08x",
1036                                         (unsigned) (address + size * count),
1037                                         (unsigned) r0);
1038
1039                         if (burst)
1040                                 LOG_ERROR("use 'arm11 memwrite burst disable' to disable fast burst mode");
1041
1042                         if (arm11_config_memwrite_error_fatal)
1043                                 return ERROR_FAIL;
1044                 }
1045         }
1046
1047         return arm11_run_instr_data_finish(arm11);
1048 }
1049
1050 static int arm11_write_memory(struct target *target,
1051                 uint32_t address, uint32_t size,
1052                 uint32_t count, uint8_t *buffer)
1053 {
1054         /* pointer increment matters only for multi-unit writes ...
1055          * not e.g. to a "reset the chip" controller.
1056          */
1057         return arm11_write_memory_inner(target, address, size,
1058                         count, buffer, count == 1);
1059 }
1060
1061 /* write target memory in multiples of 4 byte, optimized for writing large quantities of data */
1062 static int arm11_bulk_write_memory(struct target *target,
1063                 uint32_t address, uint32_t count, uint8_t *buffer)
1064 {
1065         if (target->state != TARGET_HALTED)
1066         {
1067                 LOG_WARNING("target was not halted");
1068                 return ERROR_TARGET_NOT_HALTED;
1069         }
1070
1071         return arm11_write_memory(target, address, 4, count, buffer);
1072 }
1073
1074 /* target break-/watchpoint control
1075 * rw: 0 = write, 1 = read, 2 = access
1076 */
1077 static int arm11_add_breakpoint(struct target *target,
1078                 struct breakpoint *breakpoint)
1079 {
1080         struct arm11_common *arm11 = target_to_arm11(target);
1081
1082 #if 0
1083         if (breakpoint->type == BKPT_SOFT)
1084         {
1085                 LOG_INFO("sw breakpoint requested, but software breakpoints not enabled");
1086                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1087         }
1088 #endif
1089
1090         if (!arm11->free_brps)
1091         {
1092                 LOG_DEBUG("no breakpoint unit available for hardware breakpoint");
1093                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1094         }
1095
1096         if (breakpoint->length != 4)
1097         {
1098                 LOG_DEBUG("only breakpoints of four bytes length supported");
1099                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1100         }
1101
1102         arm11->free_brps--;
1103
1104         return ERROR_OK;
1105 }
1106
1107 static int arm11_remove_breakpoint(struct target *target,
1108                 struct breakpoint *breakpoint)
1109 {
1110         struct arm11_common *arm11 = target_to_arm11(target);
1111
1112         arm11->free_brps++;
1113
1114         return ERROR_OK;
1115 }
1116
1117 static int arm11_target_create(struct target *target, Jim_Interp *interp)
1118 {
1119         struct arm11_common *arm11;
1120
1121         if (target->tap == NULL)
1122                 return ERROR_FAIL;
1123
1124         if (target->tap->ir_length != 5)
1125         {
1126                 LOG_ERROR("'target arm11' expects IR LENGTH = 5");
1127                 return ERROR_COMMAND_SYNTAX_ERROR;
1128         }
1129
1130         arm11 = calloc(1, sizeof *arm11);
1131         if (!arm11)
1132                 return ERROR_FAIL;
1133
1134         armv4_5_init_arch_info(target, &arm11->arm);
1135
1136         arm11->jtag_info.tap = target->tap;
1137         arm11->jtag_info.scann_size = 5;
1138         arm11->jtag_info.scann_instr = ARM11_SCAN_N;
1139         arm11->jtag_info.cur_scan_chain = ~0;   /* invalid/unknown */
1140         arm11->jtag_info.intest_instr = ARM11_INTEST;
1141
1142         return ERROR_OK;
1143 }
1144
1145 static int arm11_init_target(struct command_context *cmd_ctx,
1146                 struct target *target)
1147 {
1148         /* Initialize anything we can set up without talking to the target */
1149         return ERROR_OK;
1150 }
1151
1152 /* talk to the target and set things up */
1153 static int arm11_examine(struct target *target)
1154 {
1155         int retval;
1156         char *type;
1157         struct arm11_common *arm11 = target_to_arm11(target);
1158         uint32_t didr, device_id;
1159         uint8_t implementor;
1160
1161         /* FIXME split into do-first-time and do-every-time logic ... */
1162
1163         /* check IDCODE */
1164
1165         arm11_add_IR(arm11, ARM11_IDCODE, ARM11_TAP_DEFAULT);
1166
1167         struct scan_field               idcode_field;
1168
1169         arm11_setup_field(arm11, 32, NULL, &device_id, &idcode_field);
1170
1171         arm11_add_dr_scan_vc(1, &idcode_field, TAP_DRPAUSE);
1172
1173         /* check DIDR */
1174
1175         arm11_add_debug_SCAN_N(arm11, 0x00, ARM11_TAP_DEFAULT);
1176
1177         arm11_add_IR(arm11, ARM11_INTEST, ARM11_TAP_DEFAULT);
1178
1179         struct scan_field               chain0_fields[2];
1180
1181         arm11_setup_field(arm11, 32, NULL, &didr, chain0_fields + 0);
1182         arm11_setup_field(arm11,  8, NULL, &implementor, chain0_fields + 1);
1183
1184         arm11_add_dr_scan_vc(ARRAY_SIZE(chain0_fields), chain0_fields, TAP_IDLE);
1185
1186         CHECK_RETVAL(jtag_execute_queue());
1187
1188         switch (device_id & 0x0FFFF000)
1189         {
1190         case 0x07B36000:
1191                 type = "ARM1136";
1192                 break;
1193         case 0x07B56000:
1194                 type = "ARM1156";
1195                 break;
1196         case 0x07B76000:
1197                 arm11->arm.core_type = ARM_MODE_MON;
1198                 type = "ARM1176";
1199                 break;
1200         default:
1201                 LOG_ERROR("'target arm11' expects IDCODE 0x*7B*7****");
1202                 return ERROR_FAIL;
1203         }
1204         LOG_INFO("found %s", type);
1205
1206         /* unlikely this could ever fail, but ... */
1207         switch ((didr >> 16) & 0x0F) {
1208         case ARM11_DEBUG_V6:
1209         case ARM11_DEBUG_V61:           /* supports security extensions */
1210                 break;
1211         default:
1212                 LOG_ERROR("Only ARM v6 and v6.1 debug supported.");
1213                 return ERROR_FAIL;
1214         }
1215
1216         arm11->brp = ((didr >> 24) & 0x0F) + 1;
1217
1218         /** \todo TODO: reserve one brp slot if we allow breakpoints during step */
1219         arm11->free_brps = arm11->brp;
1220
1221         LOG_DEBUG("IDCODE %08" PRIx32 " IMPLEMENTOR %02x DIDR %08" PRIx32,
1222                         device_id, implementor, didr);
1223
1224         /* as a side-effect this reads DSCR and thus
1225          * clears the ARM11_DSCR_STICKY_PRECISE_DATA_ABORT / Sticky Precise Data Abort Flag
1226          * as suggested by the spec.
1227          */
1228
1229         retval = arm11_check_init(arm11);
1230         if (retval != ERROR_OK)
1231                 return retval;
1232
1233         /* Build register cache "late", after target_init(), since we
1234          * want to know if this core supports Secure Monitor mode.
1235          */
1236         if (!target_was_examined(target))
1237                 retval = arm11_dpm_init(arm11, didr);
1238
1239         /* ETM on ARM11 still uses original scanchain 6 access mode */
1240         if (arm11->arm.etm && !target_was_examined(target)) {
1241                 *register_get_last_cache_p(&target->reg_cache) =
1242                         etm_build_reg_cache(target, &arm11->jtag_info,
1243                                         arm11->arm.etm);
1244                 retval = etm_setup(target);
1245         }
1246
1247         target_set_examined(target);
1248
1249         return ERROR_OK;
1250 }
1251
1252
1253 /* FIXME all these BOOL_WRAPPER things should be modifying
1254  * per-instance state, not shared state; ditto the vector
1255  * catch register support.  Scan chains with multiple cores
1256  * should be able to say "work with this core like this,
1257  * that core like that".  Example, ARM11 MPCore ...
1258  */
1259
1260 #define ARM11_BOOL_WRAPPER(name, print_name)    \
1261                 COMMAND_HANDLER(arm11_handle_bool_##name) \
1262                 { \
1263                         return CALL_COMMAND_HANDLER(handle_command_parse_bool, \
1264                                         &arm11_config_##name, print_name); \
1265                 }
1266
1267 ARM11_BOOL_WRAPPER(memwrite_burst, "memory write burst mode")
1268 ARM11_BOOL_WRAPPER(memwrite_error_fatal, "fatal error mode for memory writes")
1269 ARM11_BOOL_WRAPPER(step_irq_enable, "IRQs while stepping")
1270 ARM11_BOOL_WRAPPER(hardware_step, "hardware single step")
1271
1272 COMMAND_HANDLER(arm11_handle_vcr)
1273 {
1274         switch (CMD_ARGC) {
1275         case 0:
1276                 break;
1277         case 1:
1278                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], arm11_vcr);
1279                 break;
1280         default:
1281                 return ERROR_COMMAND_SYNTAX_ERROR;
1282         }
1283
1284         LOG_INFO("VCR 0x%08" PRIx32 "", arm11_vcr);
1285         return ERROR_OK;
1286 }
1287
1288 static const struct command_registration arm11_mw_command_handlers[] = {
1289         {
1290                 .name = "burst",
1291                 .handler = &arm11_handle_bool_memwrite_burst,
1292                 .mode = COMMAND_ANY,
1293                 .help = "Enable/Disable non-standard but fast burst mode"
1294                         " (default: enabled)",
1295         },
1296         {
1297                 .name = "error_fatal",
1298                 .handler = &arm11_handle_bool_memwrite_error_fatal,
1299                 .mode = COMMAND_ANY,
1300                 .help = "Terminate program if transfer error was found"
1301                         " (default: enabled)",
1302         },
1303         COMMAND_REGISTRATION_DONE
1304 };
1305 static const struct command_registration arm11_any_command_handlers[] = {
1306         {
1307                 /* "hardware_step" is only here to check if the default
1308                  * simulate + breakpoint implementation is broken.
1309                  * TEMPORARY! NOT DOCUMENTED! */
1310                 .name = "hardware_step",
1311                 .handler = &arm11_handle_bool_hardware_step,
1312                 .mode = COMMAND_ANY,
1313                 .help = "DEBUG ONLY - Hardware single stepping"
1314                         " (default: disabled)",
1315                 .usage = "(enable|disable)",
1316         },
1317         {
1318                 .name = "memwrite",
1319                 .mode = COMMAND_ANY,
1320                 .help = "memwrite command group",
1321                 .chain = arm11_mw_command_handlers,
1322         },
1323         {
1324                 .name = "step_irq_enable",
1325                 .handler = &arm11_handle_bool_step_irq_enable,
1326                 .mode = COMMAND_ANY,
1327                 .help = "Enable interrupts while stepping"
1328                         " (default: disabled)",
1329         },
1330         {
1331                 .name = "vcr",
1332                 .handler = &arm11_handle_vcr,
1333                 .mode = COMMAND_ANY,
1334                 .help = "Control (Interrupt) Vector Catch Register",
1335         },
1336         COMMAND_REGISTRATION_DONE
1337 };
1338 static const struct command_registration arm11_command_handlers[] = {
1339         {
1340                 .chain = arm_command_handlers,
1341         },
1342         {
1343                 .chain = etm_command_handlers,
1344         },
1345         {
1346                 .name = "arm11",
1347                 .mode = COMMAND_ANY,
1348                 .help = "ARM11 command group",
1349                 .chain = arm11_any_command_handlers,
1350         },
1351         COMMAND_REGISTRATION_DONE
1352 };
1353
1354 /** Holds methods for ARM11xx targets. */
1355 struct target_type arm11_target = {
1356         .name =                 "arm11",
1357
1358         .poll =                 arm11_poll,
1359         .arch_state =           arm11_arch_state,
1360
1361         .target_request_data =  arm11_target_request_data,
1362
1363         .halt =                 arm11_halt,
1364         .resume =               arm11_resume,
1365         .step =                 arm11_step,
1366
1367         .assert_reset =         arm11_assert_reset,
1368         .deassert_reset =       arm11_deassert_reset,
1369         .soft_reset_halt =      arm11_soft_reset_halt,
1370
1371         .get_gdb_reg_list =     armv4_5_get_gdb_reg_list,
1372
1373         .read_memory =          arm11_read_memory,
1374         .write_memory =         arm11_write_memory,
1375
1376         .bulk_write_memory =    arm11_bulk_write_memory,
1377
1378         .checksum_memory =      arm_checksum_memory,
1379         .blank_check_memory =   arm_blank_check_memory,
1380
1381         .add_breakpoint =       arm11_add_breakpoint,
1382         .remove_breakpoint =    arm11_remove_breakpoint,
1383
1384         .run_algorithm =        armv4_5_run_algorithm,
1385
1386         .commands =             arm11_command_handlers,
1387         .target_create =        arm11_target_create,
1388         .init_target =          arm11_init_target,
1389         .examine =              arm11_examine,
1390 };