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