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