change #include "time_support.h" to <helper/time_support.h>
[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 static bool arm11_config_memwrite_burst = true;
44 static bool arm11_config_memwrite_error_fatal = true;
45 static uint32_t arm11_vcr = 0;
46 static bool arm11_config_step_irq_enable = false;
47 static bool arm11_config_hardware_step = false;
48
49 static int arm11_step(struct target *target, int current,
50                 uint32_t address, int handle_breakpoints);
51
52
53 /** Check and if necessary take control of the system
54  *
55  * \param arm11         Target state variable.
56  */
57 static int arm11_check_init(struct arm11_common *arm11)
58 {
59         CHECK_RETVAL(arm11_read_DSCR(arm11));
60         LOG_DEBUG("DSCR %08x", (unsigned) arm11->dscr);
61
62         if (!(arm11->dscr & ARM11_DSCR_MODE_SELECT))
63         {
64                 LOG_DEBUG("Bringing target into debug mode");
65
66                 arm11->dscr |= ARM11_DSCR_MODE_SELECT;          /* Halt debug-mode */
67                 arm11_write_DSCR(arm11, arm11->dscr);
68
69                 /* add further reset initialization here */
70
71                 arm11->simulate_reset_on_next_halt = true;
72
73                 if (arm11->dscr & ARM11_DSCR_CORE_HALTED)
74                 {
75                         /** \todo TODO: this needs further scrutiny because
76                           * arm11_debug_entry() never gets called.  (WHY NOT?)
77                           * As a result we don't read the actual register states from
78                           * the target.
79                           */
80
81                         arm11->arm.target->state = TARGET_HALTED;
82                         arm11->arm.target->debug_reason =
83                                         arm11_get_DSCR_debug_reason(arm11->dscr);
84                 }
85                 else
86                 {
87                         arm11->arm.target->state = TARGET_RUNNING;
88                         arm11->arm.target->debug_reason = DBG_REASON_NOTHALTED;
89                 }
90
91                 arm11_sc7_clear_vbw(arm11);
92         }
93
94         return ERROR_OK;
95 }
96
97 /**
98  * Save processor state.  This is called after a HALT instruction
99  * succeeds, and on other occasions the processor enters debug mode
100  * (breakpoint, watchpoint, etc).  Caller has updated arm11->dscr.
101  */
102 static int arm11_debug_entry(struct arm11_common *arm11)
103 {
104         int retval;
105
106         arm11->arm.target->state = TARGET_HALTED;
107         arm11->arm.target->debug_reason =
108                         arm11_get_DSCR_debug_reason(arm11->dscr);
109
110         /* REVISIT entire cache should already be invalid !!! */
111         register_cache_invalidate(arm11->arm.core_cache);
112
113         /* See e.g. ARM1136 TRM, "14.8.4 Entering Debug state" */
114
115         /* maybe save wDTR (pending DCC write to debug SW, e.g. libdcc) */
116         arm11->is_wdtr_saved = !!(arm11->dscr & ARM11_DSCR_WDTR_FULL);
117         if (arm11->is_wdtr_saved)
118         {
119                 arm11_add_debug_SCAN_N(arm11, 0x05, ARM11_TAP_DEFAULT);
120
121                 arm11_add_IR(arm11, ARM11_INTEST, ARM11_TAP_DEFAULT);
122
123                 struct scan_field       chain5_fields[3];
124
125                 arm11_setup_field(arm11, 32, NULL,
126                                 &arm11->saved_wdtr, chain5_fields + 0);
127                 arm11_setup_field(arm11,  1, NULL, NULL,                chain5_fields + 1);
128                 arm11_setup_field(arm11,  1, NULL, NULL,                chain5_fields + 2);
129
130                 arm11_add_dr_scan_vc(ARRAY_SIZE(chain5_fields), chain5_fields, TAP_DRPAUSE);
131
132         }
133
134         /* DSCR: set ARM11_DSCR_EXECUTE_ARM_INSTRUCTION_ENABLE
135          *
136          * ARM1176 spec says this is needed only for wDTR/rDTR's "ITR mode",
137          * but not to issue ITRs. ARM1136 seems to require this to issue
138          * ITR's as well...
139          */
140
141         arm11_write_DSCR(arm11, ARM11_DSCR_EXECUTE_ARM_INSTRUCTION_ENABLE
142                                 | 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 & ARM11_DSCR_RDTR_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 & (ARM11_DSCR_RDTR_FULL | ARM11_DSCR_WDTR_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 & ARM11_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 & ARM11_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 & ARM11_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         if (!debug_execution)
553         {
554                 target->state                   = TARGET_RUNNING;
555                 target->debug_reason    = DBG_REASON_NOTHALTED;
556
557                 CHECK_RETVAL(target_call_event_callbacks(target, TARGET_EVENT_RESUMED));
558         }
559         else
560         {
561                 target->state                   = TARGET_DEBUG_RUNNING;
562                 target->debug_reason    = DBG_REASON_NOTHALTED;
563
564                 CHECK_RETVAL(target_call_event_callbacks(target, TARGET_EVENT_RESUMED));
565         }
566
567         return ERROR_OK;
568 }
569
570 static int arm11_step(struct target *target, int current,
571                 uint32_t address, int handle_breakpoints)
572 {
573         LOG_DEBUG("target->state: %s",
574                 target_state_name(target));
575
576         if (target->state != TARGET_HALTED)
577         {
578                 LOG_WARNING("target was not halted");
579                 return ERROR_TARGET_NOT_HALTED;
580         }
581
582         struct arm11_common *arm11 = target_to_arm11(target);
583
584         address = arm11_nextpc(arm11, current, address);
585
586         LOG_DEBUG("STEP PC %08" PRIx32 "%s", address, !current ? "!" : "");
587
588
589         /** \todo TODO: Thumb not supported here */
590
591         uint32_t        next_instruction;
592
593         CHECK_RETVAL(arm11_read_memory_word(arm11, address, &next_instruction));
594
595         /* skip over BKPT */
596         if ((next_instruction & 0xFFF00070) == 0xe1200070)
597         {
598                 address = arm11_nextpc(arm11, 0, address + 4);
599                 LOG_DEBUG("Skipping BKPT");
600         }
601         /* skip over Wait for interrupt / Standby */
602         /* mcr  15, 0, r?, cr7, cr0, {4} */
603         else if ((next_instruction & 0xFFFF0FFF) == 0xee070f90)
604         {
605                 address = arm11_nextpc(arm11, 0, address + 4);
606                 LOG_DEBUG("Skipping WFI");
607         }
608         /* ignore B to self */
609         else if ((next_instruction & 0xFEFFFFFF) == 0xeafffffe)
610         {
611                 LOG_DEBUG("Not stepping jump to self");
612         }
613         else
614         {
615                 /** \todo TODO: check if break-/watchpoints make any sense at all in combination
616                 * with this. */
617
618                 /** \todo TODO: check if disabling IRQs might be a good idea here. Alternatively
619                 * the VCR might be something worth looking into. */
620
621
622                 /* Set up breakpoint for stepping */
623
624                 struct arm11_sc7_action brp[2];
625
626                 brp[0].write    = 1;
627                 brp[0].address  = ARM11_SC7_BVR0;
628                 brp[1].write    = 1;
629                 brp[1].address  = ARM11_SC7_BCR0;
630
631                 if (arm11_config_hardware_step)
632                 {
633                         /* Hardware single stepping ("instruction address
634                          * mismatch") is used if enabled.  It's not quite
635                          * exactly "run one instruction"; "branch to here"
636                          * loops won't break, neither will some other cases,
637                          * but it's probably the best default.
638                          *
639                          * Hardware single stepping isn't supported on v6
640                          * debug modules.  ARM1176 and v7 can support it...
641                          *
642                          * FIXME Thumb stepping likely needs to use 0x03
643                          * or 0xc0 byte masks, not 0x0f.
644                          */
645                          brp[0].value   = address;
646                          brp[1].value   = 0x1 | (3 << 1) | (0x0F << 5)
647                                         | (0 << 14) | (0 << 16) | (0 << 20)
648                                         | (2 << 21);
649                 } else
650                 {
651                         /* Sets a breakpoint on the next PC, as calculated
652                          * by instruction set simulation.
653                          *
654                          * REVISIT stepping Thumb on ARM1156 requires Thumb2
655                          * support from the simulator.
656                          */
657                         uint32_t next_pc;
658                         int retval;
659
660                         retval = arm_simulate_step(target, &next_pc);
661                         if (retval != ERROR_OK)
662                                 return retval;
663
664                         brp[0].value    = next_pc;
665                         brp[1].value    = 0x1 | (3 << 1) | (0x0F << 5)
666                                         | (0 << 14) | (0 << 16) | (0 << 20)
667                                         | (0 << 21);
668                 }
669
670                 CHECK_RETVAL(arm11_sc7_run(arm11, brp, ARRAY_SIZE(brp)));
671
672                 /* resume */
673
674
675                 if (arm11_config_step_irq_enable)
676                         /* this disable should be redundant ... */
677                         arm11->dscr &= ~ARM11_DSCR_INTERRUPTS_DISABLE;
678                 else
679                         arm11->dscr |= ARM11_DSCR_INTERRUPTS_DISABLE;
680
681
682                 CHECK_RETVAL(arm11_leave_debug_state(arm11, handle_breakpoints));
683
684                 arm11_add_IR(arm11, ARM11_RESTART, TAP_IDLE);
685
686                 CHECK_RETVAL(jtag_execute_queue());
687
688                 /* wait for halt */
689                 int i = 0;
690
691                 while (1)
692                 {
693                         const uint32_t mask = ARM11_DSCR_CORE_RESTARTED
694                                         | ARM11_DSCR_CORE_HALTED;
695
696                         CHECK_RETVAL(arm11_read_DSCR(arm11));
697                         LOG_DEBUG("DSCR %08x e", (unsigned) arm11->dscr);
698
699                         if ((arm11->dscr & mask) == mask)
700                                 break;
701
702                         long long then = 0;
703                         if (i == 1000)
704                         {
705                                 then = timeval_ms();
706                         }
707                         if (i >= 1000)
708                         {
709                                 if ((timeval_ms()-then) > 1000)
710                                 {
711                                         LOG_WARNING("Timeout (1000ms) waiting for instructions to complete");
712                                         return ERROR_FAIL;
713                                 }
714                         }
715                         i++;
716                 }
717
718                 /* clear breakpoint */
719                 arm11_sc7_clear_vbw(arm11);
720
721                 /* save state */
722                 CHECK_RETVAL(arm11_debug_entry(arm11));
723
724                 /* restore default state */
725                 arm11->dscr &= ~ARM11_DSCR_INTERRUPTS_DISABLE;
726
727         }
728
729         target->debug_reason    = DBG_REASON_SINGLESTEP;
730
731         CHECK_RETVAL(target_call_event_callbacks(target, TARGET_EVENT_HALTED));
732
733         return ERROR_OK;
734 }
735
736 static int arm11_assert_reset(struct target *target)
737 {
738         int retval;
739         struct arm11_common *arm11 = target_to_arm11(target);
740
741         retval = arm11_check_init(arm11);
742         if (retval != ERROR_OK)
743                 return retval;
744
745         target->state = TARGET_UNKNOWN;
746
747         /* we would very much like to reset into the halted, state,
748          * but resetting and halting is second best... */
749         if (target->reset_halt)
750         {
751                 CHECK_RETVAL(target_halt(target));
752         }
753
754
755         /* srst is funny. We can not do *anything* else while it's asserted
756          * and it has unkonwn side effects. Make sure no other code runs
757          * meanwhile.
758          *
759          * Code below assumes srst:
760          *
761          * - Causes power-on-reset (but of what parts of the system?). Bug
762          * in arm11?
763          *
764          * - Messes us TAP state without asserting trst.
765          *
766          * - There is another bug in the arm11 core. When you generate an access to
767          * external logic (for example ddr controller via AHB bus) and that block
768          * is not configured (perhaps it is still held in reset), that transaction
769          * will never complete. This will hang arm11 core but it will also hang
770          * JTAG controller. Nothing, short of srst assertion will bring it out of
771          * this.
772          *
773          * Mysteries:
774          *
775          * - What should the PC be after an srst reset when starting in the halted
776          * state?
777          */
778
779         jtag_add_reset(0, 1);
780         jtag_add_reset(0, 0);
781
782         /* How long do we have to wait? */
783         jtag_add_sleep(5000);
784
785         /* un-mess up TAP state */
786         jtag_add_tlr();
787
788         retval = jtag_execute_queue();
789         if (retval != ERROR_OK)
790         {
791                 return retval;
792         }
793
794         return ERROR_OK;
795 }
796
797 static int arm11_deassert_reset(struct target *target)
798 {
799         return ERROR_OK;
800 }
801
802 static int arm11_soft_reset_halt(struct target *target)
803 {
804         LOG_WARNING("Not implemented: %s", __func__);
805
806         return ERROR_FAIL;
807 }
808
809 /* target memory access
810  * size: 1 = byte (8bit), 2 = half-word (16bit), 4 = word (32bit)
811  * count: number of items of <size>
812  *
813  * arm11_config_memrw_no_increment - in the future we may want to be able
814  * to read/write a range of data to a "port". a "port" is an action on
815  * read memory address for some peripheral.
816  */
817 static int arm11_read_memory_inner(struct target *target,
818                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer,
819                 bool arm11_config_memrw_no_increment)
820 {
821         /** \todo TODO: check if buffer cast to uint32_t* and uint16_t* might cause alignment problems */
822         int retval;
823
824         if (target->state != TARGET_HALTED)
825         {
826                 LOG_WARNING("target was not halted");
827                 return ERROR_TARGET_NOT_HALTED;
828         }
829
830         LOG_DEBUG("ADDR %08" PRIx32 "  SIZE %08" PRIx32 "  COUNT %08" PRIx32 "", address, size, count);
831
832         struct arm11_common *arm11 = target_to_arm11(target);
833
834         retval = arm11_run_instr_data_prepare(arm11);
835         if (retval != ERROR_OK)
836                 return retval;
837
838         /* MRC p14,0,r0,c0,c5,0 */
839         retval = arm11_run_instr_data_to_core1(arm11, 0xee100e15, address);
840         if (retval != ERROR_OK)
841                 return retval;
842
843         switch (size)
844         {
845         case 1:
846                 arm11->arm.core_cache->reg_list[1].dirty = true;
847
848                 for (size_t i = 0; i < count; i++)
849                 {
850                         /* ldrb    r1, [r0], #1 */
851                         /* ldrb    r1, [r0] */
852                         arm11_run_instr_no_data1(arm11,
853                                         !arm11_config_memrw_no_increment ? 0xe4d01001 : 0xe5d01000);
854
855                         uint32_t res;
856                         /* MCR p14,0,R1,c0,c5,0 */
857                         arm11_run_instr_data_from_core(arm11, 0xEE001E15, &res, 1);
858
859                         *buffer++ = res;
860                 }
861
862                 break;
863
864         case 2:
865                 {
866                         arm11->arm.core_cache->reg_list[1].dirty = true;
867
868                         for (size_t i = 0; i < count; i++)
869                         {
870                                 /* ldrh    r1, [r0], #2 */
871                                 arm11_run_instr_no_data1(arm11,
872                                         !arm11_config_memrw_no_increment ? 0xe0d010b2 : 0xe1d010b0);
873
874                                 uint32_t res;
875
876                                 /* MCR p14,0,R1,c0,c5,0 */
877                                 arm11_run_instr_data_from_core(arm11, 0xEE001E15, &res, 1);
878
879                                 uint16_t svalue = res;
880                                 memcpy(buffer + i * sizeof(uint16_t), &svalue, sizeof(uint16_t));
881                         }
882
883                         break;
884                 }
885
886         case 4:
887                 {
888                 uint32_t instr = !arm11_config_memrw_no_increment ? 0xecb05e01 : 0xed905e00;
889                 /** \todo TODO: buffer cast to uint32_t* causes alignment warnings */
890                 uint32_t *words = (uint32_t *)buffer;
891
892                 /* LDC p14,c5,[R0],#4 */
893                 /* LDC p14,c5,[R0] */
894                 arm11_run_instr_data_from_core(arm11, instr, words, count);
895                 break;
896                 }
897         }
898
899         return arm11_run_instr_data_finish(arm11);
900 }
901
902 static int arm11_read_memory(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
903 {
904         return arm11_read_memory_inner(target, address, size, count, buffer, false);
905 }
906
907 /*
908 * no_increment - in the future we may want to be able
909 * to read/write a range of data to a "port". a "port" is an action on
910 * read memory address for some peripheral.
911 */
912 static int arm11_write_memory_inner(struct target *target,
913                 uint32_t address, uint32_t size,
914                 uint32_t count, uint8_t *buffer,
915                 bool no_increment)
916 {
917         int retval;
918
919         if (target->state != TARGET_HALTED)
920         {
921                 LOG_WARNING("target was not halted");
922                 return ERROR_TARGET_NOT_HALTED;
923         }
924
925         LOG_DEBUG("ADDR %08" PRIx32 "  SIZE %08" PRIx32 "  COUNT %08" PRIx32 "", address, size, count);
926
927         struct arm11_common *arm11 = target_to_arm11(target);
928
929         retval = arm11_run_instr_data_prepare(arm11);
930         if (retval != ERROR_OK)
931                 return retval;
932
933         /* MRC p14,0,r0,c0,c5,0 */
934         retval = arm11_run_instr_data_to_core1(arm11, 0xee100e15, address);
935         if (retval != ERROR_OK)
936                 return retval;
937
938         /* burst writes are not used for single words as those may well be
939          * reset init script writes.
940          *
941          * The other advantage is that as burst writes are default, we'll
942          * now exercise both burst and non-burst code paths with the
943          * default settings, increasing code coverage.
944          */
945         bool burst = arm11_config_memwrite_burst && (count > 1);
946
947         switch (size)
948         {
949         case 1:
950                 {
951                         arm11->arm.core_cache->reg_list[1].dirty = true;
952
953                         for (size_t i = 0; i < count; i++)
954                         {
955                                 /* MRC p14,0,r1,c0,c5,0 */
956                                 retval = arm11_run_instr_data_to_core1(arm11, 0xee101e15, *buffer++);
957                                 if (retval != ERROR_OK)
958                                         return retval;
959
960                                 /* strb    r1, [r0], #1 */
961                                 /* strb    r1, [r0] */
962                                 retval = arm11_run_instr_no_data1(arm11,
963                                         !no_increment
964                                                 ? 0xe4c01001
965                                                 : 0xe5c01000);
966                                 if (retval != ERROR_OK)
967                                         return retval;
968                         }
969
970                         break;
971                 }
972
973         case 2:
974                 {
975                         arm11->arm.core_cache->reg_list[1].dirty = true;
976
977                         for (size_t i = 0; i < count; i++)
978                         {
979                                 uint16_t value;
980                                 memcpy(&value, buffer + i * sizeof(uint16_t), sizeof(uint16_t));
981
982                                 /* MRC p14,0,r1,c0,c5,0 */
983                                 retval = arm11_run_instr_data_to_core1(arm11, 0xee101e15, value);
984                                 if (retval != ERROR_OK)
985                                         return retval;
986
987                                 /* strh    r1, [r0], #2 */
988                                 /* strh    r1, [r0] */
989                                 retval = arm11_run_instr_no_data1(arm11,
990                                         !no_increment
991                                                 ? 0xe0c010b2
992                                                 : 0xe1c010b0);
993                                 if (retval != ERROR_OK)
994                                         return retval;
995                         }
996
997                         break;
998                 }
999
1000         case 4: {
1001                 uint32_t instr = !no_increment ? 0xeca05e01 : 0xed805e00;
1002
1003                 /** \todo TODO: buffer cast to uint32_t* causes alignment warnings */
1004                 uint32_t *words = (uint32_t*)buffer;
1005
1006                 if (!burst)
1007                 {
1008                         /* STC p14,c5,[R0],#4 */
1009                         /* STC p14,c5,[R0]*/
1010                         retval = arm11_run_instr_data_to_core(arm11, instr, words, count);
1011                         if (retval != ERROR_OK)
1012                                 return retval;
1013                 }
1014                 else
1015                 {
1016                         /* STC p14,c5,[R0],#4 */
1017                         /* STC p14,c5,[R0]*/
1018                         retval = arm11_run_instr_data_to_core_noack(arm11, instr, words, count);
1019                         if (retval != ERROR_OK)
1020                                 return retval;
1021                 }
1022
1023                 break;
1024         }
1025         }
1026
1027         /* r0 verification */
1028         if (!no_increment)
1029         {
1030                 uint32_t r0;
1031
1032                 /* MCR p14,0,R0,c0,c5,0 */
1033                 retval = arm11_run_instr_data_from_core(arm11, 0xEE000E15, &r0, 1);
1034                 if (retval != ERROR_OK)
1035                         return retval;
1036
1037                 if (address + size * count != r0)
1038                 {
1039                         LOG_ERROR("Data transfer failed. Expected end "
1040                                         "address 0x%08x, got 0x%08x",
1041                                         (unsigned) (address + size * count),
1042                                         (unsigned) r0);
1043
1044                         if (burst)
1045                                 LOG_ERROR("use 'arm11 memwrite burst disable' to disable fast burst mode");
1046
1047                         if (arm11_config_memwrite_error_fatal)
1048                                 return ERROR_FAIL;
1049                 }
1050         }
1051
1052         return arm11_run_instr_data_finish(arm11);
1053 }
1054
1055 static int arm11_write_memory(struct target *target,
1056                 uint32_t address, uint32_t size,
1057                 uint32_t count, uint8_t *buffer)
1058 {
1059         /* pointer increment matters only for multi-unit writes ...
1060          * not e.g. to a "reset the chip" controller.
1061          */
1062         return arm11_write_memory_inner(target, address, size,
1063                         count, buffer, count == 1);
1064 }
1065
1066 /* write target memory in multiples of 4 byte, optimized for writing large quantities of data */
1067 static int arm11_bulk_write_memory(struct target *target,
1068                 uint32_t address, uint32_t count, uint8_t *buffer)
1069 {
1070         if (target->state != TARGET_HALTED)
1071         {
1072                 LOG_WARNING("target was not halted");
1073                 return ERROR_TARGET_NOT_HALTED;
1074         }
1075
1076         return arm11_write_memory(target, address, 4, count, buffer);
1077 }
1078
1079 /* target break-/watchpoint control
1080 * rw: 0 = write, 1 = read, 2 = access
1081 */
1082 static int arm11_add_breakpoint(struct target *target,
1083                 struct breakpoint *breakpoint)
1084 {
1085         struct arm11_common *arm11 = target_to_arm11(target);
1086
1087 #if 0
1088         if (breakpoint->type == BKPT_SOFT)
1089         {
1090                 LOG_INFO("sw breakpoint requested, but software breakpoints not enabled");
1091                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1092         }
1093 #endif
1094
1095         if (!arm11->free_brps)
1096         {
1097                 LOG_DEBUG("no breakpoint unit available for hardware breakpoint");
1098                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1099         }
1100
1101         if (breakpoint->length != 4)
1102         {
1103                 LOG_DEBUG("only breakpoints of four bytes length supported");
1104                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1105         }
1106
1107         arm11->free_brps--;
1108
1109         return ERROR_OK;
1110 }
1111
1112 static int arm11_remove_breakpoint(struct target *target,
1113                 struct breakpoint *breakpoint)
1114 {
1115         struct arm11_common *arm11 = target_to_arm11(target);
1116
1117         arm11->free_brps++;
1118
1119         return ERROR_OK;
1120 }
1121
1122 static int arm11_target_create(struct target *target, Jim_Interp *interp)
1123 {
1124         struct arm11_common *arm11;
1125
1126         if (target->tap == NULL)
1127                 return ERROR_FAIL;
1128
1129         if (target->tap->ir_length != 5)
1130         {
1131                 LOG_ERROR("'target arm11' expects IR LENGTH = 5");
1132                 return ERROR_COMMAND_SYNTAX_ERROR;
1133         }
1134
1135         arm11 = calloc(1, sizeof *arm11);
1136         if (!arm11)
1137                 return ERROR_FAIL;
1138
1139         armv4_5_init_arch_info(target, &arm11->arm);
1140
1141         arm11->jtag_info.tap = target->tap;
1142         arm11->jtag_info.scann_size = 5;
1143         arm11->jtag_info.scann_instr = ARM11_SCAN_N;
1144         /* cur_scan_chain == 0 */
1145         arm11->jtag_info.intest_instr = ARM11_INTEST;
1146
1147         return ERROR_OK;
1148 }
1149
1150 static int arm11_init_target(struct command_context *cmd_ctx,
1151                 struct target *target)
1152 {
1153         /* Initialize anything we can set up without talking to the target */
1154         return ERROR_OK;
1155 }
1156
1157 /* talk to the target and set things up */
1158 static int arm11_examine(struct target *target)
1159 {
1160         int retval;
1161         char *type;
1162         struct arm11_common *arm11 = target_to_arm11(target);
1163         uint32_t didr, device_id;
1164         uint8_t implementor;
1165
1166         /* FIXME split into do-first-time and do-every-time logic ... */
1167
1168         /* check IDCODE */
1169
1170         arm11_add_IR(arm11, ARM11_IDCODE, ARM11_TAP_DEFAULT);
1171
1172         struct scan_field               idcode_field;
1173
1174         arm11_setup_field(arm11, 32, NULL, &device_id, &idcode_field);
1175
1176         arm11_add_dr_scan_vc(1, &idcode_field, TAP_DRPAUSE);
1177
1178         /* check DIDR */
1179
1180         arm11_add_debug_SCAN_N(arm11, 0x00, ARM11_TAP_DEFAULT);
1181
1182         arm11_add_IR(arm11, ARM11_INTEST, ARM11_TAP_DEFAULT);
1183
1184         struct scan_field               chain0_fields[2];
1185
1186         arm11_setup_field(arm11, 32, NULL, &didr, chain0_fields + 0);
1187         arm11_setup_field(arm11,  8, NULL, &implementor, chain0_fields + 1);
1188
1189         arm11_add_dr_scan_vc(ARRAY_SIZE(chain0_fields), chain0_fields, TAP_IDLE);
1190
1191         CHECK_RETVAL(jtag_execute_queue());
1192
1193         switch (device_id & 0x0FFFF000)
1194         {
1195         case 0x07B36000:
1196                 type = "ARM1136";
1197                 break;
1198         case 0x07B56000:
1199                 type = "ARM1156";
1200                 break;
1201         case 0x07B76000:
1202                 arm11->arm.core_type = ARM_MODE_MON;
1203                 type = "ARM1176";
1204                 break;
1205         default:
1206                 LOG_ERROR("'target arm11' expects IDCODE 0x*7B*7****");
1207                 return ERROR_FAIL;
1208         }
1209         LOG_INFO("found %s", type);
1210
1211         /* unlikely this could ever fail, but ... */
1212         switch ((didr >> 16) & 0x0F) {
1213         case ARM11_DEBUG_V6:
1214         case ARM11_DEBUG_V61:           /* supports security extensions */
1215                 break;
1216         default:
1217                 LOG_ERROR("Only ARM v6 and v6.1 debug supported.");
1218                 return ERROR_FAIL;
1219         }
1220
1221         arm11->brp = ((didr >> 24) & 0x0F) + 1;
1222         arm11->wrp = ((didr >> 28) & 0x0F) + 1;
1223
1224         /** \todo TODO: reserve one brp slot if we allow breakpoints during step */
1225         arm11->free_brps = arm11->brp;
1226
1227         LOG_DEBUG("IDCODE %08" PRIx32 " IMPLEMENTOR %02x DIDR %08" PRIx32,
1228                         device_id, implementor, didr);
1229
1230         /* as a side-effect this reads DSCR and thus
1231          * clears the ARM11_DSCR_STICKY_PRECISE_DATA_ABORT / Sticky Precise Data Abort Flag
1232          * as suggested by the spec.
1233          */
1234
1235         retval = arm11_check_init(arm11);
1236         if (retval != ERROR_OK)
1237                 return retval;
1238
1239         /* Build register cache "late", after target_init(), since we
1240          * want to know if this core supports Secure Monitor mode.
1241          */
1242         if (!target_was_examined(target))
1243                 retval = arm11_dpm_init(arm11, didr);
1244
1245         /* ETM on ARM11 still uses original scanchain 6 access mode */
1246         if (arm11->arm.etm && !target_was_examined(target)) {
1247                 *register_get_last_cache_p(&target->reg_cache) =
1248                         etm_build_reg_cache(target, &arm11->jtag_info,
1249                                         arm11->arm.etm);
1250                 retval = etm_setup(target);
1251         }
1252
1253         target_set_examined(target);
1254
1255         return ERROR_OK;
1256 }
1257
1258
1259 /* FIXME all these BOOL_WRAPPER things should be modifying
1260  * per-instance state, not shared state; ditto the vector
1261  * catch register support.  Scan chains with multiple cores
1262  * should be able to say "work with this core like this,
1263  * that core like that".  Example, ARM11 MPCore ...
1264  */
1265
1266 #define ARM11_BOOL_WRAPPER(name, print_name)    \
1267                 COMMAND_HANDLER(arm11_handle_bool_##name) \
1268                 { \
1269                         return CALL_COMMAND_HANDLER(handle_command_parse_bool, \
1270                                         &arm11_config_##name, print_name); \
1271                 }
1272
1273 ARM11_BOOL_WRAPPER(memwrite_burst, "memory write burst mode")
1274 ARM11_BOOL_WRAPPER(memwrite_error_fatal, "fatal error mode for memory writes")
1275 ARM11_BOOL_WRAPPER(step_irq_enable, "IRQs while stepping")
1276 ARM11_BOOL_WRAPPER(hardware_step, "hardware single step")
1277
1278 COMMAND_HANDLER(arm11_handle_vcr)
1279 {
1280         switch (CMD_ARGC) {
1281         case 0:
1282                 break;
1283         case 1:
1284                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], arm11_vcr);
1285                 break;
1286         default:
1287                 return ERROR_COMMAND_SYNTAX_ERROR;
1288         }
1289
1290         LOG_INFO("VCR 0x%08" PRIx32 "", arm11_vcr);
1291         return ERROR_OK;
1292 }
1293
1294 static const struct command_registration arm11_mw_command_handlers[] = {
1295         {
1296                 .name = "burst",
1297                 .handler = &arm11_handle_bool_memwrite_burst,
1298                 .mode = COMMAND_ANY,
1299                 .help = "Enable/Disable non-standard but fast burst mode"
1300                         " (default: enabled)",
1301         },
1302         {
1303                 .name = "error_fatal",
1304                 .handler = &arm11_handle_bool_memwrite_error_fatal,
1305                 .mode = COMMAND_ANY,
1306                 .help = "Terminate program if transfer error was found"
1307                         " (default: enabled)",
1308         },
1309         COMMAND_REGISTRATION_DONE
1310 };
1311 static const struct command_registration arm11_any_command_handlers[] = {
1312         {
1313                 /* "hardware_step" is only here to check if the default
1314                  * simulate + breakpoint implementation is broken.
1315                  * TEMPORARY! NOT DOCUMENTED! */
1316                 .name = "hardware_step",
1317                 .handler = &arm11_handle_bool_hardware_step,
1318                 .mode = COMMAND_ANY,
1319                 .help = "DEBUG ONLY - Hardware single stepping"
1320                         " (default: disabled)",
1321                 .usage = "(enable|disable)",
1322         },
1323         {
1324                 .name = "memwrite",
1325                 .mode = COMMAND_ANY,
1326                 .help = "memwrite command group",
1327                 .chain = arm11_mw_command_handlers,
1328         },
1329         {
1330                 .name = "step_irq_enable",
1331                 .handler = &arm11_handle_bool_step_irq_enable,
1332                 .mode = COMMAND_ANY,
1333                 .help = "Enable interrupts while stepping"
1334                         " (default: disabled)",
1335         },
1336         {
1337                 .name = "vcr",
1338                 .handler = &arm11_handle_vcr,
1339                 .mode = COMMAND_ANY,
1340                 .help = "Control (Interrupt) Vector Catch Register",
1341         },
1342         COMMAND_REGISTRATION_DONE
1343 };
1344 static const struct command_registration arm11_command_handlers[] = {
1345         {
1346                 .chain = arm_command_handlers,
1347         },
1348         {
1349                 .chain = etm_command_handlers,
1350         },
1351         {
1352                 .name = "arm11",
1353                 .mode = COMMAND_ANY,
1354                 .help = "ARM11 command group",
1355                 .chain = arm11_any_command_handlers,
1356         },
1357         COMMAND_REGISTRATION_DONE
1358 };
1359
1360 /** Holds methods for ARM11xx targets. */
1361 struct target_type arm11_target = {
1362         .name =                 "arm11",
1363
1364         .poll =                 arm11_poll,
1365         .arch_state =           arm11_arch_state,
1366
1367         .target_request_data =  arm11_target_request_data,
1368
1369         .halt =                 arm11_halt,
1370         .resume =               arm11_resume,
1371         .step =                 arm11_step,
1372
1373         .assert_reset =         arm11_assert_reset,
1374         .deassert_reset =       arm11_deassert_reset,
1375         .soft_reset_halt =      arm11_soft_reset_halt,
1376
1377         .get_gdb_reg_list =     armv4_5_get_gdb_reg_list,
1378
1379         .read_memory =          arm11_read_memory,
1380         .write_memory =         arm11_write_memory,
1381
1382         .bulk_write_memory =    arm11_bulk_write_memory,
1383
1384         .checksum_memory =      arm_checksum_memory,
1385         .blank_check_memory =   arm_blank_check_memory,
1386
1387         .add_breakpoint =       arm11_add_breakpoint,
1388         .remove_breakpoint =    arm11_remove_breakpoint,
1389
1390         .run_algorithm =        armv4_5_run_algorithm,
1391
1392         .commands =             arm11_command_handlers,
1393         .target_create =        arm11_target_create,
1394         .init_target =          arm11_init_target,
1395         .examine =              arm11_examine,
1396 };