74cf1b0d3d213ca7244837ed14bcb7add8edff88
[fw/openocd] / src / target / etm.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 /***************************************************************************
4  *   Copyright (C) 2005 by Dominic Rath                                    *
5  *   Dominic.Rath@gmx.de                                                   *
6  ***************************************************************************/
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #include "arm.h"
12 #include "etm.h"
13 #include "etb.h"
14 #include "image.h"
15 #include "arm_disassembler.h"
16 #include "register.h"
17 #include "etm_dummy.h"
18
19 /*
20  * ARM "Embedded Trace Macrocell" (ETM) support -- direct JTAG access.
21  *
22  * ETM modules collect instruction and/or data trace information, compress
23  * it, and transfer it to a debugging host through either a (buffered) trace
24  * port (often a 38-pin Mictor connector) or an Embedded Trace Buffer (ETB).
25  *
26  * There are several generations of these modules.  Original versions have
27  * JTAG access through a dedicated scan chain.  Recent versions have added
28  * access via coprocessor instructions, memory addressing, and the ARM Debug
29  * Interface v5 (ADIv5); and phased out direct JTAG access.
30  *
31  * This code supports up to the ETMv1.3 architecture, as seen in ETM9 and
32  * most common ARM9 systems.  Note: "CoreSight ETM9" implements ETMv3.2,
33  * implying non-JTAG connectivity options.
34  *
35  * Relevant documentation includes:
36  *  ARM DDI 0157G ... ETM9 (r2p2) Technical Reference Manual
37  *  ARM DDI 0315B ... CoreSight ETM9 (r0p1) Technical Reference Manual
38  *  ARM IHI 0014O ... Embedded Trace Macrocell, Architecture Specification
39  */
40
41 enum {
42         RO,                             /* read/only */
43         WO,                             /* write/only */
44         RW,                             /* read/write */
45 };
46
47 struct etm_reg_info {
48         uint8_t addr;
49         uint8_t size;                   /* low-N of 32 bits */
50         uint8_t mode;                   /* RO, WO, RW */
51         uint8_t bcd_vers;               /* 1.0, 2.0, etc */
52         const char *name;
53 };
54
55 /*
56  * Registers 0..0x7f are JTAG-addressable using scanchain 6.
57  * (Or on some processors, through coprocessor operations.)
58  * Newer versions of ETM make some W/O registers R/W, and
59  * provide definitions for some previously-unused bits.
60  */
61
62 /* core registers used to version/configure the ETM */
63 static const struct etm_reg_info etm_core[] = {
64         /* NOTE: we "know" the order here ... */
65         { ETM_CONFIG, 32, RO, 0x10, "ETM_config", },
66         { ETM_ID, 32, RO, 0x20, "ETM_id", },
67 };
68
69 /* basic registers that are always there given the right ETM version */
70 static const struct etm_reg_info etm_basic[] = {
71         /* ETM Trace Registers */
72         { ETM_CTRL, 32, RW, 0x10, "ETM_ctrl", },
73         { ETM_TRIG_EVENT, 17, WO, 0x10, "ETM_trig_event", },
74         { ETM_ASIC_CTRL,  8, WO, 0x10, "ETM_asic_ctrl", },
75         { ETM_STATUS,  3, RO, 0x11, "ETM_status", },
76         { ETM_SYS_CONFIG,  9, RO, 0x12, "ETM_sys_config", },
77
78         /* TraceEnable configuration */
79         { ETM_TRACE_RESOURCE_CTRL, 32, WO, 0x12, "ETM_trace_resource_ctrl", },
80         { ETM_TRACE_EN_CTRL2, 16, WO, 0x12, "ETM_trace_en_ctrl2", },
81         { ETM_TRACE_EN_EVENT, 17, WO, 0x10, "ETM_trace_en_event", },
82         { ETM_TRACE_EN_CTRL1, 26, WO, 0x10, "ETM_trace_en_ctrl1", },
83
84         /* ViewData configuration (data trace) */
85         { ETM_VIEWDATA_EVENT, 17, WO, 0x10, "ETM_viewdata_event", },
86         { ETM_VIEWDATA_CTRL1, 32, WO, 0x10, "ETM_viewdata_ctrl1", },
87         { ETM_VIEWDATA_CTRL2, 32, WO, 0x10, "ETM_viewdata_ctrl2", },
88         { ETM_VIEWDATA_CTRL3, 17, WO, 0x10, "ETM_viewdata_ctrl3", },
89
90         /* REVISIT exclude VIEWDATA_CTRL2 when it's not there */
91
92         { 0x78, 12, WO, 0x20, "ETM_sync_freq", },
93         { 0x7a, 22, RO, 0x31, "ETM_config_code_ext", },
94         { 0x7b, 32, WO, 0x31, "ETM_ext_input_select", },
95         { 0x7c, 32, WO, 0x34, "ETM_trace_start_stop", },
96         { 0x7d, 8, WO, 0x34, "ETM_behavior_control", },
97 };
98
99 static const struct etm_reg_info etm_fifofull[] = {
100         /* FIFOFULL configuration */
101         { ETM_FIFOFULL_REGION, 25, WO, 0x10, "ETM_fifofull_region", },
102         { ETM_FIFOFULL_LEVEL,  8, WO, 0x10, "ETM_fifofull_level", },
103 };
104
105 static const struct etm_reg_info etm_addr_comp[] = {
106         /* Address comparator register pairs */
107 #define ADDR_COMPARATOR(i) \
108                 { ETM_ADDR_COMPARATOR_VALUE + (i) - 1, 32, WO, 0x10, \
109                                 "ETM_addr_" #i "_comparator_value", }, \
110                 { ETM_ADDR_ACCESS_TYPE + (i) - 1,  7, WO, 0x10, \
111                                 "ETM_addr_" #i "_access_type", }
112         ADDR_COMPARATOR(1),
113         ADDR_COMPARATOR(2),
114         ADDR_COMPARATOR(3),
115         ADDR_COMPARATOR(4),
116         ADDR_COMPARATOR(5),
117         ADDR_COMPARATOR(6),
118         ADDR_COMPARATOR(7),
119         ADDR_COMPARATOR(8),
120
121         ADDR_COMPARATOR(9),
122         ADDR_COMPARATOR(10),
123         ADDR_COMPARATOR(11),
124         ADDR_COMPARATOR(12),
125         ADDR_COMPARATOR(13),
126         ADDR_COMPARATOR(14),
127         ADDR_COMPARATOR(15),
128         ADDR_COMPARATOR(16),
129         { 0, 0, 0, 0, NULL }
130 #undef ADDR_COMPARATOR
131 };
132
133 static const struct etm_reg_info etm_data_comp[] = {
134         /* Data Value Comparators (NOTE: odd addresses are reserved) */
135 #define DATA_COMPARATOR(i) \
136                 { ETM_DATA_COMPARATOR_VALUE + 2*(i) - 1, 32, WO, 0x10, \
137                                 "ETM_data_" #i "_comparator_value", }, \
138                 { ETM_DATA_COMPARATOR_MASK + 2*(i) - 1, 32, WO, 0x10, \
139                                 "ETM_data_" #i "_comparator_mask", }
140         DATA_COMPARATOR(1),
141         DATA_COMPARATOR(2),
142         DATA_COMPARATOR(3),
143         DATA_COMPARATOR(4),
144         DATA_COMPARATOR(5),
145         DATA_COMPARATOR(6),
146         DATA_COMPARATOR(7),
147         DATA_COMPARATOR(8),
148         { 0, 0, 0, 0, NULL }
149 #undef DATA_COMPARATOR
150 };
151
152 static const struct etm_reg_info etm_counters[] = {
153 #define ETM_COUNTER(i) \
154                 { ETM_COUNTER_RELOAD_VALUE + (i) - 1, 16, WO, 0x10, \
155                                 "ETM_counter_" #i "_reload_value", }, \
156                 { ETM_COUNTER_ENABLE + (i) - 1, 18, WO, 0x10, \
157                                 "ETM_counter_" #i "_enable", }, \
158                 { ETM_COUNTER_RELOAD_EVENT + (i) - 1, 17, WO, 0x10, \
159                                 "ETM_counter_" #i "_reload_event", }, \
160                 { ETM_COUNTER_VALUE + (i) - 1, 16, RO, 0x10, \
161                                 "ETM_counter_" #i "_value", }
162         ETM_COUNTER(1),
163         ETM_COUNTER(2),
164         ETM_COUNTER(3),
165         ETM_COUNTER(4),
166         { 0, 0, 0, 0, NULL }
167 #undef ETM_COUNTER
168 };
169
170 static const struct etm_reg_info etm_sequencer[] = {
171 #define ETM_SEQ(i) \
172                 { ETM_SEQUENCER_EVENT + (i), 17, WO, 0x10, \
173                                 "ETM_sequencer_event" #i, }
174         ETM_SEQ(0),                             /* 1->2 */
175         ETM_SEQ(1),                             /* 2->1 */
176         ETM_SEQ(2),                             /* 2->3 */
177         ETM_SEQ(3),                             /* 3->1 */
178         ETM_SEQ(4),                             /* 3->2 */
179         ETM_SEQ(5),                             /* 1->3 */
180 #undef ETM_SEQ
181         /* 0x66 reserved */
182         { ETM_SEQUENCER_STATE,  2, RO, 0x10, "ETM_sequencer_state", },
183 };
184
185 static const struct etm_reg_info etm_outputs[] = {
186 #define ETM_OUTPUT(i) \
187                 { ETM_EXTERNAL_OUTPUT + (i) - 1, 17, WO, 0x10, \
188                                 "ETM_external_output" #i, }
189
190         ETM_OUTPUT(1),
191         ETM_OUTPUT(2),
192         ETM_OUTPUT(3),
193         ETM_OUTPUT(4),
194         { 0, 0, 0, 0, NULL }
195 #undef ETM_OUTPUT
196 };
197
198 #if 0
199         /* registers from 0x6c..0x7f were added after ETMv1.3 */
200
201         /* Context ID Comparators */
202         { 0x6c, 32, RO, 0x20, "ETM_contextid_comparator_value1", }
203         { 0x6d, 32, RO, 0x20, "ETM_contextid_comparator_value2", }
204         { 0x6e, 32, RO, 0x20, "ETM_contextid_comparator_value3", }
205         { 0x6f, 32, RO, 0x20, "ETM_contextid_comparator_mask", }
206 #endif
207
208 static int etm_get_reg(struct reg *reg);
209 static int etm_read_reg_w_check(struct reg *reg,
210         uint8_t *check_value, uint8_t *check_mask);
211 static int etm_register_user_commands(struct command_context *cmd_ctx);
212 static int etm_set_reg_w_exec(struct reg *reg, uint8_t *buf);
213 static int etm_write_reg(struct reg *reg, uint32_t value);
214
215 static const struct reg_arch_type etm_scan6_type = {
216         .get = etm_get_reg,
217         .set = etm_set_reg_w_exec,
218 };
219
220 /* Look up register by ID ... most ETM instances only
221  * support a subset of the possible registers.
222  */
223 static struct reg *etm_reg_lookup(struct etm_context *etm_ctx, unsigned id)
224 {
225         struct reg_cache *cache = etm_ctx->reg_cache;
226         unsigned i;
227
228         for (i = 0; i < cache->num_regs; i++) {
229                 struct etm_reg *reg = cache->reg_list[i].arch_info;
230
231                 if (reg->reg_info->addr == id)
232                         return &cache->reg_list[i];
233         }
234
235         /* caller asking for nonexistent register is a bug!
236          * REVISIT say which of the N targets was involved */
237         LOG_ERROR("ETM: register 0x%02x not available", id);
238         return NULL;
239 }
240
241 static void etm_reg_add(unsigned bcd_vers, struct arm_jtag *jtag_info,
242         struct reg_cache *cache, struct etm_reg *ereg,
243         const struct etm_reg_info *r, unsigned nreg)
244 {
245         struct reg *reg = cache->reg_list;
246
247         reg += cache->num_regs;
248         ereg += cache->num_regs;
249
250         /* add up to "nreg" registers from "r", if supported by this
251          * version of the ETM, to the specified cache.
252          */
253         for (; nreg--; r++) {
254                 /* No more registers to add */
255                 if (!r->size) {
256                         LOG_ERROR("etm_reg_add is requested to add non-existing registers, ETM config might be bogus");
257                         return;
258                 }
259
260                 /* this ETM may be too old to have some registers */
261                 if (r->bcd_vers > bcd_vers)
262                         continue;
263
264                 reg->name = r->name;
265                 reg->size = r->size;
266                 reg->value = ereg->value;
267                 reg->arch_info = ereg;
268                 reg->type = &etm_scan6_type;
269                 reg++;
270                 cache->num_regs++;
271
272                 ereg->reg_info = r;
273                 ereg->jtag_info = jtag_info;
274                 ereg++;
275         }
276 }
277
278 struct reg_cache *etm_build_reg_cache(struct target *target,
279         struct arm_jtag *jtag_info, struct etm_context *etm_ctx)
280 {
281         struct reg_cache *reg_cache = malloc(sizeof(struct reg_cache));
282         struct reg *reg_list = NULL;
283         struct etm_reg *arch_info = NULL;
284         unsigned bcd_vers, config;
285
286         /* the actual registers are kept in two arrays */
287         reg_list = calloc(128, sizeof(struct reg));
288         arch_info = calloc(128, sizeof(struct etm_reg));
289
290         if (!reg_cache || !reg_list || !arch_info) {
291                 LOG_ERROR("No memory");
292                 goto fail;
293         }
294
295         /* fill in values for the reg cache */
296         reg_cache->name = "etm registers";
297         reg_cache->next = NULL;
298         reg_cache->reg_list = reg_list;
299         reg_cache->num_regs = 0;
300
301         /* add ETM_CONFIG, then parse its values to see
302          * which other registers exist in this ETM
303          */
304         etm_reg_add(0x10, jtag_info, reg_cache, arch_info,
305                 etm_core, 1);
306
307         etm_get_reg(reg_list);
308         etm_ctx->config = buf_get_u32(arch_info->value, 0, 32);
309         config = etm_ctx->config;
310
311         /* figure ETM version then add base registers */
312         if (config & (1 << 31)) {
313                 LOG_WARNING("ETMv2+ support is incomplete");
314
315                 /* REVISIT more registers may exist; they may now be
316                  * readable; more register bits have defined meanings;
317                  * don't presume trace start/stop support is present;
318                  * and include any context ID comparator registers.
319                  */
320                 etm_reg_add(0x20, jtag_info, reg_cache, arch_info,
321                         etm_core + 1, 1);
322                 etm_get_reg(reg_list + 1);
323                 etm_ctx->id = buf_get_u32(
324                                 arch_info[1].value, 0, 32);
325                 LOG_DEBUG("ETM ID: %08x", (unsigned) etm_ctx->id);
326                 bcd_vers = 0x10 + (((etm_ctx->id) >> 4) & 0xff);
327
328         } else {
329                 switch (config >> 28) {
330                         case 7:
331                         case 5:
332                         case 3:
333                                 bcd_vers = 0x13;
334                                 break;
335                         case 4:
336                         case 2:
337                                 bcd_vers = 0x12;
338                                 break;
339                         case 1:
340                                 bcd_vers = 0x11;
341                                 break;
342                         case 0:
343                                 bcd_vers = 0x10;
344                                 break;
345                         default:
346                                 LOG_WARNING("Bad ETMv1 protocol %d", config >> 28);
347                                 goto fail;
348                 }
349         }
350         etm_ctx->bcd_vers = bcd_vers;
351         LOG_INFO("ETM v%d.%d", bcd_vers >> 4, bcd_vers & 0xf);
352
353         etm_reg_add(bcd_vers, jtag_info, reg_cache, arch_info,
354                 etm_basic, ARRAY_SIZE(etm_basic));
355
356         /* address and data comparators; counters; outputs */
357         etm_reg_add(bcd_vers, jtag_info, reg_cache, arch_info,
358                 etm_addr_comp, 4 * (0x0f & (config >> 0)));
359         etm_reg_add(bcd_vers, jtag_info, reg_cache, arch_info,
360                 etm_data_comp, 2 * (0x0f & (config >> 4)));
361         etm_reg_add(bcd_vers, jtag_info, reg_cache, arch_info,
362                 etm_counters, 4 * (0x07 & (config >> 13)));
363         etm_reg_add(bcd_vers, jtag_info, reg_cache, arch_info,
364                 etm_outputs, (0x07 & (config >> 20)));
365
366         /* FIFOFULL presence is optional
367          * REVISIT for ETMv1.2 and later, don't bother adding this
368          * unless ETM_SYS_CONFIG says it's also *supported* ...
369          */
370         if (config & (1 << 23))
371                 etm_reg_add(bcd_vers, jtag_info, reg_cache, arch_info,
372                         etm_fifofull, ARRAY_SIZE(etm_fifofull));
373
374         /* sequencer is optional (for state-dependant triggering) */
375         if (config & (1 << 16))
376                 etm_reg_add(bcd_vers, jtag_info, reg_cache, arch_info,
377                         etm_sequencer, ARRAY_SIZE(etm_sequencer));
378
379         /* REVISIT could realloc and likely save half the memory
380          * in the two chunks we allocated...
381          */
382
383         /* the ETM might have an ETB connected */
384         if (strcmp(etm_ctx->capture_driver->name, "etb") == 0) {
385                 struct etb *etb = etm_ctx->capture_driver_priv;
386
387                 if (!etb) {
388                         LOG_ERROR("etb selected as etm capture driver, but no ETB configured");
389                         goto fail;
390                 }
391
392                 reg_cache->next = etb_build_reg_cache(etb);
393
394                 etb->reg_cache = reg_cache->next;
395         }
396
397         etm_ctx->reg_cache = reg_cache;
398         return reg_cache;
399
400 fail:
401         free(reg_cache);
402         free(reg_list);
403         free(arch_info);
404         return NULL;
405 }
406
407 static int etm_read_reg(struct reg *reg)
408 {
409         return etm_read_reg_w_check(reg, NULL, NULL);
410 }
411
412 static int etm_store_reg(struct reg *reg)
413 {
414         return etm_write_reg(reg, buf_get_u32(reg->value, 0, reg->size));
415 }
416
417 int etm_setup(struct target *target)
418 {
419         int retval;
420         uint32_t etm_ctrl_value;
421         struct arm *arm = target_to_arm(target);
422         struct etm_context *etm_ctx = arm->etm;
423         struct reg *etm_ctrl_reg;
424
425         etm_ctrl_reg = etm_reg_lookup(etm_ctx, ETM_CTRL);
426         if (!etm_ctrl_reg)
427                 return ERROR_OK;
428
429         /* initialize some ETM control register settings */
430         etm_get_reg(etm_ctrl_reg);
431         etm_ctrl_value = buf_get_u32(etm_ctrl_reg->value, 0, 32);
432
433         /* clear the ETM powerdown bit (0) */
434         etm_ctrl_value &= ~ETM_CTRL_POWERDOWN;
435
436         /* configure port width (21,6:4), mode (13,17:16) and
437          * for older modules clocking (13)
438          */
439         etm_ctrl_value = (etm_ctrl_value
440                 & ~ETM_PORT_WIDTH_MASK
441                 & ~ETM_PORT_MODE_MASK
442                 & ~ETM_CTRL_DBGRQ
443                 & ~ETM_PORT_CLOCK_MASK)
444                 | etm_ctx->control;
445
446         buf_set_u32(etm_ctrl_reg->value, 0, 32, etm_ctrl_value);
447         etm_store_reg(etm_ctrl_reg);
448
449         etm_ctx->control = etm_ctrl_value;
450
451         retval = jtag_execute_queue();
452         if (retval != ERROR_OK)
453                 return retval;
454
455         /* REVISIT for ETMv3.0 and later, read ETM_sys_config to
456          * verify that those width and mode settings are OK ...
457          */
458
459         retval = etm_ctx->capture_driver->init(etm_ctx);
460         if (retval != ERROR_OK) {
461                 LOG_ERROR("ETM capture driver initialization failed");
462                 return retval;
463         }
464         return ERROR_OK;
465 }
466
467 static int etm_get_reg(struct reg *reg)
468 {
469         int retval;
470
471         retval = etm_read_reg(reg);
472         if (retval != ERROR_OK) {
473                 LOG_ERROR("BUG: error scheduling etm register read");
474                 return retval;
475         }
476
477         retval = jtag_execute_queue();
478         if (retval != ERROR_OK) {
479                 LOG_ERROR("register read failed");
480                 return retval;
481         }
482
483         return ERROR_OK;
484 }
485
486 static int etm_read_reg_w_check(struct reg *reg,
487         uint8_t *check_value, uint8_t *check_mask)
488 {
489         struct etm_reg *etm_reg = reg->arch_info;
490         assert(etm_reg);
491         const struct etm_reg_info *r = etm_reg->reg_info;
492         uint8_t reg_addr = r->addr & 0x7f;
493         struct scan_field fields[3];
494         int retval;
495
496         if (etm_reg->reg_info->mode == WO) {
497                 LOG_ERROR("BUG: can't read write-only register %s", r->name);
498                 return ERROR_COMMAND_SYNTAX_ERROR;
499         }
500
501         LOG_DEBUG("%s (%u)", r->name, reg_addr);
502
503         retval = arm_jtag_scann(etm_reg->jtag_info, 0x6, TAP_IDLE);
504         if (retval != ERROR_OK)
505                 return retval;
506         retval = arm_jtag_set_instr(etm_reg->jtag_info->tap,
507                         etm_reg->jtag_info->intest_instr,
508                         NULL,
509                         TAP_IDLE);
510         if (retval != ERROR_OK)
511                 return retval;
512
513         fields[0].num_bits = 32;
514         fields[0].out_value = reg->value;
515         fields[0].in_value = NULL;
516         fields[0].check_value = NULL;
517         fields[0].check_mask = NULL;
518
519         fields[1].num_bits = 7;
520         uint8_t temp1 = 0;
521         fields[1].out_value = &temp1;
522         buf_set_u32(&temp1, 0, 7, reg_addr);
523         fields[1].in_value = NULL;
524         fields[1].check_value = NULL;
525         fields[1].check_mask = NULL;
526
527         fields[2].num_bits = 1;
528         uint8_t temp2 = 0;
529         fields[2].out_value = &temp2;
530         buf_set_u32(&temp2, 0, 1, 0);
531         fields[2].in_value = NULL;
532         fields[2].check_value = NULL;
533         fields[2].check_mask = NULL;
534
535         jtag_add_dr_scan(etm_reg->jtag_info->tap, 3, fields, TAP_IDLE);
536
537         fields[0].in_value = reg->value;
538         fields[0].check_value = check_value;
539         fields[0].check_mask = check_mask;
540
541         jtag_add_dr_scan_check(etm_reg->jtag_info->tap, 3, fields, TAP_IDLE);
542
543         return ERROR_OK;
544 }
545
546 static int etm_set_reg(struct reg *reg, uint32_t value)
547 {
548         int retval = etm_write_reg(reg, value);
549         if (retval != ERROR_OK) {
550                 LOG_ERROR("BUG: error scheduling etm register write");
551                 return retval;
552         }
553
554         buf_set_u32(reg->value, 0, reg->size, value);
555         reg->valid = 1;
556         reg->dirty = 0;
557
558         return ERROR_OK;
559 }
560
561 static int etm_set_reg_w_exec(struct reg *reg, uint8_t *buf)
562 {
563         int retval;
564
565         etm_set_reg(reg, buf_get_u32(buf, 0, reg->size));
566
567         retval = jtag_execute_queue();
568         if (retval != ERROR_OK) {
569                 LOG_ERROR("register write failed");
570                 return retval;
571         }
572         return ERROR_OK;
573 }
574
575 static int etm_write_reg(struct reg *reg, uint32_t value)
576 {
577         struct etm_reg *etm_reg = reg->arch_info;
578         const struct etm_reg_info *r = etm_reg->reg_info;
579         uint8_t reg_addr = r->addr & 0x7f;
580         struct scan_field fields[3];
581         int retval;
582
583         if (etm_reg->reg_info->mode == RO) {
584                 LOG_ERROR("BUG: can't write read--only register %s", r->name);
585                 return ERROR_COMMAND_SYNTAX_ERROR;
586         }
587
588         LOG_DEBUG("%s (%u): 0x%8.8" PRIx32 "", r->name, reg_addr, value);
589
590         retval = arm_jtag_scann(etm_reg->jtag_info, 0x6, TAP_IDLE);
591         if (retval != ERROR_OK)
592                 return retval;
593         retval = arm_jtag_set_instr(etm_reg->jtag_info->tap,
594                         etm_reg->jtag_info->intest_instr,
595                         NULL,
596                         TAP_IDLE);
597         if (retval != ERROR_OK)
598                 return retval;
599
600         fields[0].num_bits = 32;
601         uint8_t tmp1[4];
602         fields[0].out_value = tmp1;
603         buf_set_u32(tmp1, 0, 32, value);
604         fields[0].in_value = NULL;
605
606         fields[1].num_bits = 7;
607         uint8_t tmp2 = 0;
608         fields[1].out_value = &tmp2;
609         buf_set_u32(&tmp2, 0, 7, reg_addr);
610         fields[1].in_value = NULL;
611
612         fields[2].num_bits = 1;
613         uint8_t tmp3 = 0;
614         fields[2].out_value = &tmp3;
615         buf_set_u32(&tmp3, 0, 1, 1);
616         fields[2].in_value = NULL;
617
618         jtag_add_dr_scan(etm_reg->jtag_info->tap, 3, fields, TAP_IDLE);
619
620         return ERROR_OK;
621 }
622
623
624 /* ETM trace analysis functionality */
625
626 static struct etm_capture_driver *etm_capture_drivers[] = {
627         &etb_capture_driver,
628         &etm_dummy_capture_driver,
629         NULL
630 };
631
632 static int etm_read_instruction(struct etm_context *ctx, struct arm_instruction *instruction)
633 {
634         int section = -1;
635         size_t size_read;
636         uint32_t opcode;
637         int retval;
638
639         if (!ctx->image)
640                 return ERROR_TRACE_IMAGE_UNAVAILABLE;
641
642         /* search for the section the current instruction belongs to */
643         for (unsigned int i = 0; i < ctx->image->num_sections; i++) {
644                 if ((ctx->image->sections[i].base_address <= ctx->current_pc) &&
645                         (ctx->image->sections[i].base_address + ctx->image->sections[i].size >
646                         ctx->current_pc)) {
647                         section = i;
648                         break;
649                 }
650         }
651
652         if (section == -1) {
653                 /* current instruction couldn't be found in the image */
654                 return ERROR_TRACE_INSTRUCTION_UNAVAILABLE;
655         }
656
657         if (ctx->core_state == ARM_STATE_ARM) {
658                 uint8_t buf[4];
659                 retval = image_read_section(ctx->image, section,
660                                 ctx->current_pc -
661                                 ctx->image->sections[section].base_address,
662                                 4, buf, &size_read);
663                 if (retval != ERROR_OK) {
664                         LOG_ERROR("error while reading instruction");
665                         return ERROR_TRACE_INSTRUCTION_UNAVAILABLE;
666                 }
667                 opcode = target_buffer_get_u32(ctx->target, buf);
668                 arm_evaluate_opcode(opcode, ctx->current_pc, instruction);
669         } else if (ctx->core_state == ARM_STATE_THUMB) {
670                 uint8_t buf[2];
671                 retval = image_read_section(ctx->image, section,
672                                 ctx->current_pc -
673                                 ctx->image->sections[section].base_address,
674                                 2, buf, &size_read);
675                 if (retval != ERROR_OK) {
676                         LOG_ERROR("error while reading instruction");
677                         return ERROR_TRACE_INSTRUCTION_UNAVAILABLE;
678                 }
679                 opcode = target_buffer_get_u16(ctx->target, buf);
680                 thumb_evaluate_opcode(opcode, ctx->current_pc, instruction);
681         } else if (ctx->core_state == ARM_STATE_JAZELLE) {
682                 LOG_ERROR("BUG: tracing of jazelle code not supported");
683                 return ERROR_FAIL;
684         } else {
685                 LOG_ERROR("BUG: unknown core state encountered");
686                 return ERROR_FAIL;
687         }
688
689         return ERROR_OK;
690 }
691
692 static int etmv1_next_packet(struct etm_context *ctx, uint8_t *packet, int apo)
693 {
694         while (ctx->data_index < ctx->trace_depth) {
695                 /* if the caller specified an address packet offset, skip until the
696                  * we reach the n-th cycle marked with tracesync */
697                 if (apo > 0) {
698                         if (ctx->trace_data[ctx->data_index].flags & ETMV1_TRACESYNC_CYCLE)
699                                 apo--;
700
701                         if (apo > 0) {
702                                 ctx->data_index++;
703                                 ctx->data_half = 0;
704                         }
705                         continue;
706                 }
707
708                 /* no tracedata output during a TD cycle
709                  * or in a trigger cycle */
710                 if ((ctx->trace_data[ctx->data_index].pipestat == STAT_TD)
711                         || (ctx->trace_data[ctx->data_index].flags & ETMV1_TRIGGER_CYCLE)) {
712                         ctx->data_index++;
713                         ctx->data_half = 0;
714                         continue;
715                 }
716
717                 /* FIXME there are more port widths than these... */
718                 if ((ctx->control & ETM_PORT_WIDTH_MASK) == ETM_PORT_16BIT) {
719                         if (ctx->data_half == 0) {
720                                 *packet = ctx->trace_data[ctx->data_index].packet & 0xff;
721                                 ctx->data_half = 1;
722                         } else {
723                                 *packet = (ctx->trace_data[ctx->data_index].packet & 0xff00) >> 8;
724                                 ctx->data_half = 0;
725                                 ctx->data_index++;
726                         }
727                 } else if ((ctx->control & ETM_PORT_WIDTH_MASK) == ETM_PORT_8BIT) {
728                         *packet = ctx->trace_data[ctx->data_index].packet & 0xff;
729                         ctx->data_index++;
730                 } else {
731                         /* on a 4-bit port, a packet will be output during two consecutive cycles */
732                         if (ctx->data_index > (ctx->trace_depth - 2))
733                                 return -1;
734
735                         *packet = ctx->trace_data[ctx->data_index].packet & 0xf;
736                         *packet |= (ctx->trace_data[ctx->data_index + 1].packet & 0xf) << 4;
737                         ctx->data_index += 2;
738                 }
739
740                 return 0;
741         }
742
743         return -1;
744 }
745
746 static int etmv1_branch_address(struct etm_context *ctx)
747 {
748         int retval;
749         uint8_t packet;
750         int shift = 0;
751         int apo;
752         uint32_t i;
753
754         /* quit analysis if less than two cycles are left in the trace
755          * because we can't extract the APO */
756         if (ctx->data_index > (ctx->trace_depth - 2))
757                 return -1;
758
759         /* a BE could be output during an APO cycle, skip the current
760          * and continue with the new one */
761         if (ctx->trace_data[ctx->pipe_index + 1].pipestat & 0x4)
762                 return 1;
763         if (ctx->trace_data[ctx->pipe_index + 2].pipestat & 0x4)
764                 return 2;
765
766         /* address packet offset encoded in the next two cycles' pipestat bits */
767         apo = ctx->trace_data[ctx->pipe_index + 1].pipestat & 0x3;
768         apo |= (ctx->trace_data[ctx->pipe_index + 2].pipestat & 0x3) << 2;
769
770         /* count number of tracesync cycles between current pipe_index and data_index
771          * i.e. the number of tracesyncs that data_index already passed by
772          * to subtract them from the APO */
773         for (i = ctx->pipe_index; i < ctx->data_index; i++) {
774                 if (ctx->trace_data[ctx->pipe_index + 1].pipestat & ETMV1_TRACESYNC_CYCLE)
775                         apo--;
776         }
777
778         /* extract up to four 7-bit packets */
779         do {
780                 retval = etmv1_next_packet(ctx, &packet, (shift == 0) ? apo + 1 : 0);
781                 if (retval != 0)
782                         return -1;
783                 ctx->last_branch &= ~(0x7f << shift);
784                 ctx->last_branch |= (packet & 0x7f) << shift;
785                 shift += 7;
786         } while ((packet & 0x80) && (shift < 28));
787
788         /* one last packet holding 4 bits of the address, plus the branch reason code */
789         if ((shift == 28) && (packet & 0x80)) {
790                 retval = etmv1_next_packet(ctx, &packet, 0);
791                 if (retval != 0)
792                         return -1;
793                 ctx->last_branch &= 0x0fffffff;
794                 ctx->last_branch |= (packet & 0x0f) << 28;
795                 ctx->last_branch_reason = (packet & 0x70) >> 4;
796                 shift += 4;
797         } else
798                 ctx->last_branch_reason = 0;
799
800         if (shift == 32)
801                 ctx->pc_ok = 1;
802
803         /* if a full address was output, we might have branched into Jazelle state */
804         if ((shift == 32) && (packet & 0x80))
805                 ctx->core_state = ARM_STATE_JAZELLE;
806         else {
807                 /* if we didn't branch into Jazelle state, the current processor state is
808                  * encoded in bit 0 of the branch target address */
809                 if (ctx->last_branch & 0x1) {
810                         ctx->core_state = ARM_STATE_THUMB;
811                         ctx->last_branch &= ~0x1;
812                 } else {
813                         ctx->core_state = ARM_STATE_ARM;
814                         ctx->last_branch &= ~0x3;
815                 }
816         }
817
818         return 0;
819 }
820
821 static int etmv1_data(struct etm_context *ctx, int size, uint32_t *data)
822 {
823         int j;
824         uint8_t buf[4];
825         int retval;
826
827         for (j = 0; j < size; j++) {
828                 retval = etmv1_next_packet(ctx, &buf[j], 0);
829                 if (retval != 0)
830                         return -1;
831         }
832
833         if (size == 8) {
834                 LOG_ERROR("TODO: add support for 64-bit values");
835                 return -1;
836         } else if (size == 4)
837                 *data = target_buffer_get_u32(ctx->target, buf);
838         else if (size == 2)
839                 *data = target_buffer_get_u16(ctx->target, buf);
840         else if (size == 1)
841                 *data = buf[0];
842         else
843                 return -1;
844
845         return 0;
846 }
847
848 static int etmv1_analyze_trace(struct etm_context *ctx, struct command_invocation *cmd)
849 {
850         int retval;
851         struct arm_instruction instruction;
852
853         /* read the trace data if it wasn't read already */
854         if (ctx->trace_depth == 0)
855                 ctx->capture_driver->read_trace(ctx);
856
857         if (ctx->trace_depth == 0) {
858                 command_print(cmd, "Trace is empty.");
859                 return ERROR_OK;
860         }
861
862         /* start at the beginning of the captured trace */
863         ctx->pipe_index = 0;
864         ctx->data_index = 0;
865         ctx->data_half = 0;
866
867         /* neither the PC nor the data pointer are valid */
868         ctx->pc_ok = 0;
869         ctx->ptr_ok = 0;
870
871         while (ctx->pipe_index < ctx->trace_depth) {
872                 uint8_t pipestat = ctx->trace_data[ctx->pipe_index].pipestat;
873                 uint32_t next_pc = ctx->current_pc;
874                 uint32_t old_data_index = ctx->data_index;
875                 uint32_t old_data_half = ctx->data_half;
876                 uint32_t old_index = ctx->pipe_index;
877                 uint32_t last_instruction = ctx->last_instruction;
878                 uint32_t cycles = 0;
879                 int current_pc_ok = ctx->pc_ok;
880
881                 if (ctx->trace_data[ctx->pipe_index].flags & ETMV1_TRIGGER_CYCLE)
882                         command_print(cmd, "--- trigger ---");
883
884                 /* instructions execute in IE/D or BE/D cycles */
885                 if ((pipestat == STAT_IE) || (pipestat == STAT_ID))
886                         ctx->last_instruction = ctx->pipe_index;
887
888                 /* if we don't have a valid pc skip until we reach an indirect branch */
889                 if ((!ctx->pc_ok) && (pipestat != STAT_BE)) {
890                         ctx->pipe_index++;
891                         continue;
892                 }
893
894                 /* any indirect branch could have interrupted instruction flow
895                  * - the branch reason code could indicate a trace discontinuity
896                  * - a branch to the exception vectors indicates an exception
897                  */
898                 if ((pipestat == STAT_BE) || (pipestat == STAT_BD)) {
899                         /* backup current data index, to be able to consume the branch address
900                          * before examining data address and values
901                          */
902                         old_data_index = ctx->data_index;
903                         old_data_half = ctx->data_half;
904
905                         ctx->last_instruction = ctx->pipe_index;
906
907                         retval = etmv1_branch_address(ctx);
908                         if (retval != 0) {
909                                 /* negative return value from etmv1_branch_address means we ran out of packets,
910                                  * quit analysing the trace */
911                                 if (retval < 0)
912                                         break;
913
914                                 /* a positive return values means the current branch was abandoned,
915                                  * and a new branch was encountered in cycle ctx->pipe_index + retval;
916                                  */
917                                 LOG_WARNING(
918                                         "abandoned branch encountered, correctness of analysis uncertain");
919                                 ctx->pipe_index += retval;
920                                 continue;
921                         }
922
923                         /* skip over APO cycles */
924                         ctx->pipe_index += 2;
925
926                         switch (ctx->last_branch_reason) {
927                                 case 0x0:       /* normal PC change */
928                                         next_pc = ctx->last_branch;
929                                         break;
930                                 case 0x1:       /* tracing enabled */
931                                         command_print(cmd,
932                                                 "--- tracing enabled at 0x%8.8" PRIx32 " ---",
933                                                 ctx->last_branch);
934                                         ctx->current_pc = ctx->last_branch;
935                                         ctx->pipe_index++;
936                                         continue;
937                                         break;
938                                 case 0x2:       /* trace restarted after FIFO overflow */
939                                         command_print(cmd,
940                                                 "--- trace restarted after FIFO overflow at 0x%8.8" PRIx32 " ---",
941                                                 ctx->last_branch);
942                                         ctx->current_pc = ctx->last_branch;
943                                         ctx->pipe_index++;
944                                         continue;
945                                         break;
946                                 case 0x3:       /* exit from debug state */
947                                         command_print(cmd,
948                                                 "--- exit from debug state at 0x%8.8" PRIx32 " ---",
949                                                 ctx->last_branch);
950                                         ctx->current_pc = ctx->last_branch;
951                                         ctx->pipe_index++;
952                                         continue;
953                                         break;
954                                 case 0x4:       /* periodic synchronization point */
955                                         next_pc = ctx->last_branch;
956                                         /* if we had no valid PC prior to this synchronization point,
957                                          * we have to move on with the next trace cycle
958                                          */
959                                         if (!current_pc_ok) {
960                                                 command_print(cmd,
961                                                         "--- periodic synchronization point at 0x%8.8" PRIx32 " ---",
962                                                         next_pc);
963                                                 ctx->current_pc = next_pc;
964                                                 ctx->pipe_index++;
965                                                 continue;
966                                         }
967                                         break;
968                                 default:        /* reserved */
969                                         LOG_ERROR(
970                                                 "BUG: branch reason code 0x%" PRIx32 " is reserved",
971                                                 ctx->last_branch_reason);
972                                         return ERROR_FAIL;
973                         }
974
975                         /* if we got here the branch was a normal PC change
976                          * (or a periodic synchronization point, which means the same for that matter)
977                          * if we didn't acquire a complete PC continue with the next cycle
978                          */
979                         if (!ctx->pc_ok)
980                                 continue;
981
982                         /* indirect branch to the exception vector means an exception occurred */
983                         if ((ctx->last_branch <= 0x20)
984                                 || ((ctx->last_branch >= 0xffff0000) &&
985                                 (ctx->last_branch <= 0xffff0020))) {
986                                 if ((ctx->last_branch & 0xff) == 0x10)
987                                         command_print(cmd, "data abort");
988                                 else {
989                                         command_print(cmd,
990                                                 "exception vector 0x%2.2" PRIx32 "",
991                                                 ctx->last_branch);
992                                         ctx->current_pc = ctx->last_branch;
993                                         ctx->pipe_index++;
994                                         continue;
995                                 }
996                         }
997                 }
998
999                 /* an instruction was executed (or not, depending on the condition flags)
1000                  * retrieve it from the image for displaying */
1001                 if (ctx->pc_ok && (pipestat != STAT_WT) && (pipestat != STAT_TD) &&
1002                         !(((pipestat == STAT_BE) || (pipestat == STAT_BD)) &&
1003                         ((ctx->last_branch_reason != 0x0) && (ctx->last_branch_reason != 0x4)))) {
1004                         retval = etm_read_instruction(ctx, &instruction);
1005                         if (retval != ERROR_OK) {
1006                                 /* can't continue tracing with no image available */
1007                                 if (retval == ERROR_TRACE_IMAGE_UNAVAILABLE)
1008                                         return retval;
1009                                 else if (retval == ERROR_TRACE_INSTRUCTION_UNAVAILABLE) {
1010                                         /* TODO: handle incomplete images
1011                                          * for now we just quit the analysis*/
1012                                         return retval;
1013                                 }
1014                         }
1015
1016                         cycles = old_index - last_instruction;
1017                 }
1018
1019                 if ((pipestat == STAT_ID) || (pipestat == STAT_BD)) {
1020                         uint32_t new_data_index = ctx->data_index;
1021                         uint32_t new_data_half = ctx->data_half;
1022
1023                         /* in case of a branch with data, the branch target address was consumed before
1024                          * we temporarily go back to the saved data index */
1025                         if (pipestat == STAT_BD) {
1026                                 ctx->data_index = old_data_index;
1027                                 ctx->data_half = old_data_half;
1028                         }
1029
1030                         if (ctx->control & ETM_CTRL_TRACE_ADDR) {
1031                                 uint8_t packet;
1032                                 int shift = 0;
1033
1034                                 do {
1035                                         retval = etmv1_next_packet(ctx, &packet, 0);
1036                                         if (retval != 0)
1037                                                 return ERROR_ETM_ANALYSIS_FAILED;
1038                                         ctx->last_ptr &= ~(0x7f << shift);
1039                                         ctx->last_ptr |= (packet & 0x7f) << shift;
1040                                         shift += 7;
1041                                 } while ((packet & 0x80) && (shift < 32));
1042
1043                                 if (shift >= 32)
1044                                         ctx->ptr_ok = 1;
1045
1046                                 if (ctx->ptr_ok)
1047                                         command_print(cmd,
1048                                                 "address: 0x%8.8" PRIx32 "",
1049                                                 ctx->last_ptr);
1050                         }
1051
1052                         if (ctx->control & ETM_CTRL_TRACE_DATA) {
1053                                 if ((instruction.type == ARM_LDM) ||
1054                                         (instruction.type == ARM_STM)) {
1055                                         int i;
1056                                         for (i = 0; i < 16; i++) {
1057                                                 if (instruction.info.load_store_multiple.register_list
1058                                                         & (1 << i)) {
1059                                                         uint32_t data;
1060                                                         if (etmv1_data(ctx, 4, &data) != 0)
1061                                                                 return ERROR_ETM_ANALYSIS_FAILED;
1062                                                         command_print(cmd,
1063                                                                 "data: 0x%8.8" PRIx32 "",
1064                                                                 data);
1065                                                 }
1066                                         }
1067                                 } else if ((instruction.type >= ARM_LDR) &&
1068                                         (instruction.type <= ARM_STRH)) {
1069                                         uint32_t data;
1070                                         if (etmv1_data(ctx, arm_access_size(&instruction),
1071                                                 &data) != 0)
1072                                                 return ERROR_ETM_ANALYSIS_FAILED;
1073                                         command_print(cmd, "data: 0x%8.8" PRIx32 "", data);
1074                                 }
1075                         }
1076
1077                         /* restore data index after consuming BD address and data */
1078                         if (pipestat == STAT_BD) {
1079                                 ctx->data_index = new_data_index;
1080                                 ctx->data_half = new_data_half;
1081                         }
1082                 }
1083
1084                 /* adjust PC */
1085                 if ((pipestat == STAT_IE) || (pipestat == STAT_ID)) {
1086                         if (((instruction.type == ARM_B) ||
1087                                 (instruction.type == ARM_BL) ||
1088                                 (instruction.type == ARM_BLX)) &&
1089                                 (instruction.info.b_bl_bx_blx.target_address != 0xffffffff))
1090                                 next_pc = instruction.info.b_bl_bx_blx.target_address;
1091                         else
1092                                 next_pc += (ctx->core_state == ARM_STATE_ARM) ? 4 : 2;
1093                 } else if (pipestat == STAT_IN)
1094                         next_pc += (ctx->core_state == ARM_STATE_ARM) ? 4 : 2;
1095
1096                 if ((pipestat != STAT_TD) && (pipestat != STAT_WT)) {
1097                         char cycles_text[32] = "";
1098
1099                         /* if the trace was captured with cycle accurate tracing enabled,
1100                          * output the number of cycles since the last executed instruction
1101                          */
1102                         if (ctx->control & ETM_CTRL_CYCLE_ACCURATE) {
1103                                 snprintf(cycles_text, 32, " (%i %s)",
1104                                         (int)cycles,
1105                                         (cycles == 1) ? "cycle" : "cycles");
1106                         }
1107
1108                         command_print(cmd, "%s%s%s",
1109                                 instruction.text,
1110                                 (pipestat == STAT_IN) ? " (not executed)" : "",
1111                                 cycles_text);
1112
1113                         ctx->current_pc = next_pc;
1114
1115                         /* packets for an instruction don't start on or before the preceding
1116                          * functional pipestat (i.e. other than WT or TD)
1117                          */
1118                         if (ctx->data_index <= ctx->pipe_index) {
1119                                 ctx->data_index = ctx->pipe_index + 1;
1120                                 ctx->data_half = 0;
1121                         }
1122                 }
1123
1124                 ctx->pipe_index += 1;
1125         }
1126
1127         return ERROR_OK;
1128 }
1129
1130 static COMMAND_HELPER(handle_etm_tracemode_command_update,
1131         uint32_t *mode)
1132 {
1133         uint32_t tracemode;
1134
1135         /* what parts of data access are traced? */
1136         if (strcmp(CMD_ARGV[0], "none") == 0)
1137                 tracemode = 0;
1138         else if (strcmp(CMD_ARGV[0], "data") == 0)
1139                 tracemode = ETM_CTRL_TRACE_DATA;
1140         else if (strcmp(CMD_ARGV[0], "address") == 0)
1141                 tracemode = ETM_CTRL_TRACE_ADDR;
1142         else if (strcmp(CMD_ARGV[0], "all") == 0)
1143                 tracemode = ETM_CTRL_TRACE_DATA | ETM_CTRL_TRACE_ADDR;
1144         else {
1145                 command_print(CMD, "invalid option '%s'", CMD_ARGV[0]);
1146                 return ERROR_COMMAND_SYNTAX_ERROR;
1147         }
1148
1149         uint8_t context_id;
1150         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[1], context_id);
1151         switch (context_id) {
1152                 case 0:
1153                         tracemode |= ETM_CTRL_CONTEXTID_NONE;
1154                         break;
1155                 case 8:
1156                         tracemode |= ETM_CTRL_CONTEXTID_8;
1157                         break;
1158                 case 16:
1159                         tracemode |= ETM_CTRL_CONTEXTID_16;
1160                         break;
1161                 case 32:
1162                         tracemode |= ETM_CTRL_CONTEXTID_32;
1163                         break;
1164                 default:
1165                         command_print(CMD, "invalid option '%s'", CMD_ARGV[1]);
1166                         return ERROR_COMMAND_SYNTAX_ERROR;
1167         }
1168
1169         bool etmv1_cycle_accurate;
1170         COMMAND_PARSE_ENABLE(CMD_ARGV[2], etmv1_cycle_accurate);
1171         if (etmv1_cycle_accurate)
1172                 tracemode |= ETM_CTRL_CYCLE_ACCURATE;
1173
1174         bool etmv1_branch_output;
1175         COMMAND_PARSE_ENABLE(CMD_ARGV[3], etmv1_branch_output);
1176         if (etmv1_branch_output)
1177                 tracemode |= ETM_CTRL_BRANCH_OUTPUT;
1178
1179         /* IGNORED:
1180          *  - CPRT tracing (coprocessor register transfers)
1181          *  - debug request (causes debug entry on trigger)
1182          *  - stall on FIFOFULL (preventing tracedata loss)
1183          */
1184         *mode = tracemode;
1185
1186         return ERROR_OK;
1187 }
1188
1189 COMMAND_HANDLER(handle_etm_tracemode_command)
1190 {
1191         struct target *target = get_current_target(CMD_CTX);
1192         struct arm *arm = target_to_arm(target);
1193         struct etm_context *etm;
1194
1195         if (!is_arm(arm)) {
1196                 command_print(CMD, "ETM: current target isn't an ARM");
1197                 return ERROR_FAIL;
1198         }
1199
1200         etm = arm->etm;
1201         if (!etm) {
1202                 command_print(CMD, "current target doesn't have an ETM configured");
1203                 return ERROR_FAIL;
1204         }
1205
1206         uint32_t tracemode = etm->control;
1207
1208         switch (CMD_ARGC) {
1209                 case 0:
1210                         break;
1211                 case 4:
1212                         CALL_COMMAND_HANDLER(handle_etm_tracemode_command_update,
1213                                 &tracemode);
1214                         break;
1215                 default:
1216                         return ERROR_COMMAND_SYNTAX_ERROR;
1217         }
1218
1219         /**
1220          * todo: fail if parameters were invalid for this hardware,
1221          * or couldn't be written; display actual hardware state...
1222          */
1223
1224         command_print(CMD, "current tracemode configuration:");
1225
1226         switch (tracemode & ETM_CTRL_TRACE_MASK) {
1227                 default:
1228                         command_print(CMD, "data tracing: none");
1229                         break;
1230                 case ETM_CTRL_TRACE_DATA:
1231                         command_print(CMD, "data tracing: data only");
1232                         break;
1233                 case ETM_CTRL_TRACE_ADDR:
1234                         command_print(CMD, "data tracing: address only");
1235                         break;
1236                 case ETM_CTRL_TRACE_DATA | ETM_CTRL_TRACE_ADDR:
1237                         command_print(CMD, "data tracing: address and data");
1238                         break;
1239         }
1240
1241         switch (tracemode & ETM_CTRL_CONTEXTID_MASK) {
1242                 case ETM_CTRL_CONTEXTID_NONE:
1243                         command_print(CMD, "contextid tracing: none");
1244                         break;
1245                 case ETM_CTRL_CONTEXTID_8:
1246                         command_print(CMD, "contextid tracing: 8 bit");
1247                         break;
1248                 case ETM_CTRL_CONTEXTID_16:
1249                         command_print(CMD, "contextid tracing: 16 bit");
1250                         break;
1251                 case ETM_CTRL_CONTEXTID_32:
1252                         command_print(CMD, "contextid tracing: 32 bit");
1253                         break;
1254         }
1255
1256         if (tracemode & ETM_CTRL_CYCLE_ACCURATE)
1257                 command_print(CMD, "cycle-accurate tracing enabled");
1258         else
1259                 command_print(CMD, "cycle-accurate tracing disabled");
1260
1261         if (tracemode & ETM_CTRL_BRANCH_OUTPUT)
1262                 command_print(CMD, "full branch address output enabled");
1263         else
1264                 command_print(CMD, "full branch address output disabled");
1265
1266 #define TRACEMODE_MASK ( \
1267                 ETM_CTRL_CONTEXTID_MASK \
1268                 | ETM_CTRL_BRANCH_OUTPUT \
1269                 | ETM_CTRL_CYCLE_ACCURATE \
1270                 | ETM_CTRL_TRACE_MASK \
1271                 )
1272
1273         /* only update ETM_CTRL register if tracemode changed */
1274         if ((etm->control & TRACEMODE_MASK) != tracemode) {
1275                 struct reg *etm_ctrl_reg;
1276
1277                 etm_ctrl_reg = etm_reg_lookup(etm, ETM_CTRL);
1278                 if (!etm_ctrl_reg)
1279                         return ERROR_FAIL;
1280
1281                 etm->control &= ~TRACEMODE_MASK;
1282                 etm->control |= tracemode & TRACEMODE_MASK;
1283
1284                 buf_set_u32(etm_ctrl_reg->value, 0, 32, etm->control);
1285                 etm_store_reg(etm_ctrl_reg);
1286
1287                 /* invalidate old trace data */
1288                 etm->capture_status = TRACE_IDLE;
1289                 if (etm->trace_depth > 0) {
1290                         free(etm->trace_data);
1291                         etm->trace_data = NULL;
1292                 }
1293                 etm->trace_depth = 0;
1294         }
1295
1296 #undef TRACEMODE_MASK
1297
1298         return ERROR_OK;
1299 }
1300
1301 COMMAND_HANDLER(handle_etm_config_command)
1302 {
1303         struct target *target;
1304         struct arm *arm;
1305         uint32_t portmode = 0x0;
1306         struct etm_context *etm_ctx;
1307         int i;
1308
1309         if (CMD_ARGC != 5)
1310                 return ERROR_COMMAND_SYNTAX_ERROR;
1311
1312         target = get_target(CMD_ARGV[0]);
1313         if (!target) {
1314                 LOG_ERROR("target '%s' not defined", CMD_ARGV[0]);
1315                 return ERROR_FAIL;
1316         }
1317
1318         arm = target_to_arm(target);
1319         if (!is_arm(arm)) {
1320                 command_print(CMD, "target '%s' is '%s'; not an ARM",
1321                         target_name(target),
1322                         target_type_name(target));
1323                 return ERROR_FAIL;
1324         }
1325
1326         /* FIXME for ETMv3.0 and above -- and we don't yet know what ETM
1327          * version we'll be using!! -- so we can't know how to validate
1328          * params yet.  "etm config" should likely be *AFTER* hookup...
1329          *
1330          *  - Many more widths might be supported ... and we can easily
1331          *    check whether our setting "took".
1332          *
1333          *  - The "clock" and "mode" bits are interpreted differently.
1334          *    See ARM IHI 0014O table 2-17 for the old behaviour, and
1335          *    table 2-18 for the new.  With ETB it's best to specify
1336          *    "normal full" ...
1337          */
1338         uint8_t port_width;
1339         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[1], port_width);
1340         switch (port_width) {
1341                 /* before ETMv3.0 */
1342                 case 4:
1343                         portmode |= ETM_PORT_4BIT;
1344                         break;
1345                 case 8:
1346                         portmode |= ETM_PORT_8BIT;
1347                         break;
1348                 case 16:
1349                         portmode |= ETM_PORT_16BIT;
1350                         break;
1351                 /* ETMv3.0 and later*/
1352                 case 24:
1353                         portmode |= ETM_PORT_24BIT;
1354                         break;
1355                 case 32:
1356                         portmode |= ETM_PORT_32BIT;
1357                         break;
1358                 case 48:
1359                         portmode |= ETM_PORT_48BIT;
1360                         break;
1361                 case 64:
1362                         portmode |= ETM_PORT_64BIT;
1363                         break;
1364                 case 1:
1365                         portmode |= ETM_PORT_1BIT;
1366                         break;
1367                 case 2:
1368                         portmode |= ETM_PORT_2BIT;
1369                         break;
1370                 default:
1371                         command_print(CMD,
1372                                 "unsupported ETM port width '%s'", CMD_ARGV[1]);
1373                         return ERROR_FAIL;
1374         }
1375
1376         if (strcmp("normal", CMD_ARGV[2]) == 0)
1377                 portmode |= ETM_PORT_NORMAL;
1378         else if (strcmp("multiplexed", CMD_ARGV[2]) == 0)
1379                 portmode |= ETM_PORT_MUXED;
1380         else if (strcmp("demultiplexed", CMD_ARGV[2]) == 0)
1381                 portmode |= ETM_PORT_DEMUXED;
1382         else {
1383                 command_print(CMD,
1384                         "unsupported ETM port mode '%s', must be 'normal', 'multiplexed' or 'demultiplexed'",
1385                         CMD_ARGV[2]);
1386                 return ERROR_FAIL;
1387         }
1388
1389         if (strcmp("half", CMD_ARGV[3]) == 0)
1390                 portmode |= ETM_PORT_HALF_CLOCK;
1391         else if (strcmp("full", CMD_ARGV[3]) == 0)
1392                 portmode |= ETM_PORT_FULL_CLOCK;
1393         else {
1394                 command_print(CMD,
1395                         "unsupported ETM port clocking '%s', must be 'full' or 'half'",
1396                         CMD_ARGV[3]);
1397                 return ERROR_FAIL;
1398         }
1399
1400         etm_ctx = calloc(1, sizeof(struct etm_context));
1401         if (!etm_ctx) {
1402                 LOG_DEBUG("out of memory");
1403                 return ERROR_FAIL;
1404         }
1405
1406         for (i = 0; etm_capture_drivers[i]; i++) {
1407                 if (strcmp(CMD_ARGV[4], etm_capture_drivers[i]->name) == 0) {
1408                         int retval = register_commands(CMD_CTX, NULL, etm_capture_drivers[i]->commands);
1409                         if (retval != ERROR_OK) {
1410                                 free(etm_ctx);
1411                                 return retval;
1412                         }
1413
1414                         etm_ctx->capture_driver = etm_capture_drivers[i];
1415
1416                         break;
1417                 }
1418         }
1419
1420         if (!etm_capture_drivers[i]) {
1421                 /* no supported capture driver found, don't register an ETM */
1422                 free(etm_ctx);
1423                 LOG_ERROR("trace capture driver '%s' not found", CMD_ARGV[4]);
1424                 return ERROR_FAIL;
1425         }
1426
1427         etm_ctx->target = target;
1428         etm_ctx->trace_data = NULL;
1429         etm_ctx->control = portmode;
1430         etm_ctx->core_state = ARM_STATE_ARM;
1431
1432         arm->etm = etm_ctx;
1433
1434         return etm_register_user_commands(CMD_CTX);
1435 }
1436
1437 COMMAND_HANDLER(handle_etm_info_command)
1438 {
1439         struct target *target;
1440         struct arm *arm;
1441         struct etm_context *etm;
1442         struct reg *etm_sys_config_reg;
1443         int max_port_size;
1444         uint32_t config;
1445
1446         target = get_current_target(CMD_CTX);
1447         arm = target_to_arm(target);
1448         if (!is_arm(arm)) {
1449                 command_print(CMD, "ETM: current target isn't an ARM");
1450                 return ERROR_FAIL;
1451         }
1452
1453         etm = arm->etm;
1454         if (!etm) {
1455                 command_print(CMD, "current target doesn't have an ETM configured");
1456                 return ERROR_FAIL;
1457         }
1458
1459         command_print(CMD, "ETM v%d.%d",
1460                 etm->bcd_vers >> 4, etm->bcd_vers & 0xf);
1461         command_print(CMD, "pairs of address comparators: %i",
1462                 (int) (etm->config >> 0) & 0x0f);
1463         command_print(CMD, "data comparators: %i",
1464                 (int) (etm->config >> 4) & 0x0f);
1465         command_print(CMD, "memory map decoders: %i",
1466                 (int) (etm->config >> 8) & 0x1f);
1467         command_print(CMD, "number of counters: %i",
1468                 (int) (etm->config >> 13) & 0x07);
1469         command_print(CMD, "sequencer %spresent",
1470                 (int) (etm->config & (1 << 16)) ? "" : "not ");
1471         command_print(CMD, "number of ext. inputs: %i",
1472                 (int) (etm->config >> 17) & 0x07);
1473         command_print(CMD, "number of ext. outputs: %i",
1474                 (int) (etm->config >> 20) & 0x07);
1475         command_print(CMD, "FIFO full %spresent",
1476                 (int) (etm->config & (1 << 23)) ? "" : "not ");
1477         if (etm->bcd_vers < 0x20)
1478                 command_print(CMD, "protocol version: %i",
1479                         (int) (etm->config >> 28) & 0x07);
1480         else {
1481                 command_print(CMD,
1482                         "coprocessor and memory access %ssupported",
1483                         (etm->config & (1 << 26)) ? "" : "not ");
1484                 command_print(CMD, "trace start/stop %spresent",
1485                         (etm->config & (1 << 26)) ? "" : "not ");
1486                 command_print(CMD, "number of context comparators: %i",
1487                         (int) (etm->config >> 24) & 0x03);
1488         }
1489
1490         /* SYS_CONFIG isn't present before ETMv1.2 */
1491         etm_sys_config_reg = etm_reg_lookup(etm, ETM_SYS_CONFIG);
1492         if (!etm_sys_config_reg)
1493                 return ERROR_OK;
1494
1495         etm_get_reg(etm_sys_config_reg);
1496         config = buf_get_u32(etm_sys_config_reg->value, 0, 32);
1497
1498         LOG_DEBUG("ETM SYS CONFIG %08x", (unsigned) config);
1499
1500         max_port_size = config & 0x7;
1501         if (etm->bcd_vers >= 0x30)
1502                 max_port_size |= (config >> 6) & 0x08;
1503         switch (max_port_size) {
1504                 /* before ETMv3.0 */
1505                 case 0:
1506                         max_port_size = 4;
1507                         break;
1508                 case 1:
1509                         max_port_size = 8;
1510                         break;
1511                 case 2:
1512                         max_port_size = 16;
1513                         break;
1514                 /* ETMv3.0 and later*/
1515                 case 3:
1516                         max_port_size = 24;
1517                         break;
1518                 case 4:
1519                         max_port_size = 32;
1520                         break;
1521                 case 5:
1522                         max_port_size = 48;
1523                         break;
1524                 case 6:
1525                         max_port_size = 64;
1526                         break;
1527                 case 8:
1528                         max_port_size = 1;
1529                         break;
1530                 case 9:
1531                         max_port_size = 2;
1532                         break;
1533                 default:
1534                         LOG_ERROR("Illegal max_port_size");
1535                         return ERROR_FAIL;
1536         }
1537         command_print(CMD, "max. port size: %i", max_port_size);
1538
1539         if (etm->bcd_vers < 0x30) {
1540                 command_print(CMD, "half-rate clocking %ssupported",
1541                         (config & (1 << 3)) ? "" : "not ");
1542                 command_print(CMD, "full-rate clocking %ssupported",
1543                         (config & (1 << 4)) ? "" : "not ");
1544                 command_print(CMD, "normal trace format %ssupported",
1545                         (config & (1 << 5)) ? "" : "not ");
1546                 command_print(CMD, "multiplex trace format %ssupported",
1547                         (config & (1 << 6)) ? "" : "not ");
1548                 command_print(CMD, "demultiplex trace format %ssupported",
1549                         (config & (1 << 7)) ? "" : "not ");
1550         } else {
1551                 /* REVISIT show which size and format are selected ... */
1552                 command_print(CMD, "current port size %ssupported",
1553                         (config & (1 << 10)) ? "" : "not ");
1554                 command_print(CMD, "current trace format %ssupported",
1555                         (config & (1 << 11)) ? "" : "not ");
1556         }
1557         if (etm->bcd_vers >= 0x21)
1558                 command_print(CMD, "fetch comparisons %ssupported",
1559                         (config & (1 << 17)) ? "not " : "");
1560         command_print(CMD, "FIFO full %ssupported",
1561                 (config & (1 << 8)) ? "" : "not ");
1562
1563         return ERROR_OK;
1564 }
1565
1566 COMMAND_HANDLER(handle_etm_status_command)
1567 {
1568         struct target *target;
1569         struct arm *arm;
1570         struct etm_context *etm;
1571         trace_status_t trace_status;
1572
1573         target = get_current_target(CMD_CTX);
1574         arm = target_to_arm(target);
1575         if (!is_arm(arm)) {
1576                 command_print(CMD, "ETM: current target isn't an ARM");
1577                 return ERROR_FAIL;
1578         }
1579
1580         etm = arm->etm;
1581         if (!etm) {
1582                 command_print(CMD, "current target doesn't have an ETM configured");
1583                 return ERROR_FAIL;
1584         }
1585
1586         /* ETM status */
1587         if (etm->bcd_vers >= 0x11) {
1588                 struct reg *reg;
1589
1590                 reg = etm_reg_lookup(etm, ETM_STATUS);
1591                 if (!reg)
1592                         return ERROR_FAIL;
1593                 if (etm_get_reg(reg) == ERROR_OK) {
1594                         unsigned s = buf_get_u32(reg->value, 0, reg->size);
1595
1596                         command_print(CMD, "etm: %s%s%s%s",
1597                                 /* bit(1) == progbit */
1598                                 (etm->bcd_vers >= 0x12)
1599                                 ? ((s & (1 << 1))
1600                                 ? "disabled" : "enabled")
1601                                 : "?",
1602                                 ((s & (1 << 3)) && etm->bcd_vers >= 0x31)
1603                                 ? " triggered" : "",
1604                                 ((s & (1 << 2)) && etm->bcd_vers >= 0x12)
1605                                 ? " start/stop" : "",
1606                                 ((s & (1 << 0)) && etm->bcd_vers >= 0x11)
1607                                 ? " untraced-overflow" : "");
1608                 }       /* else ignore and try showing trace port status */
1609         }
1610
1611         /* Trace Port Driver status */
1612         trace_status = etm->capture_driver->status(etm);
1613         if (trace_status == TRACE_IDLE)
1614                 command_print(CMD, "%s: idle", etm->capture_driver->name);
1615         else {
1616                 static char *completed = " completed";
1617                 static char *running = " is running";
1618                 static char *overflowed = ", overflowed";
1619                 static char *triggered = ", triggered";
1620
1621                 command_print(CMD, "%s: trace collection%s%s%s",
1622                         etm->capture_driver->name,
1623                         (trace_status & TRACE_RUNNING) ? running : completed,
1624                         (trace_status & TRACE_OVERFLOWED) ? overflowed : "",
1625                         (trace_status & TRACE_TRIGGERED) ? triggered : "");
1626
1627                 if (etm->trace_depth > 0) {
1628                         command_print(CMD, "%i frames of trace data read",
1629                                 (int)(etm->trace_depth));
1630                 }
1631         }
1632
1633         return ERROR_OK;
1634 }
1635
1636 COMMAND_HANDLER(handle_etm_image_command)
1637 {
1638         struct target *target;
1639         struct arm *arm;
1640         struct etm_context *etm_ctx;
1641
1642         if (CMD_ARGC < 1)
1643                 return ERROR_COMMAND_SYNTAX_ERROR;
1644
1645         target = get_current_target(CMD_CTX);
1646         arm = target_to_arm(target);
1647         if (!is_arm(arm)) {
1648                 command_print(CMD, "ETM: current target isn't an ARM");
1649                 return ERROR_FAIL;
1650         }
1651
1652         etm_ctx = arm->etm;
1653         if (!etm_ctx) {
1654                 command_print(CMD, "current target doesn't have an ETM configured");
1655                 return ERROR_FAIL;
1656         }
1657
1658         if (etm_ctx->image) {
1659                 image_close(etm_ctx->image);
1660                 free(etm_ctx->image);
1661                 command_print(CMD, "previously loaded image found and closed");
1662         }
1663
1664         etm_ctx->image = malloc(sizeof(struct image));
1665         etm_ctx->image->base_address_set = false;
1666         etm_ctx->image->start_address_set = false;
1667
1668         /* a base address isn't always necessary, default to 0x0 (i.e. don't relocate) */
1669         if (CMD_ARGC >= 2) {
1670                 etm_ctx->image->base_address_set = true;
1671                 COMMAND_PARSE_NUMBER(llong, CMD_ARGV[1], etm_ctx->image->base_address);
1672         } else
1673                 etm_ctx->image->base_address_set = false;
1674
1675         if (image_open(etm_ctx->image, CMD_ARGV[0],
1676                 (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK) {
1677                 free(etm_ctx->image);
1678                 etm_ctx->image = NULL;
1679                 return ERROR_FAIL;
1680         }
1681
1682         return ERROR_OK;
1683 }
1684
1685 COMMAND_HANDLER(handle_etm_dump_command)
1686 {
1687         struct fileio *file;
1688         struct target *target;
1689         struct arm *arm;
1690         struct etm_context *etm_ctx;
1691         uint32_t i;
1692
1693         if (CMD_ARGC != 1)
1694                 return ERROR_COMMAND_SYNTAX_ERROR;
1695
1696         target = get_current_target(CMD_CTX);
1697         arm = target_to_arm(target);
1698         if (!is_arm(arm)) {
1699                 command_print(CMD, "ETM: current target isn't an ARM");
1700                 return ERROR_FAIL;
1701         }
1702
1703         etm_ctx = arm->etm;
1704         if (!etm_ctx) {
1705                 command_print(CMD, "current target doesn't have an ETM configured");
1706                 return ERROR_FAIL;
1707         }
1708
1709         if (etm_ctx->capture_driver->status == TRACE_IDLE) {
1710                 command_print(CMD, "trace capture wasn't enabled, no trace data captured");
1711                 return ERROR_OK;
1712         }
1713
1714         if (etm_ctx->capture_driver->status(etm_ctx) & TRACE_RUNNING) {
1715                 /* TODO: if on-the-fly capture is to be supported, this needs to be changed */
1716                 command_print(CMD, "trace capture not completed");
1717                 return ERROR_FAIL;
1718         }
1719
1720         /* read the trace data if it wasn't read already */
1721         if (etm_ctx->trace_depth == 0)
1722                 etm_ctx->capture_driver->read_trace(etm_ctx);
1723
1724         if (fileio_open(&file, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
1725                 return ERROR_FAIL;
1726
1727         fileio_write_u32(file, etm_ctx->capture_status);
1728         fileio_write_u32(file, etm_ctx->control);
1729         fileio_write_u32(file, etm_ctx->trace_depth);
1730
1731         for (i = 0; i < etm_ctx->trace_depth; i++) {
1732                 fileio_write_u32(file, etm_ctx->trace_data[i].pipestat);
1733                 fileio_write_u32(file, etm_ctx->trace_data[i].packet);
1734                 fileio_write_u32(file, etm_ctx->trace_data[i].flags);
1735         }
1736
1737         fileio_close(file);
1738
1739         return ERROR_OK;
1740 }
1741
1742 COMMAND_HANDLER(handle_etm_load_command)
1743 {
1744         struct fileio *file;
1745         struct target *target;
1746         struct arm *arm;
1747         struct etm_context *etm_ctx;
1748         uint32_t i;
1749
1750         if (CMD_ARGC != 1)
1751                 return ERROR_COMMAND_SYNTAX_ERROR;
1752
1753         target = get_current_target(CMD_CTX);
1754         arm = target_to_arm(target);
1755         if (!is_arm(arm)) {
1756                 command_print(CMD, "ETM: current target isn't an ARM");
1757                 return ERROR_FAIL;
1758         }
1759
1760         etm_ctx = arm->etm;
1761         if (!etm_ctx) {
1762                 command_print(CMD, "current target doesn't have an ETM configured");
1763                 return ERROR_FAIL;
1764         }
1765
1766         if (etm_ctx->capture_driver->status(etm_ctx) & TRACE_RUNNING) {
1767                 command_print(CMD, "trace capture running, stop first");
1768                 return ERROR_FAIL;
1769         }
1770
1771         if (fileio_open(&file, CMD_ARGV[0], FILEIO_READ, FILEIO_BINARY) != ERROR_OK)
1772                 return ERROR_FAIL;
1773
1774         size_t filesize;
1775         int retval = fileio_size(file, &filesize);
1776         if (retval != ERROR_OK) {
1777                 fileio_close(file);
1778                 return retval;
1779         }
1780
1781         if (filesize % 4) {
1782                 command_print(CMD, "size isn't a multiple of 4, no valid trace data");
1783                 fileio_close(file);
1784                 return ERROR_FAIL;
1785         }
1786
1787         if (etm_ctx->trace_depth > 0) {
1788                 free(etm_ctx->trace_data);
1789                 etm_ctx->trace_data = NULL;
1790         }
1791
1792         {
1793                 uint32_t tmp;
1794                 fileio_read_u32(file, &tmp); etm_ctx->capture_status = tmp;
1795                 fileio_read_u32(file, &tmp); etm_ctx->control = tmp;
1796                 fileio_read_u32(file, &etm_ctx->trace_depth);
1797         }
1798         etm_ctx->trace_data = malloc(sizeof(struct etmv1_trace_data) * etm_ctx->trace_depth);
1799         if (!etm_ctx->trace_data) {
1800                 command_print(CMD, "not enough memory to perform operation");
1801                 fileio_close(file);
1802                 return ERROR_FAIL;
1803         }
1804
1805         for (i = 0; i < etm_ctx->trace_depth; i++) {
1806                 uint32_t pipestat, packet, flags;
1807                 fileio_read_u32(file, &pipestat);
1808                 fileio_read_u32(file, &packet);
1809                 fileio_read_u32(file, &flags);
1810                 etm_ctx->trace_data[i].pipestat = pipestat & 0xff;
1811                 etm_ctx->trace_data[i].packet = packet & 0xffff;
1812                 etm_ctx->trace_data[i].flags = flags;
1813         }
1814
1815         fileio_close(file);
1816
1817         return ERROR_OK;
1818 }
1819
1820 COMMAND_HANDLER(handle_etm_start_command)
1821 {
1822         struct target *target;
1823         struct arm *arm;
1824         struct etm_context *etm_ctx;
1825         struct reg *etm_ctrl_reg;
1826
1827         target = get_current_target(CMD_CTX);
1828         arm = target_to_arm(target);
1829         if (!is_arm(arm)) {
1830                 command_print(CMD, "ETM: current target isn't an ARM");
1831                 return ERROR_FAIL;
1832         }
1833
1834         etm_ctx = arm->etm;
1835         if (!etm_ctx) {
1836                 command_print(CMD, "current target doesn't have an ETM configured");
1837                 return ERROR_FAIL;
1838         }
1839
1840         /* invalidate old tracing data */
1841         etm_ctx->capture_status = TRACE_IDLE;
1842         if (etm_ctx->trace_depth > 0) {
1843                 free(etm_ctx->trace_data);
1844                 etm_ctx->trace_data = NULL;
1845         }
1846         etm_ctx->trace_depth = 0;
1847
1848         etm_ctrl_reg = etm_reg_lookup(etm_ctx, ETM_CTRL);
1849         if (!etm_ctrl_reg)
1850                 return ERROR_FAIL;
1851
1852         etm_get_reg(etm_ctrl_reg);
1853
1854         /* Clear programming bit (10), set port selection bit (11) */
1855         buf_set_u32(etm_ctrl_reg->value, 10, 2, 0x2);
1856
1857         etm_store_reg(etm_ctrl_reg);
1858         jtag_execute_queue();
1859
1860         etm_ctx->capture_driver->start_capture(etm_ctx);
1861
1862         return ERROR_OK;
1863 }
1864
1865 COMMAND_HANDLER(handle_etm_stop_command)
1866 {
1867         struct target *target;
1868         struct arm *arm;
1869         struct etm_context *etm_ctx;
1870         struct reg *etm_ctrl_reg;
1871
1872         target = get_current_target(CMD_CTX);
1873         arm = target_to_arm(target);
1874         if (!is_arm(arm)) {
1875                 command_print(CMD, "ETM: current target isn't an ARM");
1876                 return ERROR_FAIL;
1877         }
1878
1879         etm_ctx = arm->etm;
1880         if (!etm_ctx) {
1881                 command_print(CMD, "current target doesn't have an ETM configured");
1882                 return ERROR_FAIL;
1883         }
1884
1885         etm_ctrl_reg = etm_reg_lookup(etm_ctx, ETM_CTRL);
1886         if (!etm_ctrl_reg)
1887                 return ERROR_FAIL;
1888
1889         etm_get_reg(etm_ctrl_reg);
1890
1891         /* Set programming bit (10), clear port selection bit (11) */
1892         buf_set_u32(etm_ctrl_reg->value, 10, 2, 0x1);
1893
1894         etm_store_reg(etm_ctrl_reg);
1895         jtag_execute_queue();
1896
1897         etm_ctx->capture_driver->stop_capture(etm_ctx);
1898
1899         return ERROR_OK;
1900 }
1901
1902 COMMAND_HANDLER(handle_etm_trigger_debug_command)
1903 {
1904         struct target *target;
1905         struct arm *arm;
1906         struct etm_context *etm;
1907
1908         target = get_current_target(CMD_CTX);
1909         arm = target_to_arm(target);
1910         if (!is_arm(arm)) {
1911                 command_print(CMD, "ETM: %s isn't an ARM",
1912                         target_name(target));
1913                 return ERROR_FAIL;
1914         }
1915
1916         etm = arm->etm;
1917         if (!etm) {
1918                 command_print(CMD, "ETM: no ETM configured for %s",
1919                         target_name(target));
1920                 return ERROR_FAIL;
1921         }
1922
1923         if (CMD_ARGC == 1) {
1924                 struct reg *etm_ctrl_reg;
1925                 bool dbgrq;
1926
1927                 etm_ctrl_reg = etm_reg_lookup(etm, ETM_CTRL);
1928                 if (!etm_ctrl_reg)
1929                         return ERROR_FAIL;
1930
1931                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], dbgrq);
1932                 if (dbgrq)
1933                         etm->control |= ETM_CTRL_DBGRQ;
1934                 else
1935                         etm->control &= ~ETM_CTRL_DBGRQ;
1936
1937                 /* etm->control will be written to hardware
1938                  * the next time an "etm start" is issued.
1939                  */
1940                 buf_set_u32(etm_ctrl_reg->value, 0, 32, etm->control);
1941         }
1942
1943         command_print(CMD, "ETM: %s debug halt",
1944                 (etm->control & ETM_CTRL_DBGRQ)
1945                 ? "triggers"
1946                 : "does not trigger");
1947         return ERROR_OK;
1948 }
1949
1950 COMMAND_HANDLER(handle_etm_analyze_command)
1951 {
1952         struct target *target;
1953         struct arm *arm;
1954         struct etm_context *etm_ctx;
1955         int retval;
1956
1957         target = get_current_target(CMD_CTX);
1958         arm = target_to_arm(target);
1959         if (!is_arm(arm)) {
1960                 command_print(CMD, "ETM: current target isn't an ARM");
1961                 return ERROR_FAIL;
1962         }
1963
1964         etm_ctx = arm->etm;
1965         if (!etm_ctx) {
1966                 command_print(CMD, "current target doesn't have an ETM configured");
1967                 return ERROR_FAIL;
1968         }
1969
1970         retval = etmv1_analyze_trace(etm_ctx, CMD);
1971         if (retval != ERROR_OK) {
1972                 /* FIX! error should be reported inside etmv1_analyze_trace() */
1973                 switch (retval) {
1974                         case ERROR_ETM_ANALYSIS_FAILED:
1975                                 command_print(CMD,
1976                                         "further analysis failed (corrupted trace data or just end of data");
1977                                 break;
1978                         case ERROR_TRACE_INSTRUCTION_UNAVAILABLE:
1979                                 command_print(CMD,
1980                                         "no instruction for current address available, analysis aborted");
1981                                 break;
1982                         case ERROR_TRACE_IMAGE_UNAVAILABLE:
1983                                 command_print(CMD, "no image available for trace analysis");
1984                                 break;
1985                         default:
1986                                 command_print(CMD, "unknown error");
1987                 }
1988         }
1989
1990         return retval;
1991 }
1992
1993 static const struct command_registration etm_config_command_handlers[] = {
1994         {
1995                 /* NOTE:  with ADIv5, ETMs are accessed by DAP operations,
1996                  * possibly over SWD, not JTAG scanchain 6 of 'target'.
1997                  *
1998                  * Also, these parameters don't match ETM v3+ modules...
1999                  */
2000                 .name = "config",
2001                 .handler = handle_etm_config_command,
2002                 .mode = COMMAND_CONFIG,
2003                 .help = "Set up ETM output port.",
2004                 .usage = "target port_width port_mode clocking capture_driver",
2005         },
2006         COMMAND_REGISTRATION_DONE
2007 };
2008 const struct command_registration etm_command_handlers[] = {
2009         {
2010                 .name = "etm",
2011                 .mode = COMMAND_ANY,
2012                 .help = "Embedded Trace Macrocell command group",
2013                 .usage = "",
2014                 .chain = etm_config_command_handlers,
2015         },
2016         COMMAND_REGISTRATION_DONE
2017 };
2018
2019 static const struct command_registration etm_exec_command_handlers[] = {
2020         {
2021                 .name = "tracemode",
2022                 .handler = handle_etm_tracemode_command,
2023                 .mode = COMMAND_EXEC,
2024                 .help = "configure/display trace mode",
2025                 .usage = "('none'|'data'|'address'|'all') "
2026                         "context_id_bits "
2027                         "['enable'|'disable'] "
2028                         "['enable'|'disable']",
2029         },
2030         {
2031                 .name = "info",
2032                 .handler = handle_etm_info_command,
2033                 .mode = COMMAND_EXEC,
2034                 .usage = "",
2035                 .help = "display info about the current target's ETM",
2036         },
2037         {
2038                 .name = "status",
2039                 .handler = handle_etm_status_command,
2040                 .mode = COMMAND_EXEC,
2041                 .usage = "",
2042                 .help = "display current target's ETM status",
2043         },
2044         {
2045                 .name = "start",
2046                 .handler = handle_etm_start_command,
2047                 .mode = COMMAND_EXEC,
2048                 .usage = "",
2049                 .help = "start ETM trace collection",
2050         },
2051         {
2052                 .name = "stop",
2053                 .handler = handle_etm_stop_command,
2054                 .mode = COMMAND_EXEC,
2055                 .usage = "",
2056                 .help = "stop ETM trace collection",
2057         },
2058         {
2059                 .name = "trigger_debug",
2060                 .handler = handle_etm_trigger_debug_command,
2061                 .mode = COMMAND_EXEC,
2062                 .help = "enable/disable debug entry on trigger",
2063                 .usage = "['enable'|'disable']",
2064         },
2065         {
2066                 .name = "analyze",
2067                 .handler = handle_etm_analyze_command,
2068                 .mode = COMMAND_EXEC,
2069                 .usage = "",
2070                 .help = "analyze collected ETM trace",
2071         },
2072         {
2073                 .name = "image",
2074                 .handler = handle_etm_image_command,
2075                 .mode = COMMAND_EXEC,
2076                 .help = "load image from file with optional offset",
2077                 .usage = "<file> [base address] [type]",
2078         },
2079         {
2080                 .name = "dump",
2081                 .handler = handle_etm_dump_command,
2082                 .mode = COMMAND_EXEC,
2083                 .help = "dump captured trace data to file",
2084                 .usage = "filename",
2085         },
2086         {
2087                 .name = "load",
2088                 .handler = handle_etm_load_command,
2089                 .mode = COMMAND_EXEC,
2090                 .usage = "",
2091                 .help = "load trace data for analysis <file>",
2092         },
2093         COMMAND_REGISTRATION_DONE
2094 };
2095
2096 static int etm_register_user_commands(struct command_context *cmd_ctx)
2097 {
2098         return register_commands(cmd_ctx, "etm", etm_exec_command_handlers);
2099 }