target: Remove soft_reset_halt_imp
[fw/openocd] / src / target / target.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2010 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008, Duane Ellis                                       *
9  *   openocd@duaneeellis.com                                               *
10  *                                                                         *
11  *   Copyright (C) 2008 by Spencer Oliver                                  *
12  *   spen@spen-soft.co.uk                                                  *
13  *                                                                         *
14  *   Copyright (C) 2008 by Rick Altherr                                    *
15  *   kc8apf@kc8apf.net>                                                    *
16  *                                                                         *
17  *   Copyright (C) 2011 by Broadcom Corporation                            *
18  *   Evan Hunter - ehunter@broadcom.com                                    *
19  *                                                                         *
20  *   Copyright (C) ST-Ericsson SA 2011                                     *
21  *   michel.jaouen@stericsson.com : smp minimum support                    *
22  *                                                                         *
23  *   Copyright (C) 2011 Andreas Fritiofson                                 *
24  *   andreas.fritiofson@gmail.com                                          *
25  *                                                                         *
26  *   This program is free software; you can redistribute it and/or modify  *
27  *   it under the terms of the GNU General Public License as published by  *
28  *   the Free Software Foundation; either version 2 of the License, or     *
29  *   (at your option) any later version.                                   *
30  *                                                                         *
31  *   This program is distributed in the hope that it will be useful,       *
32  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
33  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
34  *   GNU General Public License for more details.                          *
35  *                                                                         *
36  *   You should have received a copy of the GNU General Public License     *
37  *   along with this program; if not, write to the                         *
38  *   Free Software Foundation, Inc.,                                       *
39  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
40  ***************************************************************************/
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
49
50 #include "target.h"
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
54 #include "register.h"
55 #include "trace.h"
56 #include "image.h"
57 #include "rtos/rtos.h"
58
59 static int target_read_buffer_default(struct target *target, uint32_t address,
60                 uint32_t size, uint8_t *buffer);
61 static int target_write_buffer_default(struct target *target, uint32_t address,
62                 uint32_t size, const uint8_t *buffer);
63 static int target_array2mem(Jim_Interp *interp, struct target *target,
64                 int argc, Jim_Obj * const *argv);
65 static int target_mem2array(Jim_Interp *interp, struct target *target,
66                 int argc, Jim_Obj * const *argv);
67 static int target_register_user_commands(struct command_context *cmd_ctx);
68
69 /* targets */
70 extern struct target_type arm7tdmi_target;
71 extern struct target_type arm720t_target;
72 extern struct target_type arm9tdmi_target;
73 extern struct target_type arm920t_target;
74 extern struct target_type arm966e_target;
75 extern struct target_type arm946e_target;
76 extern struct target_type arm926ejs_target;
77 extern struct target_type fa526_target;
78 extern struct target_type feroceon_target;
79 extern struct target_type dragonite_target;
80 extern struct target_type xscale_target;
81 extern struct target_type cortexm3_target;
82 extern struct target_type cortexa8_target;
83 extern struct target_type arm11_target;
84 extern struct target_type mips_m4k_target;
85 extern struct target_type avr_target;
86 extern struct target_type dsp563xx_target;
87 extern struct target_type dsp5680xx_target;
88 extern struct target_type testee_target;
89 extern struct target_type avr32_ap7k_target;
90 extern struct target_type hla_target;
91
92 static struct target_type *target_types[] = {
93         &arm7tdmi_target,
94         &arm9tdmi_target,
95         &arm920t_target,
96         &arm720t_target,
97         &arm966e_target,
98         &arm946e_target,
99         &arm926ejs_target,
100         &fa526_target,
101         &feroceon_target,
102         &dragonite_target,
103         &xscale_target,
104         &cortexm3_target,
105         &cortexa8_target,
106         &arm11_target,
107         &mips_m4k_target,
108         &avr_target,
109         &dsp563xx_target,
110         &dsp5680xx_target,
111         &testee_target,
112         &avr32_ap7k_target,
113         &hla_target,
114         NULL,
115 };
116
117 struct target *all_targets;
118 static struct target_event_callback *target_event_callbacks;
119 static struct target_timer_callback *target_timer_callbacks;
120 static const int polling_interval = 100;
121
122 static const Jim_Nvp nvp_assert[] = {
123         { .name = "assert", NVP_ASSERT },
124         { .name = "deassert", NVP_DEASSERT },
125         { .name = "T", NVP_ASSERT },
126         { .name = "F", NVP_DEASSERT },
127         { .name = "t", NVP_ASSERT },
128         { .name = "f", NVP_DEASSERT },
129         { .name = NULL, .value = -1 }
130 };
131
132 static const Jim_Nvp nvp_error_target[] = {
133         { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
134         { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
135         { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
136         { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
137         { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
138         { .value = ERROR_TARGET_UNALIGNED_ACCESS   , .name = "err-unaligned-access" },
139         { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
140         { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
141         { .value = ERROR_TARGET_TRANSLATION_FAULT  , .name = "err-translation-fault" },
142         { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
143         { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
144         { .value = -1, .name = NULL }
145 };
146
147 static const char *target_strerror_safe(int err)
148 {
149         const Jim_Nvp *n;
150
151         n = Jim_Nvp_value2name_simple(nvp_error_target, err);
152         if (n->name == NULL)
153                 return "unknown";
154         else
155                 return n->name;
156 }
157
158 static const Jim_Nvp nvp_target_event[] = {
159
160         { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
161         { .value = TARGET_EVENT_HALTED, .name = "halted" },
162         { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
163         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
164         { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
165
166         { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
167         { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
168
169         { .value = TARGET_EVENT_RESET_START,         .name = "reset-start" },
170         { .value = TARGET_EVENT_RESET_ASSERT_PRE,    .name = "reset-assert-pre" },
171         { .value = TARGET_EVENT_RESET_ASSERT,        .name = "reset-assert" },
172         { .value = TARGET_EVENT_RESET_ASSERT_POST,   .name = "reset-assert-post" },
173         { .value = TARGET_EVENT_RESET_DEASSERT_PRE,  .name = "reset-deassert-pre" },
174         { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
175         { .value = TARGET_EVENT_RESET_HALT_PRE,      .name = "reset-halt-pre" },
176         { .value = TARGET_EVENT_RESET_HALT_POST,     .name = "reset-halt-post" },
177         { .value = TARGET_EVENT_RESET_WAIT_PRE,      .name = "reset-wait-pre" },
178         { .value = TARGET_EVENT_RESET_WAIT_POST,     .name = "reset-wait-post" },
179         { .value = TARGET_EVENT_RESET_INIT,          .name = "reset-init" },
180         { .value = TARGET_EVENT_RESET_END,           .name = "reset-end" },
181
182         { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
183         { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
184
185         { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
186         { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
187
188         { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
189         { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
190
191         { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
192         { .value = TARGET_EVENT_GDB_FLASH_WRITE_END  , .name = "gdb-flash-write-end"   },
193
194         { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
195         { .value = TARGET_EVENT_GDB_FLASH_ERASE_END  , .name = "gdb-flash-erase-end" },
196
197         { .name = NULL, .value = -1 }
198 };
199
200 static const Jim_Nvp nvp_target_state[] = {
201         { .name = "unknown", .value = TARGET_UNKNOWN },
202         { .name = "running", .value = TARGET_RUNNING },
203         { .name = "halted",  .value = TARGET_HALTED },
204         { .name = "reset",   .value = TARGET_RESET },
205         { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
206         { .name = NULL, .value = -1 },
207 };
208
209 static const Jim_Nvp nvp_target_debug_reason[] = {
210         { .name = "debug-request"            , .value = DBG_REASON_DBGRQ },
211         { .name = "breakpoint"               , .value = DBG_REASON_BREAKPOINT },
212         { .name = "watchpoint"               , .value = DBG_REASON_WATCHPOINT },
213         { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
214         { .name = "single-step"              , .value = DBG_REASON_SINGLESTEP },
215         { .name = "target-not-halted"        , .value = DBG_REASON_NOTHALTED  },
216         { .name = "undefined"                , .value = DBG_REASON_UNDEFINED },
217         { .name = NULL, .value = -1 },
218 };
219
220 static const Jim_Nvp nvp_target_endian[] = {
221         { .name = "big",    .value = TARGET_BIG_ENDIAN },
222         { .name = "little", .value = TARGET_LITTLE_ENDIAN },
223         { .name = "be",     .value = TARGET_BIG_ENDIAN },
224         { .name = "le",     .value = TARGET_LITTLE_ENDIAN },
225         { .name = NULL,     .value = -1 },
226 };
227
228 static const Jim_Nvp nvp_reset_modes[] = {
229         { .name = "unknown", .value = RESET_UNKNOWN },
230         { .name = "run"    , .value = RESET_RUN },
231         { .name = "halt"   , .value = RESET_HALT },
232         { .name = "init"   , .value = RESET_INIT },
233         { .name = NULL     , .value = -1 },
234 };
235
236 const char *debug_reason_name(struct target *t)
237 {
238         const char *cp;
239
240         cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
241                         t->debug_reason)->name;
242         if (!cp) {
243                 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
244                 cp = "(*BUG*unknown*BUG*)";
245         }
246         return cp;
247 }
248
249 const char *target_state_name(struct target *t)
250 {
251         const char *cp;
252         cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
253         if (!cp) {
254                 LOG_ERROR("Invalid target state: %d", (int)(t->state));
255                 cp = "(*BUG*unknown*BUG*)";
256         }
257         return cp;
258 }
259
260 /* determine the number of the new target */
261 static int new_target_number(void)
262 {
263         struct target *t;
264         int x;
265
266         /* number is 0 based */
267         x = -1;
268         t = all_targets;
269         while (t) {
270                 if (x < t->target_number)
271                         x = t->target_number;
272                 t = t->next;
273         }
274         return x + 1;
275 }
276
277 /* read a uint32_t from a buffer in target memory endianness */
278 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
279 {
280         if (target->endianness == TARGET_LITTLE_ENDIAN)
281                 return le_to_h_u32(buffer);
282         else
283                 return be_to_h_u32(buffer);
284 }
285
286 /* read a uint24_t from a buffer in target memory endianness */
287 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
288 {
289         if (target->endianness == TARGET_LITTLE_ENDIAN)
290                 return le_to_h_u24(buffer);
291         else
292                 return be_to_h_u24(buffer);
293 }
294
295 /* read a uint16_t from a buffer in target memory endianness */
296 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
297 {
298         if (target->endianness == TARGET_LITTLE_ENDIAN)
299                 return le_to_h_u16(buffer);
300         else
301                 return be_to_h_u16(buffer);
302 }
303
304 /* read a uint8_t from a buffer in target memory endianness */
305 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
306 {
307         return *buffer & 0x0ff;
308 }
309
310 /* write a uint32_t to a buffer in target memory endianness */
311 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
312 {
313         if (target->endianness == TARGET_LITTLE_ENDIAN)
314                 h_u32_to_le(buffer, value);
315         else
316                 h_u32_to_be(buffer, value);
317 }
318
319 /* write a uint24_t to a buffer in target memory endianness */
320 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
321 {
322         if (target->endianness == TARGET_LITTLE_ENDIAN)
323                 h_u24_to_le(buffer, value);
324         else
325                 h_u24_to_be(buffer, value);
326 }
327
328 /* write a uint16_t to a buffer in target memory endianness */
329 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
330 {
331         if (target->endianness == TARGET_LITTLE_ENDIAN)
332                 h_u16_to_le(buffer, value);
333         else
334                 h_u16_to_be(buffer, value);
335 }
336
337 /* write a uint8_t to a buffer in target memory endianness */
338 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
339 {
340         *buffer = value;
341 }
342
343 /* write a uint32_t array to a buffer in target memory endianness */
344 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
345 {
346         uint32_t i;
347         for (i = 0; i < count; i++)
348                 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
349 }
350
351 /* write a uint16_t array to a buffer in target memory endianness */
352 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
353 {
354         uint32_t i;
355         for (i = 0; i < count; i++)
356                 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
357 }
358
359 /* write a uint32_t array to a buffer in target memory endianness */
360 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, uint32_t *srcbuf)
361 {
362         uint32_t i;
363         for (i = 0; i < count; i++)
364                 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
365 }
366
367 /* write a uint16_t array to a buffer in target memory endianness */
368 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, uint16_t *srcbuf)
369 {
370         uint32_t i;
371         for (i = 0; i < count; i++)
372                 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
373 }
374
375 /* return a pointer to a configured target; id is name or number */
376 struct target *get_target(const char *id)
377 {
378         struct target *target;
379
380         /* try as tcltarget name */
381         for (target = all_targets; target; target = target->next) {
382                 if (target_name(target) == NULL)
383                         continue;
384                 if (strcmp(id, target_name(target)) == 0)
385                         return target;
386         }
387
388         /* It's OK to remove this fallback sometime after August 2010 or so */
389
390         /* no match, try as number */
391         unsigned num;
392         if (parse_uint(id, &num) != ERROR_OK)
393                 return NULL;
394
395         for (target = all_targets; target; target = target->next) {
396                 if (target->target_number == (int)num) {
397                         LOG_WARNING("use '%s' as target identifier, not '%u'",
398                                         target_name(target), num);
399                         return target;
400                 }
401         }
402
403         return NULL;
404 }
405
406 /* returns a pointer to the n-th configured target */
407 static struct target *get_target_by_num(int num)
408 {
409         struct target *target = all_targets;
410
411         while (target) {
412                 if (target->target_number == num)
413                         return target;
414                 target = target->next;
415         }
416
417         return NULL;
418 }
419
420 struct target *get_current_target(struct command_context *cmd_ctx)
421 {
422         struct target *target = get_target_by_num(cmd_ctx->current_target);
423
424         if (target == NULL) {
425                 LOG_ERROR("BUG: current_target out of bounds");
426                 exit(-1);
427         }
428
429         return target;
430 }
431
432 int target_poll(struct target *target)
433 {
434         int retval;
435
436         /* We can't poll until after examine */
437         if (!target_was_examined(target)) {
438                 /* Fail silently lest we pollute the log */
439                 return ERROR_FAIL;
440         }
441
442         retval = target->type->poll(target);
443         if (retval != ERROR_OK)
444                 return retval;
445
446         if (target->halt_issued) {
447                 if (target->state == TARGET_HALTED)
448                         target->halt_issued = false;
449                 else {
450                         long long t = timeval_ms() - target->halt_issued_time;
451                         if (t > 1000) {
452                                 target->halt_issued = false;
453                                 LOG_INFO("Halt timed out, wake up GDB.");
454                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
455                         }
456                 }
457         }
458
459         return ERROR_OK;
460 }
461
462 int target_halt(struct target *target)
463 {
464         int retval;
465         /* We can't poll until after examine */
466         if (!target_was_examined(target)) {
467                 LOG_ERROR("Target not examined yet");
468                 return ERROR_FAIL;
469         }
470
471         retval = target->type->halt(target);
472         if (retval != ERROR_OK)
473                 return retval;
474
475         target->halt_issued = true;
476         target->halt_issued_time = timeval_ms();
477
478         return ERROR_OK;
479 }
480
481 /**
482  * Make the target (re)start executing using its saved execution
483  * context (possibly with some modifications).
484  *
485  * @param target Which target should start executing.
486  * @param current True to use the target's saved program counter instead
487  *      of the address parameter
488  * @param address Optionally used as the program counter.
489  * @param handle_breakpoints True iff breakpoints at the resumption PC
490  *      should be skipped.  (For example, maybe execution was stopped by
491  *      such a breakpoint, in which case it would be counterprodutive to
492  *      let it re-trigger.
493  * @param debug_execution False if all working areas allocated by OpenOCD
494  *      should be released and/or restored to their original contents.
495  *      (This would for example be true to run some downloaded "helper"
496  *      algorithm code, which resides in one such working buffer and uses
497  *      another for data storage.)
498  *
499  * @todo Resolve the ambiguity about what the "debug_execution" flag
500  * signifies.  For example, Target implementations don't agree on how
501  * it relates to invalidation of the register cache, or to whether
502  * breakpoints and watchpoints should be enabled.  (It would seem wrong
503  * to enable breakpoints when running downloaded "helper" algorithms
504  * (debug_execution true), since the breakpoints would be set to match
505  * target firmware being debugged, not the helper algorithm.... and
506  * enabling them could cause such helpers to malfunction (for example,
507  * by overwriting data with a breakpoint instruction.  On the other
508  * hand the infrastructure for running such helpers might use this
509  * procedure but rely on hardware breakpoint to detect termination.)
510  */
511 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
512 {
513         int retval;
514
515         /* We can't poll until after examine */
516         if (!target_was_examined(target)) {
517                 LOG_ERROR("Target not examined yet");
518                 return ERROR_FAIL;
519         }
520
521         target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
522
523         /* note that resume *must* be asynchronous. The CPU can halt before
524          * we poll. The CPU can even halt at the current PC as a result of
525          * a software breakpoint being inserted by (a bug?) the application.
526          */
527         retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
528         if (retval != ERROR_OK)
529                 return retval;
530
531         target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
532
533         return retval;
534 }
535
536 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
537 {
538         char buf[100];
539         int retval;
540         Jim_Nvp *n;
541         n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
542         if (n->name == NULL) {
543                 LOG_ERROR("invalid reset mode");
544                 return ERROR_FAIL;
545         }
546
547         /* disable polling during reset to make reset event scripts
548          * more predictable, i.e. dr/irscan & pathmove in events will
549          * not have JTAG operations injected into the middle of a sequence.
550          */
551         bool save_poll = jtag_poll_get_enabled();
552
553         jtag_poll_set_enabled(false);
554
555         sprintf(buf, "ocd_process_reset %s", n->name);
556         retval = Jim_Eval(cmd_ctx->interp, buf);
557
558         jtag_poll_set_enabled(save_poll);
559
560         if (retval != JIM_OK) {
561                 Jim_MakeErrorMessage(cmd_ctx->interp);
562                 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
563                 return ERROR_FAIL;
564         }
565
566         /* We want any events to be processed before the prompt */
567         retval = target_call_timer_callbacks_now();
568
569         struct target *target;
570         for (target = all_targets; target; target = target->next)
571                 target->type->check_reset(target);
572
573         return retval;
574 }
575
576 static int identity_virt2phys(struct target *target,
577                 uint32_t virtual, uint32_t *physical)
578 {
579         *physical = virtual;
580         return ERROR_OK;
581 }
582
583 static int no_mmu(struct target *target, int *enabled)
584 {
585         *enabled = 0;
586         return ERROR_OK;
587 }
588
589 static int default_examine(struct target *target)
590 {
591         target_set_examined(target);
592         return ERROR_OK;
593 }
594
595 /* no check by default */
596 static int default_check_reset(struct target *target)
597 {
598         return ERROR_OK;
599 }
600
601 int target_examine_one(struct target *target)
602 {
603         return target->type->examine(target);
604 }
605
606 static int jtag_enable_callback(enum jtag_event event, void *priv)
607 {
608         struct target *target = priv;
609
610         if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
611                 return ERROR_OK;
612
613         jtag_unregister_event_callback(jtag_enable_callback, target);
614
615         target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
616
617         int retval = target_examine_one(target);
618         if (retval != ERROR_OK)
619                 return retval;
620
621         target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
622
623         return retval;
624 }
625
626 /* Targets that correctly implement init + examine, i.e.
627  * no communication with target during init:
628  *
629  * XScale
630  */
631 int target_examine(void)
632 {
633         int retval = ERROR_OK;
634         struct target *target;
635
636         for (target = all_targets; target; target = target->next) {
637                 /* defer examination, but don't skip it */
638                 if (!target->tap->enabled) {
639                         jtag_register_event_callback(jtag_enable_callback,
640                                         target);
641                         continue;
642                 }
643
644                 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
645
646                 retval = target_examine_one(target);
647                 if (retval != ERROR_OK)
648                         return retval;
649
650                 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
651         }
652         return retval;
653 }
654
655 const char *target_type_name(struct target *target)
656 {
657         return target->type->name;
658 }
659
660 static int target_write_memory_imp(struct target *target, uint32_t address,
661                 uint32_t size, uint32_t count, const uint8_t *buffer)
662 {
663         if (!target_was_examined(target)) {
664                 LOG_ERROR("Target not examined yet");
665                 return ERROR_FAIL;
666         }
667         return target->type->write_memory_imp(target, address, size, count, buffer);
668 }
669
670 static int target_read_memory_imp(struct target *target, uint32_t address,
671                 uint32_t size, uint32_t count, uint8_t *buffer)
672 {
673         if (!target_was_examined(target)) {
674                 LOG_ERROR("Target not examined yet");
675                 return ERROR_FAIL;
676         }
677         return target->type->read_memory_imp(target, address, size, count, buffer);
678 }
679
680 static int target_soft_reset_halt(struct target *target)
681 {
682         if (!target_was_examined(target)) {
683                 LOG_ERROR("Target not examined yet");
684                 return ERROR_FAIL;
685         }
686         if (!target->type->soft_reset_halt) {
687                 LOG_ERROR("Target %s does not support soft_reset_halt",
688                                 target_name(target));
689                 return ERROR_FAIL;
690         }
691         return target->type->soft_reset_halt(target);
692 }
693
694 /**
695  * Downloads a target-specific native code algorithm to the target,
696  * and executes it.  * Note that some targets may need to set up, enable,
697  * and tear down a breakpoint (hard or * soft) to detect algorithm
698  * termination, while others may support  lower overhead schemes where
699  * soft breakpoints embedded in the algorithm automatically terminate the
700  * algorithm.
701  *
702  * @param target used to run the algorithm
703  * @param arch_info target-specific description of the algorithm.
704  */
705 int target_run_algorithm(struct target *target,
706                 int num_mem_params, struct mem_param *mem_params,
707                 int num_reg_params, struct reg_param *reg_param,
708                 uint32_t entry_point, uint32_t exit_point,
709                 int timeout_ms, void *arch_info)
710 {
711         int retval = ERROR_FAIL;
712
713         if (!target_was_examined(target)) {
714                 LOG_ERROR("Target not examined yet");
715                 goto done;
716         }
717         if (!target->type->run_algorithm) {
718                 LOG_ERROR("Target type '%s' does not support %s",
719                                 target_type_name(target), __func__);
720                 goto done;
721         }
722
723         target->running_alg = true;
724         retval = target->type->run_algorithm(target,
725                         num_mem_params, mem_params,
726                         num_reg_params, reg_param,
727                         entry_point, exit_point, timeout_ms, arch_info);
728         target->running_alg = false;
729
730 done:
731         return retval;
732 }
733
734 /**
735  * Downloads a target-specific native code algorithm to the target,
736  * executes and leaves it running.
737  *
738  * @param target used to run the algorithm
739  * @param arch_info target-specific description of the algorithm.
740  */
741 int target_start_algorithm(struct target *target,
742                 int num_mem_params, struct mem_param *mem_params,
743                 int num_reg_params, struct reg_param *reg_params,
744                 uint32_t entry_point, uint32_t exit_point,
745                 void *arch_info)
746 {
747         int retval = ERROR_FAIL;
748
749         if (!target_was_examined(target)) {
750                 LOG_ERROR("Target not examined yet");
751                 goto done;
752         }
753         if (!target->type->start_algorithm) {
754                 LOG_ERROR("Target type '%s' does not support %s",
755                                 target_type_name(target), __func__);
756                 goto done;
757         }
758         if (target->running_alg) {
759                 LOG_ERROR("Target is already running an algorithm");
760                 goto done;
761         }
762
763         target->running_alg = true;
764         retval = target->type->start_algorithm(target,
765                         num_mem_params, mem_params,
766                         num_reg_params, reg_params,
767                         entry_point, exit_point, arch_info);
768
769 done:
770         return retval;
771 }
772
773 /**
774  * Waits for an algorithm started with target_start_algorithm() to complete.
775  *
776  * @param target used to run the algorithm
777  * @param arch_info target-specific description of the algorithm.
778  */
779 int target_wait_algorithm(struct target *target,
780                 int num_mem_params, struct mem_param *mem_params,
781                 int num_reg_params, struct reg_param *reg_params,
782                 uint32_t exit_point, int timeout_ms,
783                 void *arch_info)
784 {
785         int retval = ERROR_FAIL;
786
787         if (!target->type->wait_algorithm) {
788                 LOG_ERROR("Target type '%s' does not support %s",
789                                 target_type_name(target), __func__);
790                 goto done;
791         }
792         if (!target->running_alg) {
793                 LOG_ERROR("Target is not running an algorithm");
794                 goto done;
795         }
796
797         retval = target->type->wait_algorithm(target,
798                         num_mem_params, mem_params,
799                         num_reg_params, reg_params,
800                         exit_point, timeout_ms, arch_info);
801         if (retval != ERROR_TARGET_TIMEOUT)
802                 target->running_alg = false;
803
804 done:
805         return retval;
806 }
807
808 /**
809  * Executes a target-specific native code algorithm in the target.
810  * It differs from target_run_algorithm in that the algorithm is asynchronous.
811  * Because of this it requires an compliant algorithm:
812  * see contrib/loaders/flash/stm32f1x.S for example.
813  *
814  * @param target used to run the algorithm
815  */
816
817 int target_run_flash_async_algorithm(struct target *target,
818                 uint8_t *buffer, uint32_t count, int block_size,
819                 int num_mem_params, struct mem_param *mem_params,
820                 int num_reg_params, struct reg_param *reg_params,
821                 uint32_t buffer_start, uint32_t buffer_size,
822                 uint32_t entry_point, uint32_t exit_point, void *arch_info)
823 {
824         int retval;
825         int timeout = 0;
826
827         /* Set up working area. First word is write pointer, second word is read pointer,
828          * rest is fifo data area. */
829         uint32_t wp_addr = buffer_start;
830         uint32_t rp_addr = buffer_start + 4;
831         uint32_t fifo_start_addr = buffer_start + 8;
832         uint32_t fifo_end_addr = buffer_start + buffer_size;
833
834         uint32_t wp = fifo_start_addr;
835         uint32_t rp = fifo_start_addr;
836
837         /* validate block_size is 2^n */
838         assert(!block_size || !(block_size & (block_size - 1)));
839
840         retval = target_write_u32(target, wp_addr, wp);
841         if (retval != ERROR_OK)
842                 return retval;
843         retval = target_write_u32(target, rp_addr, rp);
844         if (retval != ERROR_OK)
845                 return retval;
846
847         /* Start up algorithm on target and let it idle while writing the first chunk */
848         retval = target_start_algorithm(target, num_mem_params, mem_params,
849                         num_reg_params, reg_params,
850                         entry_point,
851                         exit_point,
852                         arch_info);
853
854         if (retval != ERROR_OK) {
855                 LOG_ERROR("error starting target flash write algorithm");
856                 return retval;
857         }
858
859         while (count > 0) {
860
861                 retval = target_read_u32(target, rp_addr, &rp);
862                 if (retval != ERROR_OK) {
863                         LOG_ERROR("failed to get read pointer");
864                         break;
865                 }
866
867                 LOG_DEBUG("count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32, count, wp, rp);
868
869                 if (rp == 0) {
870                         LOG_ERROR("flash write algorithm aborted by target");
871                         retval = ERROR_FLASH_OPERATION_FAILED;
872                         break;
873                 }
874
875                 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
876                         LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
877                         break;
878                 }
879
880                 /* Count the number of bytes available in the fifo without
881                  * crossing the wrap around. Make sure to not fill it completely,
882                  * because that would make wp == rp and that's the empty condition. */
883                 uint32_t thisrun_bytes;
884                 if (rp > wp)
885                         thisrun_bytes = rp - wp - block_size;
886                 else if (rp > fifo_start_addr)
887                         thisrun_bytes = fifo_end_addr - wp;
888                 else
889                         thisrun_bytes = fifo_end_addr - wp - block_size;
890
891                 if (thisrun_bytes == 0) {
892                         /* Throttle polling a bit if transfer is (much) faster than flash
893                          * programming. The exact delay shouldn't matter as long as it's
894                          * less than buffer size / flash speed. This is very unlikely to
895                          * run when using high latency connections such as USB. */
896                         alive_sleep(10);
897
898                         /* to stop an infinite loop on some targets check and increment a timeout
899                          * this issue was observed on a stellaris using the new ICDI interface */
900                         if (timeout++ >= 500) {
901                                 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
902                                 return ERROR_FLASH_OPERATION_FAILED;
903                         }
904                         continue;
905                 }
906
907                 /* reset our timeout */
908                 timeout = 0;
909
910                 /* Limit to the amount of data we actually want to write */
911                 if (thisrun_bytes > count * block_size)
912                         thisrun_bytes = count * block_size;
913
914                 /* Write data to fifo */
915                 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
916                 if (retval != ERROR_OK)
917                         break;
918
919                 /* Update counters and wrap write pointer */
920                 buffer += thisrun_bytes;
921                 count -= thisrun_bytes / block_size;
922                 wp += thisrun_bytes;
923                 if (wp >= fifo_end_addr)
924                         wp = fifo_start_addr;
925
926                 /* Store updated write pointer to target */
927                 retval = target_write_u32(target, wp_addr, wp);
928                 if (retval != ERROR_OK)
929                         break;
930         }
931
932         if (retval != ERROR_OK) {
933                 /* abort flash write algorithm on target */
934                 target_write_u32(target, wp_addr, 0);
935         }
936
937         int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
938                         num_reg_params, reg_params,
939                         exit_point,
940                         10000,
941                         arch_info);
942
943         if (retval2 != ERROR_OK) {
944                 LOG_ERROR("error waiting for target flash write algorithm");
945                 retval = retval2;
946         }
947
948         return retval;
949 }
950
951 int target_read_memory(struct target *target,
952                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
953 {
954         return target->type->read_memory(target, address, size, count, buffer);
955 }
956
957 static int target_read_phys_memory(struct target *target,
958                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
959 {
960         return target->type->read_phys_memory(target, address, size, count, buffer);
961 }
962
963 int target_write_memory(struct target *target,
964                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
965 {
966         return target->type->write_memory(target, address, size, count, buffer);
967 }
968
969 static int target_write_phys_memory(struct target *target,
970                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
971 {
972         return target->type->write_phys_memory(target, address, size, count, buffer);
973 }
974
975 int target_bulk_write_memory(struct target *target,
976                 uint32_t address, uint32_t count, const uint8_t *buffer)
977 {
978         return target->type->bulk_write_memory(target, address, count, buffer);
979 }
980
981 int target_add_breakpoint(struct target *target,
982                 struct breakpoint *breakpoint)
983 {
984         if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
985                 LOG_WARNING("target %s is not halted", target_name(target));
986                 return ERROR_TARGET_NOT_HALTED;
987         }
988         return target->type->add_breakpoint(target, breakpoint);
989 }
990
991 int target_add_context_breakpoint(struct target *target,
992                 struct breakpoint *breakpoint)
993 {
994         if (target->state != TARGET_HALTED) {
995                 LOG_WARNING("target %s is not halted", target_name(target));
996                 return ERROR_TARGET_NOT_HALTED;
997         }
998         return target->type->add_context_breakpoint(target, breakpoint);
999 }
1000
1001 int target_add_hybrid_breakpoint(struct target *target,
1002                 struct breakpoint *breakpoint)
1003 {
1004         if (target->state != TARGET_HALTED) {
1005                 LOG_WARNING("target %s is not halted", target_name(target));
1006                 return ERROR_TARGET_NOT_HALTED;
1007         }
1008         return target->type->add_hybrid_breakpoint(target, breakpoint);
1009 }
1010
1011 int target_remove_breakpoint(struct target *target,
1012                 struct breakpoint *breakpoint)
1013 {
1014         return target->type->remove_breakpoint(target, breakpoint);
1015 }
1016
1017 int target_add_watchpoint(struct target *target,
1018                 struct watchpoint *watchpoint)
1019 {
1020         if (target->state != TARGET_HALTED) {
1021                 LOG_WARNING("target %s is not halted", target_name(target));
1022                 return ERROR_TARGET_NOT_HALTED;
1023         }
1024         return target->type->add_watchpoint(target, watchpoint);
1025 }
1026 int target_remove_watchpoint(struct target *target,
1027                 struct watchpoint *watchpoint)
1028 {
1029         return target->type->remove_watchpoint(target, watchpoint);
1030 }
1031
1032 int target_get_gdb_reg_list(struct target *target,
1033                 struct reg **reg_list[], int *reg_list_size)
1034 {
1035         return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
1036 }
1037 int target_step(struct target *target,
1038                 int current, uint32_t address, int handle_breakpoints)
1039 {
1040         return target->type->step(target, current, address, handle_breakpoints);
1041 }
1042
1043 /**
1044  * Reset the @c examined flag for the given target.
1045  * Pure paranoia -- targets are zeroed on allocation.
1046  */
1047 static void target_reset_examined(struct target *target)
1048 {
1049         target->examined = false;
1050 }
1051
1052 static int err_read_phys_memory(struct target *target, uint32_t address,
1053                 uint32_t size, uint32_t count, uint8_t *buffer)
1054 {
1055         LOG_ERROR("Not implemented: %s", __func__);
1056         return ERROR_FAIL;
1057 }
1058
1059 static int err_write_phys_memory(struct target *target, uint32_t address,
1060                 uint32_t size, uint32_t count, const uint8_t *buffer)
1061 {
1062         LOG_ERROR("Not implemented: %s", __func__);
1063         return ERROR_FAIL;
1064 }
1065
1066 static int handle_target(void *priv);
1067
1068 static int target_init_one(struct command_context *cmd_ctx,
1069                 struct target *target)
1070 {
1071         target_reset_examined(target);
1072
1073         struct target_type *type = target->type;
1074         if (type->examine == NULL)
1075                 type->examine = default_examine;
1076
1077         if (type->check_reset == NULL)
1078                 type->check_reset = default_check_reset;
1079
1080         assert(type->init_target != NULL);
1081
1082         int retval = type->init_target(cmd_ctx, target);
1083         if (ERROR_OK != retval) {
1084                 LOG_ERROR("target '%s' init failed", target_name(target));
1085                 return retval;
1086         }
1087
1088         /**
1089          * @todo get rid of those *memory_imp() methods, now that all
1090          * callers are using target_*_memory() accessors ... and make
1091          * sure the "physical" paths handle the same issues.
1092          */
1093         /* a non-invasive way(in terms of patches) to add some code that
1094          * runs before the type->write/read_memory implementation
1095          */
1096         type->write_memory_imp = target->type->write_memory;
1097         type->write_memory = target_write_memory_imp;
1098
1099         type->read_memory_imp = target->type->read_memory;
1100         type->read_memory = target_read_memory_imp;
1101
1102         /* Sanity-check MMU support ... stub in what we must, to help
1103          * implement it in stages, but warn if we need to do so.
1104          */
1105         if (type->mmu) {
1106                 if (type->write_phys_memory == NULL) {
1107                         LOG_ERROR("type '%s' is missing write_phys_memory",
1108                                         type->name);
1109                         type->write_phys_memory = err_write_phys_memory;
1110                 }
1111                 if (type->read_phys_memory == NULL) {
1112                         LOG_ERROR("type '%s' is missing read_phys_memory",
1113                                         type->name);
1114                         type->read_phys_memory = err_read_phys_memory;
1115                 }
1116                 if (type->virt2phys == NULL) {
1117                         LOG_ERROR("type '%s' is missing virt2phys", type->name);
1118                         type->virt2phys = identity_virt2phys;
1119                 }
1120         } else {
1121                 /* Make sure no-MMU targets all behave the same:  make no
1122                  * distinction between physical and virtual addresses, and
1123                  * ensure that virt2phys() is always an identity mapping.
1124                  */
1125                 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1126                         LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1127
1128                 type->mmu = no_mmu;
1129                 type->write_phys_memory = type->write_memory;
1130                 type->read_phys_memory = type->read_memory;
1131                 type->virt2phys = identity_virt2phys;
1132         }
1133
1134         if (target->type->read_buffer == NULL)
1135                 target->type->read_buffer = target_read_buffer_default;
1136
1137         if (target->type->write_buffer == NULL)
1138                 target->type->write_buffer = target_write_buffer_default;
1139
1140         return ERROR_OK;
1141 }
1142
1143 static int target_init(struct command_context *cmd_ctx)
1144 {
1145         struct target *target;
1146         int retval;
1147
1148         for (target = all_targets; target; target = target->next) {
1149                 retval = target_init_one(cmd_ctx, target);
1150                 if (ERROR_OK != retval)
1151                         return retval;
1152         }
1153
1154         if (!all_targets)
1155                 return ERROR_OK;
1156
1157         retval = target_register_user_commands(cmd_ctx);
1158         if (ERROR_OK != retval)
1159                 return retval;
1160
1161         retval = target_register_timer_callback(&handle_target,
1162                         polling_interval, 1, cmd_ctx->interp);
1163         if (ERROR_OK != retval)
1164                 return retval;
1165
1166         return ERROR_OK;
1167 }
1168
1169 COMMAND_HANDLER(handle_target_init_command)
1170 {
1171         int retval;
1172
1173         if (CMD_ARGC != 0)
1174                 return ERROR_COMMAND_SYNTAX_ERROR;
1175
1176         static bool target_initialized;
1177         if (target_initialized) {
1178                 LOG_INFO("'target init' has already been called");
1179                 return ERROR_OK;
1180         }
1181         target_initialized = true;
1182
1183         retval = command_run_line(CMD_CTX, "init_targets");
1184         if (ERROR_OK != retval)
1185                 return retval;
1186
1187         retval = command_run_line(CMD_CTX, "init_board");
1188         if (ERROR_OK != retval)
1189                 return retval;
1190
1191         LOG_DEBUG("Initializing targets...");
1192         return target_init(CMD_CTX);
1193 }
1194
1195 int target_register_event_callback(int (*callback)(struct target *target,
1196                 enum target_event event, void *priv), void *priv)
1197 {
1198         struct target_event_callback **callbacks_p = &target_event_callbacks;
1199
1200         if (callback == NULL)
1201                 return ERROR_COMMAND_SYNTAX_ERROR;
1202
1203         if (*callbacks_p) {
1204                 while ((*callbacks_p)->next)
1205                         callbacks_p = &((*callbacks_p)->next);
1206                 callbacks_p = &((*callbacks_p)->next);
1207         }
1208
1209         (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1210         (*callbacks_p)->callback = callback;
1211         (*callbacks_p)->priv = priv;
1212         (*callbacks_p)->next = NULL;
1213
1214         return ERROR_OK;
1215 }
1216
1217 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1218 {
1219         struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1220         struct timeval now;
1221
1222         if (callback == NULL)
1223                 return ERROR_COMMAND_SYNTAX_ERROR;
1224
1225         if (*callbacks_p) {
1226                 while ((*callbacks_p)->next)
1227                         callbacks_p = &((*callbacks_p)->next);
1228                 callbacks_p = &((*callbacks_p)->next);
1229         }
1230
1231         (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1232         (*callbacks_p)->callback = callback;
1233         (*callbacks_p)->periodic = periodic;
1234         (*callbacks_p)->time_ms = time_ms;
1235
1236         gettimeofday(&now, NULL);
1237         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1238         time_ms -= (time_ms % 1000);
1239         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1240         if ((*callbacks_p)->when.tv_usec > 1000000) {
1241                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1242                 (*callbacks_p)->when.tv_sec += 1;
1243         }
1244
1245         (*callbacks_p)->priv = priv;
1246         (*callbacks_p)->next = NULL;
1247
1248         return ERROR_OK;
1249 }
1250
1251 int target_unregister_event_callback(int (*callback)(struct target *target,
1252                 enum target_event event, void *priv), void *priv)
1253 {
1254         struct target_event_callback **p = &target_event_callbacks;
1255         struct target_event_callback *c = target_event_callbacks;
1256
1257         if (callback == NULL)
1258                 return ERROR_COMMAND_SYNTAX_ERROR;
1259
1260         while (c) {
1261                 struct target_event_callback *next = c->next;
1262                 if ((c->callback == callback) && (c->priv == priv)) {
1263                         *p = next;
1264                         free(c);
1265                         return ERROR_OK;
1266                 } else
1267                         p = &(c->next);
1268                 c = next;
1269         }
1270
1271         return ERROR_OK;
1272 }
1273
1274 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1275 {
1276         struct target_timer_callback **p = &target_timer_callbacks;
1277         struct target_timer_callback *c = target_timer_callbacks;
1278
1279         if (callback == NULL)
1280                 return ERROR_COMMAND_SYNTAX_ERROR;
1281
1282         while (c) {
1283                 struct target_timer_callback *next = c->next;
1284                 if ((c->callback == callback) && (c->priv == priv)) {
1285                         *p = next;
1286                         free(c);
1287                         return ERROR_OK;
1288                 } else
1289                         p = &(c->next);
1290                 c = next;
1291         }
1292
1293         return ERROR_OK;
1294 }
1295
1296 int target_call_event_callbacks(struct target *target, enum target_event event)
1297 {
1298         struct target_event_callback *callback = target_event_callbacks;
1299         struct target_event_callback *next_callback;
1300
1301         if (event == TARGET_EVENT_HALTED) {
1302                 /* execute early halted first */
1303                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1304         }
1305
1306         LOG_DEBUG("target event %i (%s)", event,
1307                         Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1308
1309         target_handle_event(target, event);
1310
1311         while (callback) {
1312                 next_callback = callback->next;
1313                 callback->callback(target, event, callback->priv);
1314                 callback = next_callback;
1315         }
1316
1317         return ERROR_OK;
1318 }
1319
1320 static int target_timer_callback_periodic_restart(
1321                 struct target_timer_callback *cb, struct timeval *now)
1322 {
1323         int time_ms = cb->time_ms;
1324         cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1325         time_ms -= (time_ms % 1000);
1326         cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1327         if (cb->when.tv_usec > 1000000) {
1328                 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1329                 cb->when.tv_sec += 1;
1330         }
1331         return ERROR_OK;
1332 }
1333
1334 static int target_call_timer_callback(struct target_timer_callback *cb,
1335                 struct timeval *now)
1336 {
1337         cb->callback(cb->priv);
1338
1339         if (cb->periodic)
1340                 return target_timer_callback_periodic_restart(cb, now);
1341
1342         return target_unregister_timer_callback(cb->callback, cb->priv);
1343 }
1344
1345 static int target_call_timer_callbacks_check_time(int checktime)
1346 {
1347         keep_alive();
1348
1349         struct timeval now;
1350         gettimeofday(&now, NULL);
1351
1352         struct target_timer_callback *callback = target_timer_callbacks;
1353         while (callback) {
1354                 /* cleaning up may unregister and free this callback */
1355                 struct target_timer_callback *next_callback = callback->next;
1356
1357                 bool call_it = callback->callback &&
1358                         ((!checktime && callback->periodic) ||
1359                           now.tv_sec > callback->when.tv_sec ||
1360                          (now.tv_sec == callback->when.tv_sec &&
1361                           now.tv_usec >= callback->when.tv_usec));
1362
1363                 if (call_it) {
1364                         int retval = target_call_timer_callback(callback, &now);
1365                         if (retval != ERROR_OK)
1366                                 return retval;
1367                 }
1368
1369                 callback = next_callback;
1370         }
1371
1372         return ERROR_OK;
1373 }
1374
1375 int target_call_timer_callbacks(void)
1376 {
1377         return target_call_timer_callbacks_check_time(1);
1378 }
1379
1380 /* invoke periodic callbacks immediately */
1381 int target_call_timer_callbacks_now(void)
1382 {
1383         return target_call_timer_callbacks_check_time(0);
1384 }
1385
1386 /* Prints the working area layout for debug purposes */
1387 static void print_wa_layout(struct target *target)
1388 {
1389         struct working_area *c = target->working_areas;
1390
1391         while (c) {
1392                 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1393                         c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1394                         c->address, c->address + c->size - 1, c->size);
1395                 c = c->next;
1396         }
1397 }
1398
1399 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1400 static void target_split_working_area(struct working_area *area, uint32_t size)
1401 {
1402         assert(area->free); /* Shouldn't split an allocated area */
1403         assert(size <= area->size); /* Caller should guarantee this */
1404
1405         /* Split only if not already the right size */
1406         if (size < area->size) {
1407                 struct working_area *new_wa = malloc(sizeof(*new_wa));
1408
1409                 if (new_wa == NULL)
1410                         return;
1411
1412                 new_wa->next = area->next;
1413                 new_wa->size = area->size - size;
1414                 new_wa->address = area->address + size;
1415                 new_wa->backup = NULL;
1416                 new_wa->user = NULL;
1417                 new_wa->free = true;
1418
1419                 area->next = new_wa;
1420                 area->size = size;
1421
1422                 /* If backup memory was allocated to this area, it has the wrong size
1423                  * now so free it and it will be reallocated if/when needed */
1424                 if (area->backup) {
1425                         free(area->backup);
1426                         area->backup = NULL;
1427                 }
1428         }
1429 }
1430
1431 /* Merge all adjacent free areas into one */
1432 static void target_merge_working_areas(struct target *target)
1433 {
1434         struct working_area *c = target->working_areas;
1435
1436         while (c && c->next) {
1437                 assert(c->next->address == c->address + c->size); /* This is an invariant */
1438
1439                 /* Find two adjacent free areas */
1440                 if (c->free && c->next->free) {
1441                         /* Merge the last into the first */
1442                         c->size += c->next->size;
1443
1444                         /* Remove the last */
1445                         struct working_area *to_be_freed = c->next;
1446                         c->next = c->next->next;
1447                         if (to_be_freed->backup)
1448                                 free(to_be_freed->backup);
1449                         free(to_be_freed);
1450
1451                         /* If backup memory was allocated to the remaining area, it's has
1452                          * the wrong size now */
1453                         if (c->backup) {
1454                                 free(c->backup);
1455                                 c->backup = NULL;
1456                         }
1457                 } else {
1458                         c = c->next;
1459                 }
1460         }
1461 }
1462
1463 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1464 {
1465         /* Reevaluate working area address based on MMU state*/
1466         if (target->working_areas == NULL) {
1467                 int retval;
1468                 int enabled;
1469
1470                 retval = target->type->mmu(target, &enabled);
1471                 if (retval != ERROR_OK)
1472                         return retval;
1473
1474                 if (!enabled) {
1475                         if (target->working_area_phys_spec) {
1476                                 LOG_DEBUG("MMU disabled, using physical "
1477                                         "address for working memory 0x%08"PRIx32,
1478                                         target->working_area_phys);
1479                                 target->working_area = target->working_area_phys;
1480                         } else {
1481                                 LOG_ERROR("No working memory available. "
1482                                         "Specify -work-area-phys to target.");
1483                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1484                         }
1485                 } else {
1486                         if (target->working_area_virt_spec) {
1487                                 LOG_DEBUG("MMU enabled, using virtual "
1488                                         "address for working memory 0x%08"PRIx32,
1489                                         target->working_area_virt);
1490                                 target->working_area = target->working_area_virt;
1491                         } else {
1492                                 LOG_ERROR("No working memory available. "
1493                                         "Specify -work-area-virt to target.");
1494                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1495                         }
1496                 }
1497
1498                 /* Set up initial working area on first call */
1499                 struct working_area *new_wa = malloc(sizeof(*new_wa));
1500                 if (new_wa) {
1501                         new_wa->next = NULL;
1502                         new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1503                         new_wa->address = target->working_area;
1504                         new_wa->backup = NULL;
1505                         new_wa->user = NULL;
1506                         new_wa->free = true;
1507                 }
1508
1509                 target->working_areas = new_wa;
1510         }
1511
1512         /* only allocate multiples of 4 byte */
1513         if (size % 4)
1514                 size = (size + 3) & (~3UL);
1515
1516         struct working_area *c = target->working_areas;
1517
1518         /* Find the first large enough working area */
1519         while (c) {
1520                 if (c->free && c->size >= size)
1521                         break;
1522                 c = c->next;
1523         }
1524
1525         if (c == NULL)
1526                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1527
1528         /* Split the working area into the requested size */
1529         target_split_working_area(c, size);
1530
1531         LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1532
1533         if (target->backup_working_area) {
1534                 if (c->backup == NULL) {
1535                         c->backup = malloc(c->size);
1536                         if (c->backup == NULL)
1537                                 return ERROR_FAIL;
1538                 }
1539
1540                 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1541                 if (retval != ERROR_OK)
1542                         return retval;
1543         }
1544
1545         /* mark as used, and return the new (reused) area */
1546         c->free = false;
1547         *area = c;
1548
1549         /* user pointer */
1550         c->user = area;
1551
1552         print_wa_layout(target);
1553
1554         return ERROR_OK;
1555 }
1556
1557 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1558 {
1559         int retval;
1560
1561         retval = target_alloc_working_area_try(target, size, area);
1562         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1563                 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1564         return retval;
1565
1566 }
1567
1568 static int target_restore_working_area(struct target *target, struct working_area *area)
1569 {
1570         int retval = ERROR_OK;
1571
1572         if (target->backup_working_area && area->backup != NULL) {
1573                 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1574                 if (retval != ERROR_OK)
1575                         LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1576                                         area->size, area->address);
1577         }
1578
1579         return retval;
1580 }
1581
1582 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1583 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1584 {
1585         int retval = ERROR_OK;
1586
1587         if (area->free)
1588                 return retval;
1589
1590         if (restore) {
1591                 retval = target_restore_working_area(target, area);
1592                 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1593                 if (retval != ERROR_OK)
1594                         return retval;
1595         }
1596
1597         area->free = true;
1598
1599         LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1600                         area->size, area->address);
1601
1602         /* mark user pointer invalid */
1603         /* TODO: Is this really safe? It points to some previous caller's memory.
1604          * How could we know that the area pointer is still in that place and not
1605          * some other vital data? What's the purpose of this, anyway? */
1606         *area->user = NULL;
1607         area->user = NULL;
1608
1609         target_merge_working_areas(target);
1610
1611         print_wa_layout(target);
1612
1613         return retval;
1614 }
1615
1616 int target_free_working_area(struct target *target, struct working_area *area)
1617 {
1618         return target_free_working_area_restore(target, area, 1);
1619 }
1620
1621 /* free resources and restore memory, if restoring memory fails,
1622  * free up resources anyway
1623  */
1624 static void target_free_all_working_areas_restore(struct target *target, int restore)
1625 {
1626         struct working_area *c = target->working_areas;
1627
1628         LOG_DEBUG("freeing all working areas");
1629
1630         /* Loop through all areas, restoring the allocated ones and marking them as free */
1631         while (c) {
1632                 if (!c->free) {
1633                         if (restore)
1634                                 target_restore_working_area(target, c);
1635                         c->free = true;
1636                         *c->user = NULL; /* Same as above */
1637                         c->user = NULL;
1638                 }
1639                 c = c->next;
1640         }
1641
1642         /* Run a merge pass to combine all areas into one */
1643         target_merge_working_areas(target);
1644
1645         print_wa_layout(target);
1646 }
1647
1648 void target_free_all_working_areas(struct target *target)
1649 {
1650         target_free_all_working_areas_restore(target, 1);
1651 }
1652
1653 /* Find the largest number of bytes that can be allocated */
1654 uint32_t target_get_working_area_avail(struct target *target)
1655 {
1656         struct working_area *c = target->working_areas;
1657         uint32_t max_size = 0;
1658
1659         if (c == NULL)
1660                 return target->working_area_size;
1661
1662         while (c) {
1663                 if (c->free && max_size < c->size)
1664                         max_size = c->size;
1665
1666                 c = c->next;
1667         }
1668
1669         return max_size;
1670 }
1671
1672 int target_arch_state(struct target *target)
1673 {
1674         int retval;
1675         if (target == NULL) {
1676                 LOG_USER("No target has been configured");
1677                 return ERROR_OK;
1678         }
1679
1680         LOG_USER("target state: %s", target_state_name(target));
1681
1682         if (target->state != TARGET_HALTED)
1683                 return ERROR_OK;
1684
1685         retval = target->type->arch_state(target);
1686         return retval;
1687 }
1688
1689 /* Single aligned words are guaranteed to use 16 or 32 bit access
1690  * mode respectively, otherwise data is handled as quickly as
1691  * possible
1692  */
1693 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1694 {
1695         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1696                         (int)size, (unsigned)address);
1697
1698         if (!target_was_examined(target)) {
1699                 LOG_ERROR("Target not examined yet");
1700                 return ERROR_FAIL;
1701         }
1702
1703         if (size == 0)
1704                 return ERROR_OK;
1705
1706         if ((address + size - 1) < address) {
1707                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1708                 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1709                                   (unsigned)address,
1710                                   (unsigned)size);
1711                 return ERROR_FAIL;
1712         }
1713
1714         return target->type->write_buffer(target, address, size, buffer);
1715 }
1716
1717 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1718 {
1719         int retval = ERROR_OK;
1720
1721         if (((address % 2) == 0) && (size == 2))
1722                 return target_write_memory(target, address, 2, 1, buffer);
1723
1724         /* handle unaligned head bytes */
1725         if (address % 4) {
1726                 uint32_t unaligned = 4 - (address % 4);
1727
1728                 if (unaligned > size)
1729                         unaligned = size;
1730
1731                 retval = target_write_memory(target, address, 1, unaligned, buffer);
1732                 if (retval != ERROR_OK)
1733                         return retval;
1734
1735                 buffer += unaligned;
1736                 address += unaligned;
1737                 size -= unaligned;
1738         }
1739
1740         /* handle aligned words */
1741         if (size >= 4) {
1742                 int aligned = size - (size % 4);
1743
1744                 /* use bulk writes above a certain limit. This may have to be changed */
1745                 if (aligned > 128) {
1746                         retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer);
1747                         if (retval != ERROR_OK)
1748                                 return retval;
1749                 } else {
1750                         retval = target_write_memory(target, address, 4, aligned / 4, buffer);
1751                         if (retval != ERROR_OK)
1752                                 return retval;
1753                 }
1754
1755                 buffer += aligned;
1756                 address += aligned;
1757                 size -= aligned;
1758         }
1759
1760         /* handle tail writes of less than 4 bytes */
1761         if (size > 0) {
1762                 retval = target_write_memory(target, address, 1, size, buffer);
1763                 if (retval != ERROR_OK)
1764                         return retval;
1765         }
1766
1767         return retval;
1768 }
1769
1770 /* Single aligned words are guaranteed to use 16 or 32 bit access
1771  * mode respectively, otherwise data is handled as quickly as
1772  * possible
1773  */
1774 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1775 {
1776         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1777                           (int)size, (unsigned)address);
1778
1779         if (!target_was_examined(target)) {
1780                 LOG_ERROR("Target not examined yet");
1781                 return ERROR_FAIL;
1782         }
1783
1784         if (size == 0)
1785                 return ERROR_OK;
1786
1787         if ((address + size - 1) < address) {
1788                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1789                 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1790                                   address,
1791                                   size);
1792                 return ERROR_FAIL;
1793         }
1794
1795         return target->type->read_buffer(target, address, size, buffer);
1796 }
1797
1798 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1799 {
1800         int retval = ERROR_OK;
1801
1802         if (((address % 2) == 0) && (size == 2))
1803                 return target_read_memory(target, address, 2, 1, buffer);
1804
1805         /* handle unaligned head bytes */
1806         if (address % 4) {
1807                 uint32_t unaligned = 4 - (address % 4);
1808
1809                 if (unaligned > size)
1810                         unaligned = size;
1811
1812                 retval = target_read_memory(target, address, 1, unaligned, buffer);
1813                 if (retval != ERROR_OK)
1814                         return retval;
1815
1816                 buffer += unaligned;
1817                 address += unaligned;
1818                 size -= unaligned;
1819         }
1820
1821         /* handle aligned words */
1822         if (size >= 4) {
1823                 int aligned = size - (size % 4);
1824
1825                 retval = target_read_memory(target, address, 4, aligned / 4, buffer);
1826                 if (retval != ERROR_OK)
1827                         return retval;
1828
1829                 buffer += aligned;
1830                 address += aligned;
1831                 size -= aligned;
1832         }
1833
1834         /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1835         if (size        >= 2) {
1836                 int aligned = size - (size % 2);
1837                 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1838                 if (retval != ERROR_OK)
1839                         return retval;
1840
1841                 buffer += aligned;
1842                 address += aligned;
1843                 size -= aligned;
1844         }
1845         /* handle tail writes of less than 4 bytes */
1846         if (size > 0) {
1847                 retval = target_read_memory(target, address, 1, size, buffer);
1848                 if (retval != ERROR_OK)
1849                         return retval;
1850         }
1851
1852         return ERROR_OK;
1853 }
1854
1855 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1856 {
1857         uint8_t *buffer;
1858         int retval;
1859         uint32_t i;
1860         uint32_t checksum = 0;
1861         if (!target_was_examined(target)) {
1862                 LOG_ERROR("Target not examined yet");
1863                 return ERROR_FAIL;
1864         }
1865
1866         retval = target->type->checksum_memory(target, address, size, &checksum);
1867         if (retval != ERROR_OK) {
1868                 buffer = malloc(size);
1869                 if (buffer == NULL) {
1870                         LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1871                         return ERROR_COMMAND_SYNTAX_ERROR;
1872                 }
1873                 retval = target_read_buffer(target, address, size, buffer);
1874                 if (retval != ERROR_OK) {
1875                         free(buffer);
1876                         return retval;
1877                 }
1878
1879                 /* convert to target endianness */
1880                 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
1881                         uint32_t target_data;
1882                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1883                         target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1884                 }
1885
1886                 retval = image_calculate_checksum(buffer, size, &checksum);
1887                 free(buffer);
1888         }
1889
1890         *crc = checksum;
1891
1892         return retval;
1893 }
1894
1895 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1896 {
1897         int retval;
1898         if (!target_was_examined(target)) {
1899                 LOG_ERROR("Target not examined yet");
1900                 return ERROR_FAIL;
1901         }
1902
1903         if (target->type->blank_check_memory == 0)
1904                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1905
1906         retval = target->type->blank_check_memory(target, address, size, blank);
1907
1908         return retval;
1909 }
1910
1911 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1912 {
1913         uint8_t value_buf[4];
1914         if (!target_was_examined(target)) {
1915                 LOG_ERROR("Target not examined yet");
1916                 return ERROR_FAIL;
1917         }
1918
1919         int retval = target_read_memory(target, address, 4, 1, value_buf);
1920
1921         if (retval == ERROR_OK) {
1922                 *value = target_buffer_get_u32(target, value_buf);
1923                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1924                                   address,
1925                                   *value);
1926         } else {
1927                 *value = 0x0;
1928                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1929                                   address);
1930         }
1931
1932         return retval;
1933 }
1934
1935 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1936 {
1937         uint8_t value_buf[2];
1938         if (!target_was_examined(target)) {
1939                 LOG_ERROR("Target not examined yet");
1940                 return ERROR_FAIL;
1941         }
1942
1943         int retval = target_read_memory(target, address, 2, 1, value_buf);
1944
1945         if (retval == ERROR_OK) {
1946                 *value = target_buffer_get_u16(target, value_buf);
1947                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1948                                   address,
1949                                   *value);
1950         } else {
1951                 *value = 0x0;
1952                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1953                                   address);
1954         }
1955
1956         return retval;
1957 }
1958
1959 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1960 {
1961         int retval = target_read_memory(target, address, 1, 1, value);
1962         if (!target_was_examined(target)) {
1963                 LOG_ERROR("Target not examined yet");
1964                 return ERROR_FAIL;
1965         }
1966
1967         if (retval == ERROR_OK) {
1968                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1969                                   address,
1970                                   *value);
1971         } else {
1972                 *value = 0x0;
1973                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1974                                   address);
1975         }
1976
1977         return retval;
1978 }
1979
1980 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1981 {
1982         int retval;
1983         uint8_t value_buf[4];
1984         if (!target_was_examined(target)) {
1985                 LOG_ERROR("Target not examined yet");
1986                 return ERROR_FAIL;
1987         }
1988
1989         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1990                           address,
1991                           value);
1992
1993         target_buffer_set_u32(target, value_buf, value);
1994         retval = target_write_memory(target, address, 4, 1, value_buf);
1995         if (retval != ERROR_OK)
1996                 LOG_DEBUG("failed: %i", retval);
1997
1998         return retval;
1999 }
2000
2001 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2002 {
2003         int retval;
2004         uint8_t value_buf[2];
2005         if (!target_was_examined(target)) {
2006                 LOG_ERROR("Target not examined yet");
2007                 return ERROR_FAIL;
2008         }
2009
2010         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2011                           address,
2012                           value);
2013
2014         target_buffer_set_u16(target, value_buf, value);
2015         retval = target_write_memory(target, address, 2, 1, value_buf);
2016         if (retval != ERROR_OK)
2017                 LOG_DEBUG("failed: %i", retval);
2018
2019         return retval;
2020 }
2021
2022 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2023 {
2024         int retval;
2025         if (!target_was_examined(target)) {
2026                 LOG_ERROR("Target not examined yet");
2027                 return ERROR_FAIL;
2028         }
2029
2030         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2031                           address, value);
2032
2033         retval = target_write_memory(target, address, 1, 1, &value);
2034         if (retval != ERROR_OK)
2035                 LOG_DEBUG("failed: %i", retval);
2036
2037         return retval;
2038 }
2039
2040 static int find_target(struct command_context *cmd_ctx, const char *name)
2041 {
2042         struct target *target = get_target(name);
2043         if (target == NULL) {
2044                 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2045                 return ERROR_FAIL;
2046         }
2047         if (!target->tap->enabled) {
2048                 LOG_USER("Target: TAP %s is disabled, "
2049                          "can't be the current target\n",
2050                          target->tap->dotted_name);
2051                 return ERROR_FAIL;
2052         }
2053
2054         cmd_ctx->current_target = target->target_number;
2055         return ERROR_OK;
2056 }
2057
2058
2059 COMMAND_HANDLER(handle_targets_command)
2060 {
2061         int retval = ERROR_OK;
2062         if (CMD_ARGC == 1) {
2063                 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2064                 if (retval == ERROR_OK) {
2065                         /* we're done! */
2066                         return retval;
2067                 }
2068         }
2069
2070         struct target *target = all_targets;
2071         command_print(CMD_CTX, "    TargetName         Type       Endian TapName            State       ");
2072         command_print(CMD_CTX, "--  ------------------ ---------- ------ ------------------ ------------");
2073         while (target) {
2074                 const char *state;
2075                 char marker = ' ';
2076
2077                 if (target->tap->enabled)
2078                         state = target_state_name(target);
2079                 else
2080                         state = "tap-disabled";
2081
2082                 if (CMD_CTX->current_target == target->target_number)
2083                         marker = '*';
2084
2085                 /* keep columns lined up to match the headers above */
2086                 command_print(CMD_CTX,
2087                                 "%2d%c %-18s %-10s %-6s %-18s %s",
2088                                 target->target_number,
2089                                 marker,
2090                                 target_name(target),
2091                                 target_type_name(target),
2092                                 Jim_Nvp_value2name_simple(nvp_target_endian,
2093                                         target->endianness)->name,
2094                                 target->tap->dotted_name,
2095                                 state);
2096                 target = target->next;
2097         }
2098
2099         return retval;
2100 }
2101
2102 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2103
2104 static int powerDropout;
2105 static int srstAsserted;
2106
2107 static int runPowerRestore;
2108 static int runPowerDropout;
2109 static int runSrstAsserted;
2110 static int runSrstDeasserted;
2111
2112 static int sense_handler(void)
2113 {
2114         static int prevSrstAsserted;
2115         static int prevPowerdropout;
2116
2117         int retval = jtag_power_dropout(&powerDropout);
2118         if (retval != ERROR_OK)
2119                 return retval;
2120
2121         int powerRestored;
2122         powerRestored = prevPowerdropout && !powerDropout;
2123         if (powerRestored)
2124                 runPowerRestore = 1;
2125
2126         long long current = timeval_ms();
2127         static long long lastPower;
2128         int waitMore = lastPower + 2000 > current;
2129         if (powerDropout && !waitMore) {
2130                 runPowerDropout = 1;
2131                 lastPower = current;
2132         }
2133
2134         retval = jtag_srst_asserted(&srstAsserted);
2135         if (retval != ERROR_OK)
2136                 return retval;
2137
2138         int srstDeasserted;
2139         srstDeasserted = prevSrstAsserted && !srstAsserted;
2140
2141         static long long lastSrst;
2142         waitMore = lastSrst + 2000 > current;
2143         if (srstDeasserted && !waitMore) {
2144                 runSrstDeasserted = 1;
2145                 lastSrst = current;
2146         }
2147
2148         if (!prevSrstAsserted && srstAsserted)
2149                 runSrstAsserted = 1;
2150
2151         prevSrstAsserted = srstAsserted;
2152         prevPowerdropout = powerDropout;
2153
2154         if (srstDeasserted || powerRestored) {
2155                 /* Other than logging the event we can't do anything here.
2156                  * Issuing a reset is a particularly bad idea as we might
2157                  * be inside a reset already.
2158                  */
2159         }
2160
2161         return ERROR_OK;
2162 }
2163
2164 /* process target state changes */
2165 static int handle_target(void *priv)
2166 {
2167         Jim_Interp *interp = (Jim_Interp *)priv;
2168         int retval = ERROR_OK;
2169
2170         if (!is_jtag_poll_safe()) {
2171                 /* polling is disabled currently */
2172                 return ERROR_OK;
2173         }
2174
2175         /* we do not want to recurse here... */
2176         static int recursive;
2177         if (!recursive) {
2178                 recursive = 1;
2179                 sense_handler();
2180                 /* danger! running these procedures can trigger srst assertions and power dropouts.
2181                  * We need to avoid an infinite loop/recursion here and we do that by
2182                  * clearing the flags after running these events.
2183                  */
2184                 int did_something = 0;
2185                 if (runSrstAsserted) {
2186                         LOG_INFO("srst asserted detected, running srst_asserted proc.");
2187                         Jim_Eval(interp, "srst_asserted");
2188                         did_something = 1;
2189                 }
2190                 if (runSrstDeasserted) {
2191                         Jim_Eval(interp, "srst_deasserted");
2192                         did_something = 1;
2193                 }
2194                 if (runPowerDropout) {
2195                         LOG_INFO("Power dropout detected, running power_dropout proc.");
2196                         Jim_Eval(interp, "power_dropout");
2197                         did_something = 1;
2198                 }
2199                 if (runPowerRestore) {
2200                         Jim_Eval(interp, "power_restore");
2201                         did_something = 1;
2202                 }
2203
2204                 if (did_something) {
2205                         /* clear detect flags */
2206                         sense_handler();
2207                 }
2208
2209                 /* clear action flags */
2210
2211                 runSrstAsserted = 0;
2212                 runSrstDeasserted = 0;
2213                 runPowerRestore = 0;
2214                 runPowerDropout = 0;
2215
2216                 recursive = 0;
2217         }
2218
2219         /* Poll targets for state changes unless that's globally disabled.
2220          * Skip targets that are currently disabled.
2221          */
2222         for (struct target *target = all_targets;
2223                         is_jtag_poll_safe() && target;
2224                         target = target->next) {
2225                 if (!target->tap->enabled)
2226                         continue;
2227
2228                 if (target->backoff.times > target->backoff.count) {
2229                         /* do not poll this time as we failed previously */
2230                         target->backoff.count++;
2231                         continue;
2232                 }
2233                 target->backoff.count = 0;
2234
2235                 /* only poll target if we've got power and srst isn't asserted */
2236                 if (!powerDropout && !srstAsserted) {
2237                         /* polling may fail silently until the target has been examined */
2238                         retval = target_poll(target);
2239                         if (retval != ERROR_OK) {
2240                                 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2241                                 if (target->backoff.times * polling_interval < 5000) {
2242                                         target->backoff.times *= 2;
2243                                         target->backoff.times++;
2244                                 }
2245                                 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2246                                                 target_name(target),
2247                                                 target->backoff.times * polling_interval);
2248
2249                                 /* Tell GDB to halt the debugger. This allows the user to
2250                                  * run monitor commands to handle the situation.
2251                                  */
2252                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2253                                 return retval;
2254                         }
2255                         /* Since we succeeded, we reset backoff count */
2256                         if (target->backoff.times > 0)
2257                                 LOG_USER("Polling target %s succeeded again", target_name(target));
2258                         target->backoff.times = 0;
2259                 }
2260         }
2261
2262         return retval;
2263 }
2264
2265 COMMAND_HANDLER(handle_reg_command)
2266 {
2267         struct target *target;
2268         struct reg *reg = NULL;
2269         unsigned count = 0;
2270         char *value;
2271
2272         LOG_DEBUG("-");
2273
2274         target = get_current_target(CMD_CTX);
2275
2276         /* list all available registers for the current target */
2277         if (CMD_ARGC == 0) {
2278                 struct reg_cache *cache = target->reg_cache;
2279
2280                 count = 0;
2281                 while (cache) {
2282                         unsigned i;
2283
2284                         command_print(CMD_CTX, "===== %s", cache->name);
2285
2286                         for (i = 0, reg = cache->reg_list;
2287                                         i < cache->num_regs;
2288                                         i++, reg++, count++) {
2289                                 /* only print cached values if they are valid */
2290                                 if (reg->valid) {
2291                                         value = buf_to_str(reg->value,
2292                                                         reg->size, 16);
2293                                         command_print(CMD_CTX,
2294                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
2295                                                         count, reg->name,
2296                                                         reg->size, value,
2297                                                         reg->dirty
2298                                                                 ? " (dirty)"
2299                                                                 : "");
2300                                         free(value);
2301                                 } else {
2302                                         command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2303                                                           count, reg->name,
2304                                                           reg->size) ;
2305                                 }
2306                         }
2307                         cache = cache->next;
2308                 }
2309
2310                 return ERROR_OK;
2311         }
2312
2313         /* access a single register by its ordinal number */
2314         if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2315                 unsigned num;
2316                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2317
2318                 struct reg_cache *cache = target->reg_cache;
2319                 count = 0;
2320                 while (cache) {
2321                         unsigned i;
2322                         for (i = 0; i < cache->num_regs; i++) {
2323                                 if (count++ == num) {
2324                                         reg = &cache->reg_list[i];
2325                                         break;
2326                                 }
2327                         }
2328                         if (reg)
2329                                 break;
2330                         cache = cache->next;
2331                 }
2332
2333                 if (!reg) {
2334                         command_print(CMD_CTX, "%i is out of bounds, the current target "
2335                                         "has only %i registers (0 - %i)", num, count, count - 1);
2336                         return ERROR_OK;
2337                 }
2338         } else {
2339                 /* access a single register by its name */
2340                 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2341
2342                 if (!reg) {
2343                         command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2344                         return ERROR_OK;
2345                 }
2346         }
2347
2348         assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2349
2350         /* display a register */
2351         if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2352                         && (CMD_ARGV[1][0] <= '9')))) {
2353                 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2354                         reg->valid = 0;
2355
2356                 if (reg->valid == 0)
2357                         reg->type->get(reg);
2358                 value = buf_to_str(reg->value, reg->size, 16);
2359                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2360                 free(value);
2361                 return ERROR_OK;
2362         }
2363
2364         /* set register value */
2365         if (CMD_ARGC == 2) {
2366                 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2367                 if (buf == NULL)
2368                         return ERROR_FAIL;
2369                 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2370
2371                 reg->type->set(reg, buf);
2372
2373                 value = buf_to_str(reg->value, reg->size, 16);
2374                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2375                 free(value);
2376
2377                 free(buf);
2378
2379                 return ERROR_OK;
2380         }
2381
2382         return ERROR_COMMAND_SYNTAX_ERROR;
2383 }
2384
2385 COMMAND_HANDLER(handle_poll_command)
2386 {
2387         int retval = ERROR_OK;
2388         struct target *target = get_current_target(CMD_CTX);
2389
2390         if (CMD_ARGC == 0) {
2391                 command_print(CMD_CTX, "background polling: %s",
2392                                 jtag_poll_get_enabled() ? "on" : "off");
2393                 command_print(CMD_CTX, "TAP: %s (%s)",
2394                                 target->tap->dotted_name,
2395                                 target->tap->enabled ? "enabled" : "disabled");
2396                 if (!target->tap->enabled)
2397                         return ERROR_OK;
2398                 retval = target_poll(target);
2399                 if (retval != ERROR_OK)
2400                         return retval;
2401                 retval = target_arch_state(target);
2402                 if (retval != ERROR_OK)
2403                         return retval;
2404         } else if (CMD_ARGC == 1) {
2405                 bool enable;
2406                 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2407                 jtag_poll_set_enabled(enable);
2408         } else
2409                 return ERROR_COMMAND_SYNTAX_ERROR;
2410
2411         return retval;
2412 }
2413
2414 COMMAND_HANDLER(handle_wait_halt_command)
2415 {
2416         if (CMD_ARGC > 1)
2417                 return ERROR_COMMAND_SYNTAX_ERROR;
2418
2419         unsigned ms = 5000;
2420         if (1 == CMD_ARGC) {
2421                 int retval = parse_uint(CMD_ARGV[0], &ms);
2422                 if (ERROR_OK != retval)
2423                         return ERROR_COMMAND_SYNTAX_ERROR;
2424                 /* convert seconds (given) to milliseconds (needed) */
2425                 ms *= 1000;
2426         }
2427
2428         struct target *target = get_current_target(CMD_CTX);
2429         return target_wait_state(target, TARGET_HALTED, ms);
2430 }
2431
2432 /* wait for target state to change. The trick here is to have a low
2433  * latency for short waits and not to suck up all the CPU time
2434  * on longer waits.
2435  *
2436  * After 500ms, keep_alive() is invoked
2437  */
2438 int target_wait_state(struct target *target, enum target_state state, int ms)
2439 {
2440         int retval;
2441         long long then = 0, cur;
2442         int once = 1;
2443
2444         for (;;) {
2445                 retval = target_poll(target);
2446                 if (retval != ERROR_OK)
2447                         return retval;
2448                 if (target->state == state)
2449                         break;
2450                 cur = timeval_ms();
2451                 if (once) {
2452                         once = 0;
2453                         then = timeval_ms();
2454                         LOG_DEBUG("waiting for target %s...",
2455                                 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2456                 }
2457
2458                 if (cur-then > 500)
2459                         keep_alive();
2460
2461                 if ((cur-then) > ms) {
2462                         LOG_ERROR("timed out while waiting for target %s",
2463                                 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2464                         return ERROR_FAIL;
2465                 }
2466         }
2467
2468         return ERROR_OK;
2469 }
2470
2471 COMMAND_HANDLER(handle_halt_command)
2472 {
2473         LOG_DEBUG("-");
2474
2475         struct target *target = get_current_target(CMD_CTX);
2476         int retval = target_halt(target);
2477         if (ERROR_OK != retval)
2478                 return retval;
2479
2480         if (CMD_ARGC == 1) {
2481                 unsigned wait_local;
2482                 retval = parse_uint(CMD_ARGV[0], &wait_local);
2483                 if (ERROR_OK != retval)
2484                         return ERROR_COMMAND_SYNTAX_ERROR;
2485                 if (!wait_local)
2486                         return ERROR_OK;
2487         }
2488
2489         return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2490 }
2491
2492 COMMAND_HANDLER(handle_soft_reset_halt_command)
2493 {
2494         struct target *target = get_current_target(CMD_CTX);
2495
2496         LOG_USER("requesting target halt and executing a soft reset");
2497
2498         target_soft_reset_halt(target);
2499
2500         return ERROR_OK;
2501 }
2502
2503 COMMAND_HANDLER(handle_reset_command)
2504 {
2505         if (CMD_ARGC > 1)
2506                 return ERROR_COMMAND_SYNTAX_ERROR;
2507
2508         enum target_reset_mode reset_mode = RESET_RUN;
2509         if (CMD_ARGC == 1) {
2510                 const Jim_Nvp *n;
2511                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2512                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2513                         return ERROR_COMMAND_SYNTAX_ERROR;
2514                 reset_mode = n->value;
2515         }
2516
2517         /* reset *all* targets */
2518         return target_process_reset(CMD_CTX, reset_mode);
2519 }
2520
2521
2522 COMMAND_HANDLER(handle_resume_command)
2523 {
2524         int current = 1;
2525         if (CMD_ARGC > 1)
2526                 return ERROR_COMMAND_SYNTAX_ERROR;
2527
2528         struct target *target = get_current_target(CMD_CTX);
2529
2530         /* with no CMD_ARGV, resume from current pc, addr = 0,
2531          * with one arguments, addr = CMD_ARGV[0],
2532          * handle breakpoints, not debugging */
2533         uint32_t addr = 0;
2534         if (CMD_ARGC == 1) {
2535                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2536                 current = 0;
2537         }
2538
2539         return target_resume(target, current, addr, 1, 0);
2540 }
2541
2542 COMMAND_HANDLER(handle_step_command)
2543 {
2544         if (CMD_ARGC > 1)
2545                 return ERROR_COMMAND_SYNTAX_ERROR;
2546
2547         LOG_DEBUG("-");
2548
2549         /* with no CMD_ARGV, step from current pc, addr = 0,
2550          * with one argument addr = CMD_ARGV[0],
2551          * handle breakpoints, debugging */
2552         uint32_t addr = 0;
2553         int current_pc = 1;
2554         if (CMD_ARGC == 1) {
2555                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2556                 current_pc = 0;
2557         }
2558
2559         struct target *target = get_current_target(CMD_CTX);
2560
2561         return target->type->step(target, current_pc, addr, 1);
2562 }
2563
2564 static void handle_md_output(struct command_context *cmd_ctx,
2565                 struct target *target, uint32_t address, unsigned size,
2566                 unsigned count, const uint8_t *buffer)
2567 {
2568         const unsigned line_bytecnt = 32;
2569         unsigned line_modulo = line_bytecnt / size;
2570
2571         char output[line_bytecnt * 4 + 1];
2572         unsigned output_len = 0;
2573
2574         const char *value_fmt;
2575         switch (size) {
2576         case 4:
2577                 value_fmt = "%8.8x ";
2578                 break;
2579         case 2:
2580                 value_fmt = "%4.4x ";
2581                 break;
2582         case 1:
2583                 value_fmt = "%2.2x ";
2584                 break;
2585         default:
2586                 /* "can't happen", caller checked */
2587                 LOG_ERROR("invalid memory read size: %u", size);
2588                 return;
2589         }
2590
2591         for (unsigned i = 0; i < count; i++) {
2592                 if (i % line_modulo == 0) {
2593                         output_len += snprintf(output + output_len,
2594                                         sizeof(output) - output_len,
2595                                         "0x%8.8x: ",
2596                                         (unsigned)(address + (i*size)));
2597                 }
2598
2599                 uint32_t value = 0;
2600                 const uint8_t *value_ptr = buffer + i * size;
2601                 switch (size) {
2602                 case 4:
2603                         value = target_buffer_get_u32(target, value_ptr);
2604                         break;
2605                 case 2:
2606                         value = target_buffer_get_u16(target, value_ptr);
2607                         break;
2608                 case 1:
2609                         value = *value_ptr;
2610                 }
2611                 output_len += snprintf(output + output_len,
2612                                 sizeof(output) - output_len,
2613                                 value_fmt, value);
2614
2615                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2616                         command_print(cmd_ctx, "%s", output);
2617                         output_len = 0;
2618                 }
2619         }
2620 }
2621
2622 COMMAND_HANDLER(handle_md_command)
2623 {
2624         if (CMD_ARGC < 1)
2625                 return ERROR_COMMAND_SYNTAX_ERROR;
2626
2627         unsigned size = 0;
2628         switch (CMD_NAME[2]) {
2629         case 'w':
2630                 size = 4;
2631                 break;
2632         case 'h':
2633                 size = 2;
2634                 break;
2635         case 'b':
2636                 size = 1;
2637                 break;
2638         default:
2639                 return ERROR_COMMAND_SYNTAX_ERROR;
2640         }
2641
2642         bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2643         int (*fn)(struct target *target,
2644                         uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2645         if (physical) {
2646                 CMD_ARGC--;
2647                 CMD_ARGV++;
2648                 fn = target_read_phys_memory;
2649         } else
2650                 fn = target_read_memory;
2651         if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2652                 return ERROR_COMMAND_SYNTAX_ERROR;
2653
2654         uint32_t address;
2655         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2656
2657         unsigned count = 1;
2658         if (CMD_ARGC == 2)
2659                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2660
2661         uint8_t *buffer = calloc(count, size);
2662
2663         struct target *target = get_current_target(CMD_CTX);
2664         int retval = fn(target, address, size, count, buffer);
2665         if (ERROR_OK == retval)
2666                 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2667
2668         free(buffer);
2669
2670         return retval;
2671 }
2672
2673 typedef int (*target_write_fn)(struct target *target,
2674                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2675
2676 static int target_write_memory_fast(struct target *target,
2677                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2678 {
2679         return target_write_buffer(target, address, size * count, buffer);
2680 }
2681
2682 static int target_fill_mem(struct target *target,
2683                 uint32_t address,
2684                 target_write_fn fn,
2685                 unsigned data_size,
2686                 /* value */
2687                 uint32_t b,
2688                 /* count */
2689                 unsigned c)
2690 {
2691         /* We have to write in reasonably large chunks to be able
2692          * to fill large memory areas with any sane speed */
2693         const unsigned chunk_size = 16384;
2694         uint8_t *target_buf = malloc(chunk_size * data_size);
2695         if (target_buf == NULL) {
2696                 LOG_ERROR("Out of memory");
2697                 return ERROR_FAIL;
2698         }
2699
2700         for (unsigned i = 0; i < chunk_size; i++) {
2701                 switch (data_size) {
2702                 case 4:
2703                         target_buffer_set_u32(target, target_buf + i * data_size, b);
2704                         break;
2705                 case 2:
2706                         target_buffer_set_u16(target, target_buf + i * data_size, b);
2707                         break;
2708                 case 1:
2709                         target_buffer_set_u8(target, target_buf + i * data_size, b);
2710                         break;
2711                 default:
2712                         exit(-1);
2713                 }
2714         }
2715
2716         int retval = ERROR_OK;
2717
2718         for (unsigned x = 0; x < c; x += chunk_size) {
2719                 unsigned current;
2720                 current = c - x;
2721                 if (current > chunk_size)
2722                         current = chunk_size;
2723                 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2724                 if (retval != ERROR_OK)
2725                         break;
2726                 /* avoid GDB timeouts */
2727                 keep_alive();
2728         }
2729         free(target_buf);
2730
2731         return retval;
2732 }
2733
2734
2735 COMMAND_HANDLER(handle_mw_command)
2736 {
2737         if (CMD_ARGC < 2)
2738                 return ERROR_COMMAND_SYNTAX_ERROR;
2739         bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2740         target_write_fn fn;
2741         if (physical) {
2742                 CMD_ARGC--;
2743                 CMD_ARGV++;
2744                 fn = target_write_phys_memory;
2745         } else
2746                 fn = target_write_memory_fast;
2747         if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2748                 return ERROR_COMMAND_SYNTAX_ERROR;
2749
2750         uint32_t address;
2751         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2752
2753         uint32_t value;
2754         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2755
2756         unsigned count = 1;
2757         if (CMD_ARGC == 3)
2758                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2759
2760         struct target *target = get_current_target(CMD_CTX);
2761         unsigned wordsize;
2762         switch (CMD_NAME[2]) {
2763                 case 'w':
2764                         wordsize = 4;
2765                         break;
2766                 case 'h':
2767                         wordsize = 2;
2768                         break;
2769                 case 'b':
2770                         wordsize = 1;
2771                         break;
2772                 default:
2773                         return ERROR_COMMAND_SYNTAX_ERROR;
2774         }
2775
2776         return target_fill_mem(target, address, fn, wordsize, value, count);
2777 }
2778
2779 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2780                 uint32_t *min_address, uint32_t *max_address)
2781 {
2782         if (CMD_ARGC < 1 || CMD_ARGC > 5)
2783                 return ERROR_COMMAND_SYNTAX_ERROR;
2784
2785         /* a base address isn't always necessary,
2786          * default to 0x0 (i.e. don't relocate) */
2787         if (CMD_ARGC >= 2) {
2788                 uint32_t addr;
2789                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2790                 image->base_address = addr;
2791                 image->base_address_set = 1;
2792         } else
2793                 image->base_address_set = 0;
2794
2795         image->start_address_set = 0;
2796
2797         if (CMD_ARGC >= 4)
2798                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2799         if (CMD_ARGC == 5) {
2800                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2801                 /* use size (given) to find max (required) */
2802                 *max_address += *min_address;
2803         }
2804
2805         if (*min_address > *max_address)
2806                 return ERROR_COMMAND_SYNTAX_ERROR;
2807
2808         return ERROR_OK;
2809 }
2810
2811 COMMAND_HANDLER(handle_load_image_command)
2812 {
2813         uint8_t *buffer;
2814         size_t buf_cnt;
2815         uint32_t image_size;
2816         uint32_t min_address = 0;
2817         uint32_t max_address = 0xffffffff;
2818         int i;
2819         struct image image;
2820
2821         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2822                         &image, &min_address, &max_address);
2823         if (ERROR_OK != retval)
2824                 return retval;
2825
2826         struct target *target = get_current_target(CMD_CTX);
2827
2828         struct duration bench;
2829         duration_start(&bench);
2830
2831         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2832                 return ERROR_OK;
2833
2834         image_size = 0x0;
2835         retval = ERROR_OK;
2836         for (i = 0; i < image.num_sections; i++) {
2837                 buffer = malloc(image.sections[i].size);
2838                 if (buffer == NULL) {
2839                         command_print(CMD_CTX,
2840                                                   "error allocating buffer for section (%d bytes)",
2841                                                   (int)(image.sections[i].size));
2842                         break;
2843                 }
2844
2845                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
2846                 if (retval != ERROR_OK) {
2847                         free(buffer);
2848                         break;
2849                 }
2850
2851                 uint32_t offset = 0;
2852                 uint32_t length = buf_cnt;
2853
2854                 /* DANGER!!! beware of unsigned comparision here!!! */
2855
2856                 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
2857                                 (image.sections[i].base_address < max_address)) {
2858
2859                         if (image.sections[i].base_address < min_address) {
2860                                 /* clip addresses below */
2861                                 offset += min_address-image.sections[i].base_address;
2862                                 length -= offset;
2863                         }
2864
2865                         if (image.sections[i].base_address + buf_cnt > max_address)
2866                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2867
2868                         retval = target_write_buffer(target,
2869                                         image.sections[i].base_address + offset, length, buffer + offset);
2870                         if (retval != ERROR_OK) {
2871                                 free(buffer);
2872                                 break;
2873                         }
2874                         image_size += length;
2875                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2876                                         (unsigned int)length,
2877                                         image.sections[i].base_address + offset);
2878                 }
2879
2880                 free(buffer);
2881         }
2882
2883         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2884                 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2885                                 "in %fs (%0.3f KiB/s)", image_size,
2886                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2887         }
2888
2889         image_close(&image);
2890
2891         return retval;
2892
2893 }
2894
2895 COMMAND_HANDLER(handle_dump_image_command)
2896 {
2897         struct fileio fileio;
2898         uint8_t *buffer;
2899         int retval, retvaltemp;
2900         uint32_t address, size;
2901         struct duration bench;
2902         struct target *target = get_current_target(CMD_CTX);
2903
2904         if (CMD_ARGC != 3)
2905                 return ERROR_COMMAND_SYNTAX_ERROR;
2906
2907         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2908         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2909
2910         uint32_t buf_size = (size > 4096) ? 4096 : size;
2911         buffer = malloc(buf_size);
2912         if (!buffer)
2913                 return ERROR_FAIL;
2914
2915         retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2916         if (retval != ERROR_OK) {
2917                 free(buffer);
2918                 return retval;
2919         }
2920
2921         duration_start(&bench);
2922
2923         while (size > 0) {
2924                 size_t size_written;
2925                 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
2926                 retval = target_read_buffer(target, address, this_run_size, buffer);
2927                 if (retval != ERROR_OK)
2928                         break;
2929
2930                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2931                 if (retval != ERROR_OK)
2932                         break;
2933
2934                 size -= this_run_size;
2935                 address += this_run_size;
2936         }
2937
2938         free(buffer);
2939
2940         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
2941                 int filesize;
2942                 retval = fileio_size(&fileio, &filesize);
2943                 if (retval != ERROR_OK)
2944                         return retval;
2945                 command_print(CMD_CTX,
2946                                 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2947                                 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2948         }
2949
2950         retvaltemp = fileio_close(&fileio);
2951         if (retvaltemp != ERROR_OK)
2952                 return retvaltemp;
2953
2954         return retval;
2955 }
2956
2957 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2958 {
2959         uint8_t *buffer;
2960         size_t buf_cnt;
2961         uint32_t image_size;
2962         int i;
2963         int retval;
2964         uint32_t checksum = 0;
2965         uint32_t mem_checksum = 0;
2966
2967         struct image image;
2968
2969         struct target *target = get_current_target(CMD_CTX);
2970
2971         if (CMD_ARGC < 1)
2972                 return ERROR_COMMAND_SYNTAX_ERROR;
2973
2974         if (!target) {
2975                 LOG_ERROR("no target selected");
2976                 return ERROR_FAIL;
2977         }
2978
2979         struct duration bench;
2980         duration_start(&bench);
2981
2982         if (CMD_ARGC >= 2) {
2983                 uint32_t addr;
2984                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2985                 image.base_address = addr;
2986                 image.base_address_set = 1;
2987         } else {
2988                 image.base_address_set = 0;
2989                 image.base_address = 0x0;
2990         }
2991
2992         image.start_address_set = 0;
2993
2994         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
2995         if (retval != ERROR_OK)
2996                 return retval;
2997
2998         image_size = 0x0;
2999         int diffs = 0;
3000         retval = ERROR_OK;
3001         for (i = 0; i < image.num_sections; i++) {
3002                 buffer = malloc(image.sections[i].size);
3003                 if (buffer == NULL) {
3004                         command_print(CMD_CTX,
3005                                         "error allocating buffer for section (%d bytes)",
3006                                         (int)(image.sections[i].size));
3007                         break;
3008                 }
3009                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3010                 if (retval != ERROR_OK) {
3011                         free(buffer);
3012                         break;
3013                 }
3014
3015                 if (verify) {
3016                         /* calculate checksum of image */
3017                         retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3018                         if (retval != ERROR_OK) {
3019                                 free(buffer);
3020                                 break;
3021                         }
3022
3023                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3024                         if (retval != ERROR_OK) {
3025                                 free(buffer);
3026                                 break;
3027                         }
3028
3029                         if (checksum != mem_checksum) {
3030                                 /* failed crc checksum, fall back to a binary compare */
3031                                 uint8_t *data;
3032
3033                                 if (diffs == 0)
3034                                         LOG_ERROR("checksum mismatch - attempting binary compare");
3035
3036                                 data = (uint8_t *)malloc(buf_cnt);
3037
3038                                 /* Can we use 32bit word accesses? */
3039                                 int size = 1;
3040                                 int count = buf_cnt;
3041                                 if ((count % 4) == 0) {
3042                                         size *= 4;
3043                                         count /= 4;
3044                                 }
3045                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3046                                 if (retval == ERROR_OK) {
3047                                         uint32_t t;
3048                                         for (t = 0; t < buf_cnt; t++) {
3049                                                 if (data[t] != buffer[t]) {
3050                                                         command_print(CMD_CTX,
3051                                                                                   "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3052                                                                                   diffs,
3053                                                                                   (unsigned)(t + image.sections[i].base_address),
3054                                                                                   data[t],
3055                                                                                   buffer[t]);
3056                                                         if (diffs++ >= 127) {
3057                                                                 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3058                                                                 free(data);
3059                                                                 free(buffer);
3060                                                                 goto done;
3061                                                         }
3062                                                 }
3063                                                 keep_alive();
3064                                         }
3065                                 }
3066                                 free(data);
3067                         }
3068                 } else {
3069                         command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3070                                                   image.sections[i].base_address,
3071                                                   buf_cnt);
3072                 }
3073
3074                 free(buffer);
3075                 image_size += buf_cnt;
3076         }
3077         if (diffs > 0)
3078                 command_print(CMD_CTX, "No more differences found.");
3079 done:
3080         if (diffs > 0)
3081                 retval = ERROR_FAIL;
3082         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3083                 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3084                                 "in %fs (%0.3f KiB/s)", image_size,
3085                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3086         }
3087
3088         image_close(&image);
3089
3090         return retval;
3091 }
3092
3093 COMMAND_HANDLER(handle_verify_image_command)
3094 {
3095         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3096 }
3097
3098 COMMAND_HANDLER(handle_test_image_command)
3099 {
3100         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3101 }
3102
3103 static int handle_bp_command_list(struct command_context *cmd_ctx)
3104 {
3105         struct target *target = get_current_target(cmd_ctx);
3106         struct breakpoint *breakpoint = target->breakpoints;
3107         while (breakpoint) {
3108                 if (breakpoint->type == BKPT_SOFT) {
3109                         char *buf = buf_to_str(breakpoint->orig_instr,
3110                                         breakpoint->length, 16);
3111                         command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3112                                         breakpoint->address,
3113                                         breakpoint->length,
3114                                         breakpoint->set, buf);
3115                         free(buf);
3116                 } else {
3117                         if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3118                                 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3119                                                         breakpoint->asid,
3120                                                         breakpoint->length, breakpoint->set);
3121                         else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3122                                 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3123                                                         breakpoint->address,
3124                                                         breakpoint->length, breakpoint->set);
3125                                 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3126                                                         breakpoint->asid);
3127                         } else
3128                                 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3129                                                         breakpoint->address,
3130                                                         breakpoint->length, breakpoint->set);
3131                 }
3132
3133                 breakpoint = breakpoint->next;
3134         }
3135         return ERROR_OK;
3136 }
3137
3138 static int handle_bp_command_set(struct command_context *cmd_ctx,
3139                 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3140 {
3141         struct target *target = get_current_target(cmd_ctx);
3142
3143         if (asid == 0) {
3144                 int retval = breakpoint_add(target, addr, length, hw);
3145                 if (ERROR_OK == retval)
3146                         command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3147                 else {
3148                         LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3149                         return retval;
3150                 }
3151         } else if (addr == 0) {
3152                 int retval = context_breakpoint_add(target, asid, length, hw);
3153                 if (ERROR_OK == retval)
3154                         command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3155                 else {
3156                         LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3157                         return retval;
3158                 }
3159         } else {
3160                 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3161                 if (ERROR_OK == retval)
3162                         command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3163                 else {
3164                         LOG_ERROR("Failure setting breakpoint, the same address is already used");
3165                         return retval;
3166                 }
3167         }
3168         return ERROR_OK;
3169 }
3170
3171 COMMAND_HANDLER(handle_bp_command)
3172 {
3173         uint32_t addr;
3174         uint32_t asid;
3175         uint32_t length;
3176         int hw = BKPT_SOFT;
3177
3178         switch (CMD_ARGC) {
3179                 case 0:
3180                         return handle_bp_command_list(CMD_CTX);
3181
3182                 case 2:
3183                         asid = 0;
3184                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3185                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3186                         return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3187
3188                 case 3:
3189                         if (strcmp(CMD_ARGV[2], "hw") == 0) {
3190                                 hw = BKPT_HARD;
3191                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3192
3193                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3194
3195                                 asid = 0;
3196                                 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3197                         } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3198                                 hw = BKPT_HARD;
3199                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3200                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3201                                 addr = 0;
3202                                 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3203                         }
3204
3205                 case 4:
3206                         hw = BKPT_HARD;
3207                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3208                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3209                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3210                         return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3211
3212                 default:
3213                         return ERROR_COMMAND_SYNTAX_ERROR;
3214         }
3215 }
3216
3217 COMMAND_HANDLER(handle_rbp_command)
3218 {
3219         if (CMD_ARGC != 1)
3220                 return ERROR_COMMAND_SYNTAX_ERROR;
3221
3222         uint32_t addr;
3223         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3224
3225         struct target *target = get_current_target(CMD_CTX);
3226         breakpoint_remove(target, addr);
3227
3228         return ERROR_OK;
3229 }
3230
3231 COMMAND_HANDLER(handle_wp_command)
3232 {
3233         struct target *target = get_current_target(CMD_CTX);
3234
3235         if (CMD_ARGC == 0) {
3236                 struct watchpoint *watchpoint = target->watchpoints;
3237
3238                 while (watchpoint) {
3239                         command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3240                                         ", len: 0x%8.8" PRIx32
3241                                         ", r/w/a: %i, value: 0x%8.8" PRIx32
3242                                         ", mask: 0x%8.8" PRIx32,
3243                                         watchpoint->address,
3244                                         watchpoint->length,
3245                                         (int)watchpoint->rw,
3246                                         watchpoint->value,
3247                                         watchpoint->mask);
3248                         watchpoint = watchpoint->next;
3249                 }
3250                 return ERROR_OK;
3251         }
3252
3253         enum watchpoint_rw type = WPT_ACCESS;
3254         uint32_t addr = 0;
3255         uint32_t length = 0;
3256         uint32_t data_value = 0x0;
3257         uint32_t data_mask = 0xffffffff;
3258
3259         switch (CMD_ARGC) {
3260         case 5:
3261                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3262                 /* fall through */
3263         case 4:
3264                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3265                 /* fall through */
3266         case 3:
3267                 switch (CMD_ARGV[2][0]) {
3268                 case 'r':
3269                         type = WPT_READ;
3270                         break;
3271                 case 'w':
3272                         type = WPT_WRITE;
3273                         break;
3274                 case 'a':
3275                         type = WPT_ACCESS;
3276                         break;
3277                 default:
3278                         LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3279                         return ERROR_COMMAND_SYNTAX_ERROR;
3280                 }
3281                 /* fall through */
3282         case 2:
3283                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3284                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3285                 break;
3286
3287         default:
3288                 return ERROR_COMMAND_SYNTAX_ERROR;
3289         }
3290
3291         int retval = watchpoint_add(target, addr, length, type,
3292                         data_value, data_mask);
3293         if (ERROR_OK != retval)
3294                 LOG_ERROR("Failure setting watchpoints");
3295
3296         return retval;
3297 }
3298
3299 COMMAND_HANDLER(handle_rwp_command)
3300 {
3301         if (CMD_ARGC != 1)
3302                 return ERROR_COMMAND_SYNTAX_ERROR;
3303
3304         uint32_t addr;
3305         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3306
3307         struct target *target = get_current_target(CMD_CTX);
3308         watchpoint_remove(target, addr);
3309
3310         return ERROR_OK;
3311 }
3312
3313 /**
3314  * Translate a virtual address to a physical address.
3315  *
3316  * The low-level target implementation must have logged a detailed error
3317  * which is forwarded to telnet/GDB session.
3318  */
3319 COMMAND_HANDLER(handle_virt2phys_command)
3320 {
3321         if (CMD_ARGC != 1)
3322                 return ERROR_COMMAND_SYNTAX_ERROR;
3323
3324         uint32_t va;
3325         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3326         uint32_t pa;
3327
3328         struct target *target = get_current_target(CMD_CTX);
3329         int retval = target->type->virt2phys(target, va, &pa);
3330         if (retval == ERROR_OK)
3331                 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3332
3333         return retval;
3334 }
3335
3336 static void writeData(FILE *f, const void *data, size_t len)
3337 {
3338         size_t written = fwrite(data, 1, len, f);
3339         if (written != len)
3340                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3341 }
3342
3343 static void writeLong(FILE *f, int l)
3344 {
3345         int i;
3346         for (i = 0; i < 4; i++) {
3347                 char c = (l >> (i*8))&0xff;
3348                 writeData(f, &c, 1);
3349         }
3350
3351 }
3352
3353 static void writeString(FILE *f, char *s)
3354 {
3355         writeData(f, s, strlen(s));
3356 }
3357
3358 /* Dump a gmon.out histogram file. */
3359 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3360 {
3361         uint32_t i;
3362         FILE *f = fopen(filename, "w");
3363         if (f == NULL)
3364                 return;
3365         writeString(f, "gmon");
3366         writeLong(f, 0x00000001); /* Version */
3367         writeLong(f, 0); /* padding */
3368         writeLong(f, 0); /* padding */
3369         writeLong(f, 0); /* padding */
3370
3371         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3372         writeData(f, &zero, 1);
3373
3374         /* figure out bucket size */
3375         uint32_t min = samples[0];
3376         uint32_t max = samples[0];
3377         for (i = 0; i < sampleNum; i++) {
3378                 if (min > samples[i])
3379                         min = samples[i];
3380                 if (max < samples[i])
3381                         max = samples[i];
3382         }
3383
3384         int addressSpace = (max - min + 1);
3385         assert(addressSpace >= 2);
3386
3387         static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3388         uint32_t length = addressSpace;
3389         if (length > maxBuckets)
3390                 length = maxBuckets;
3391         int *buckets = malloc(sizeof(int)*length);
3392         if (buckets == NULL) {
3393                 fclose(f);
3394                 return;
3395         }
3396         memset(buckets, 0, sizeof(int) * length);
3397         for (i = 0; i < sampleNum; i++) {
3398                 uint32_t address = samples[i];
3399                 long long a = address - min;
3400                 long long b = length - 1;
3401                 long long c = addressSpace - 1;
3402                 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3403                 buckets[index_t]++;
3404         }
3405
3406         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3407         writeLong(f, min);                      /* low_pc */
3408         writeLong(f, max);                      /* high_pc */
3409         writeLong(f, length);           /* # of samples */
3410         writeLong(f, 100);                      /* KLUDGE! We lie, ca. 100Hz best case. */
3411         writeString(f, "seconds");
3412         for (i = 0; i < (15-strlen("seconds")); i++)
3413                 writeData(f, &zero, 1);
3414         writeString(f, "s");
3415
3416         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3417
3418         char *data = malloc(2 * length);
3419         if (data != NULL) {
3420                 for (i = 0; i < length; i++) {
3421                         int val;
3422                         val = buckets[i];
3423                         if (val > 65535)
3424                                 val = 65535;
3425                         data[i * 2] = val&0xff;
3426                         data[i * 2 + 1] = (val >> 8) & 0xff;
3427                 }
3428                 free(buckets);
3429                 writeData(f, data, length * 2);
3430                 free(data);
3431         } else
3432                 free(buckets);
3433
3434         fclose(f);
3435 }
3436
3437 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3438  * which will be used as a random sampling of PC */
3439 COMMAND_HANDLER(handle_profile_command)
3440 {
3441         struct target *target = get_current_target(CMD_CTX);
3442         struct timeval timeout, now;
3443
3444         gettimeofday(&timeout, NULL);
3445         if (CMD_ARGC != 2)
3446                 return ERROR_COMMAND_SYNTAX_ERROR;
3447         unsigned offset;
3448         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3449
3450         timeval_add_time(&timeout, offset, 0);
3451
3452         /**
3453          * @todo: Some cores let us sample the PC without the
3454          * annoying halt/resume step; for example, ARMv7 PCSR.
3455          * Provide a way to use that more efficient mechanism.
3456          */
3457
3458         command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3459
3460         static const int maxSample = 10000;
3461         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3462         if (samples == NULL)
3463                 return ERROR_OK;
3464
3465         int numSamples = 0;
3466         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3467         struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3468
3469         int retval = ERROR_OK;
3470         for (;;) {
3471                 target_poll(target);
3472                 if (target->state == TARGET_HALTED) {
3473                         uint32_t t = *((uint32_t *)reg->value);
3474                         samples[numSamples++] = t;
3475                         /* current pc, addr = 0, do not handle breakpoints, not debugging */
3476                         retval = target_resume(target, 1, 0, 0, 0);
3477                         target_poll(target);
3478                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3479                 } else if (target->state == TARGET_RUNNING) {
3480                         /* We want to quickly sample the PC. */
3481                         retval = target_halt(target);
3482                         if (retval != ERROR_OK) {
3483                                 free(samples);
3484                                 return retval;
3485                         }
3486                 } else {
3487                         command_print(CMD_CTX, "Target not halted or running");
3488                         retval = ERROR_OK;
3489                         break;
3490                 }
3491                 if (retval != ERROR_OK)
3492                         break;
3493
3494                 gettimeofday(&now, NULL);
3495                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec)
3496                                 && (now.tv_usec >= timeout.tv_usec))) {
3497                         command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3498                         retval = target_poll(target);
3499                         if (retval != ERROR_OK) {
3500                                 free(samples);
3501                                 return retval;
3502                         }
3503                         if (target->state == TARGET_HALTED) {
3504                                 /* current pc, addr = 0, do not handle
3505                                  * breakpoints, not debugging */
3506                                 target_resume(target, 1, 0, 0, 0);
3507                         }
3508                         retval = target_poll(target);
3509                         if (retval != ERROR_OK) {
3510                                 free(samples);
3511                                 return retval;
3512                         }
3513                         writeGmon(samples, numSamples, CMD_ARGV[1]);
3514                         command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3515                         break;
3516                 }
3517         }
3518         free(samples);
3519
3520         return retval;
3521 }
3522
3523 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3524 {
3525         char *namebuf;
3526         Jim_Obj *nameObjPtr, *valObjPtr;
3527         int result;
3528
3529         namebuf = alloc_printf("%s(%d)", varname, idx);
3530         if (!namebuf)
3531                 return JIM_ERR;
3532
3533         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3534         valObjPtr = Jim_NewIntObj(interp, val);
3535         if (!nameObjPtr || !valObjPtr) {
3536                 free(namebuf);
3537                 return JIM_ERR;
3538         }
3539
3540         Jim_IncrRefCount(nameObjPtr);
3541         Jim_IncrRefCount(valObjPtr);
3542         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3543         Jim_DecrRefCount(interp, nameObjPtr);
3544         Jim_DecrRefCount(interp, valObjPtr);
3545         free(namebuf);
3546         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3547         return result;
3548 }
3549
3550 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3551 {
3552         struct command_context *context;
3553         struct target *target;
3554
3555         context = current_command_context(interp);
3556         assert(context != NULL);
3557
3558         target = get_current_target(context);
3559         if (target == NULL) {
3560                 LOG_ERROR("mem2array: no current target");
3561                 return JIM_ERR;
3562         }
3563
3564         return target_mem2array(interp, target, argc - 1, argv + 1);
3565 }
3566
3567 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3568 {
3569         long l;
3570         uint32_t width;
3571         int len;
3572         uint32_t addr;
3573         uint32_t count;
3574         uint32_t v;
3575         const char *varname;
3576         int  n, e, retval;
3577         uint32_t i;
3578
3579         /* argv[1] = name of array to receive the data
3580          * argv[2] = desired width
3581          * argv[3] = memory address
3582          * argv[4] = count of times to read
3583          */
3584         if (argc != 4) {
3585                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3586                 return JIM_ERR;
3587         }
3588         varname = Jim_GetString(argv[0], &len);
3589         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3590
3591         e = Jim_GetLong(interp, argv[1], &l);
3592         width = l;
3593         if (e != JIM_OK)
3594                 return e;
3595
3596         e = Jim_GetLong(interp, argv[2], &l);
3597         addr = l;
3598         if (e != JIM_OK)
3599                 return e;
3600         e = Jim_GetLong(interp, argv[3], &l);
3601         len = l;
3602         if (e != JIM_OK)
3603                 return e;
3604         switch (width) {
3605                 case 8:
3606                         width = 1;
3607                         break;
3608                 case 16:
3609                         width = 2;
3610                         break;
3611                 case 32:
3612                         width = 4;
3613                         break;
3614                 default:
3615                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3616                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3617                         return JIM_ERR;
3618         }
3619         if (len == 0) {
3620                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3621                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3622                 return JIM_ERR;
3623         }
3624         if ((addr + (len * width)) < addr) {
3625                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3626                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3627                 return JIM_ERR;
3628         }
3629         /* absurd transfer size? */
3630         if (len > 65536) {
3631                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3632                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3633                 return JIM_ERR;
3634         }
3635
3636         if ((width == 1) ||
3637                 ((width == 2) && ((addr & 1) == 0)) ||
3638                 ((width == 4) && ((addr & 3) == 0))) {
3639                 /* all is well */
3640         } else {
3641                 char buf[100];
3642                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3643                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3644                                 addr,
3645                                 width);
3646                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3647                 return JIM_ERR;
3648         }
3649
3650         /* Transfer loop */
3651
3652         /* index counter */
3653         n = 0;
3654
3655         size_t buffersize = 4096;
3656         uint8_t *buffer = malloc(buffersize);
3657         if (buffer == NULL)
3658                 return JIM_ERR;
3659
3660         /* assume ok */
3661         e = JIM_OK;
3662         while (len) {
3663                 /* Slurp... in buffer size chunks */
3664
3665                 count = len; /* in objects.. */
3666                 if (count > (buffersize / width))
3667                         count = (buffersize / width);
3668
3669                 retval = target_read_memory(target, addr, width, count, buffer);
3670                 if (retval != ERROR_OK) {
3671                         /* BOO !*/
3672                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3673                                           (unsigned int)addr,
3674                                           (int)width,
3675                                           (int)count);
3676                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3677                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3678                         e = JIM_ERR;
3679                         break;
3680                 } else {
3681                         v = 0; /* shut up gcc */
3682                         for (i = 0; i < count ; i++, n++) {
3683                                 switch (width) {
3684                                         case 4:
3685                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3686                                                 break;
3687                                         case 2:
3688                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3689                                                 break;
3690                                         case 1:
3691                                                 v = buffer[i] & 0x0ff;
3692                                                 break;
3693                                 }
3694                                 new_int_array_element(interp, varname, n, v);
3695                         }
3696                         len -= count;
3697                 }
3698         }
3699
3700         free(buffer);
3701
3702         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3703
3704         return e;
3705 }
3706
3707 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3708 {
3709         char *namebuf;
3710         Jim_Obj *nameObjPtr, *valObjPtr;
3711         int result;
3712         long l;
3713
3714         namebuf = alloc_printf("%s(%d)", varname, idx);
3715         if (!namebuf)
3716                 return JIM_ERR;
3717
3718         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3719         if (!nameObjPtr) {
3720                 free(namebuf);
3721                 return JIM_ERR;
3722         }
3723
3724         Jim_IncrRefCount(nameObjPtr);
3725         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3726         Jim_DecrRefCount(interp, nameObjPtr);
3727         free(namebuf);
3728         if (valObjPtr == NULL)
3729                 return JIM_ERR;
3730
3731         result = Jim_GetLong(interp, valObjPtr, &l);
3732         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3733         *val = l;
3734         return result;
3735 }
3736
3737 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3738 {
3739         struct command_context *context;
3740         struct target *target;
3741
3742         context = current_command_context(interp);
3743         assert(context != NULL);
3744
3745         target = get_current_target(context);
3746         if (target == NULL) {
3747                 LOG_ERROR("array2mem: no current target");
3748                 return JIM_ERR;
3749         }
3750
3751         return target_array2mem(interp, target, argc-1, argv + 1);
3752 }
3753
3754 static int target_array2mem(Jim_Interp *interp, struct target *target,
3755                 int argc, Jim_Obj *const *argv)
3756 {
3757         long l;
3758         uint32_t width;
3759         int len;
3760         uint32_t addr;
3761         uint32_t count;
3762         uint32_t v;
3763         const char *varname;
3764         int  n, e, retval;
3765         uint32_t i;
3766
3767         /* argv[1] = name of array to get the data
3768          * argv[2] = desired width
3769          * argv[3] = memory address
3770          * argv[4] = count to write
3771          */
3772         if (argc != 4) {
3773                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3774                 return JIM_ERR;
3775         }
3776         varname = Jim_GetString(argv[0], &len);
3777         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3778
3779         e = Jim_GetLong(interp, argv[1], &l);
3780         width = l;
3781         if (e != JIM_OK)
3782                 return e;
3783
3784         e = Jim_GetLong(interp, argv[2], &l);
3785         addr = l;
3786         if (e != JIM_OK)
3787                 return e;
3788         e = Jim_GetLong(interp, argv[3], &l);
3789         len = l;
3790         if (e != JIM_OK)
3791                 return e;
3792         switch (width) {
3793                 case 8:
3794                         width = 1;
3795                         break;
3796                 case 16:
3797                         width = 2;
3798                         break;
3799                 case 32:
3800                         width = 4;
3801                         break;
3802                 default:
3803                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3804                         Jim_AppendStrings(interp, Jim_GetResult(interp),
3805                                         "Invalid width param, must be 8/16/32", NULL);
3806                         return JIM_ERR;
3807         }
3808         if (len == 0) {
3809                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3810                 Jim_AppendStrings(interp, Jim_GetResult(interp),
3811                                 "array2mem: zero width read?", NULL);
3812                 return JIM_ERR;
3813         }
3814         if ((addr + (len * width)) < addr) {
3815                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3816                 Jim_AppendStrings(interp, Jim_GetResult(interp),
3817                                 "array2mem: addr + len - wraps to zero?", NULL);
3818                 return JIM_ERR;
3819         }
3820         /* absurd transfer size? */
3821         if (len > 65536) {
3822                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3823                 Jim_AppendStrings(interp, Jim_GetResult(interp),
3824                                 "array2mem: absurd > 64K item request", NULL);
3825                 return JIM_ERR;
3826         }
3827
3828         if ((width == 1) ||
3829                 ((width == 2) && ((addr & 1) == 0)) ||
3830                 ((width == 4) && ((addr & 3) == 0))) {
3831                 /* all is well */
3832         } else {
3833                 char buf[100];
3834                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3835                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3836                                 (unsigned int)addr,
3837                                 (int)width);
3838                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3839                 return JIM_ERR;
3840         }
3841
3842         /* Transfer loop */
3843
3844         /* index counter */
3845         n = 0;
3846         /* assume ok */
3847         e = JIM_OK;
3848
3849         size_t buffersize = 4096;
3850         uint8_t *buffer = malloc(buffersize);
3851         if (buffer == NULL)
3852                 return JIM_ERR;
3853
3854         while (len) {
3855                 /* Slurp... in buffer size chunks */
3856
3857                 count = len; /* in objects.. */
3858                 if (count > (buffersize / width))
3859                         count = (buffersize / width);
3860
3861                 v = 0; /* shut up gcc */
3862                 for (i = 0; i < count; i++, n++) {
3863                         get_int_array_element(interp, varname, n, &v);
3864                         switch (width) {
3865                         case 4:
3866                                 target_buffer_set_u32(target, &buffer[i * width], v);
3867                                 break;
3868                         case 2:
3869                                 target_buffer_set_u16(target, &buffer[i * width], v);
3870                                 break;
3871                         case 1:
3872                                 buffer[i] = v & 0x0ff;
3873                                 break;
3874                         }
3875                 }
3876                 len -= count;
3877
3878                 retval = target_write_memory(target, addr, width, count, buffer);
3879                 if (retval != ERROR_OK) {
3880                         /* BOO !*/
3881                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3882                                           (unsigned int)addr,
3883                                           (int)width,
3884                                           (int)count);
3885                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3886                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3887                         e = JIM_ERR;
3888                         break;
3889                 }
3890         }
3891
3892         free(buffer);
3893
3894         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3895
3896         return e;
3897 }
3898
3899 /* FIX? should we propagate errors here rather than printing them
3900  * and continuing?
3901  */
3902 void target_handle_event(struct target *target, enum target_event e)
3903 {
3904         struct target_event_action *teap;
3905
3906         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3907                 if (teap->event == e) {
3908                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3909                                            target->target_number,
3910                                            target_name(target),
3911                                            target_type_name(target),
3912                                            e,
3913                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3914                                            Jim_GetString(teap->body, NULL));
3915                         if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
3916                                 Jim_MakeErrorMessage(teap->interp);
3917                                 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3918                         }
3919                 }
3920         }
3921 }
3922
3923 /**
3924  * Returns true only if the target has a handler for the specified event.
3925  */
3926 bool target_has_event_action(struct target *target, enum target_event event)
3927 {
3928         struct target_event_action *teap;
3929
3930         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3931                 if (teap->event == event)
3932                         return true;
3933         }
3934         return false;
3935 }
3936
3937 enum target_cfg_param {
3938         TCFG_TYPE,
3939         TCFG_EVENT,
3940         TCFG_WORK_AREA_VIRT,
3941         TCFG_WORK_AREA_PHYS,
3942         TCFG_WORK_AREA_SIZE,
3943         TCFG_WORK_AREA_BACKUP,
3944         TCFG_ENDIAN,
3945         TCFG_VARIANT,
3946         TCFG_COREID,
3947         TCFG_CHAIN_POSITION,
3948         TCFG_DBGBASE,
3949         TCFG_RTOS,
3950 };
3951
3952 static Jim_Nvp nvp_config_opts[] = {
3953         { .name = "-type",             .value = TCFG_TYPE },
3954         { .name = "-event",            .value = TCFG_EVENT },
3955         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3956         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3957         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3958         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3959         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3960         { .name = "-variant",          .value = TCFG_VARIANT },
3961         { .name = "-coreid",           .value = TCFG_COREID },
3962         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3963         { .name = "-dbgbase",          .value = TCFG_DBGBASE },
3964         { .name = "-rtos",             .value = TCFG_RTOS },
3965         { .name = NULL, .value = -1 }
3966 };
3967
3968 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3969 {
3970         Jim_Nvp *n;
3971         Jim_Obj *o;
3972         jim_wide w;
3973         char *cp;
3974         int e;
3975
3976         /* parse config or cget options ... */
3977         while (goi->argc > 0) {
3978                 Jim_SetEmptyResult(goi->interp);
3979                 /* Jim_GetOpt_Debug(goi); */
3980
3981                 if (target->type->target_jim_configure) {
3982                         /* target defines a configure function */
3983                         /* target gets first dibs on parameters */
3984                         e = (*(target->type->target_jim_configure))(target, goi);
3985                         if (e == JIM_OK) {
3986                                 /* more? */
3987                                 continue;
3988                         }
3989                         if (e == JIM_ERR) {
3990                                 /* An error */
3991                                 return e;
3992                         }
3993                         /* otherwise we 'continue' below */
3994                 }
3995                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3996                 if (e != JIM_OK) {
3997                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3998                         return e;
3999                 }
4000                 switch (n->value) {
4001                 case TCFG_TYPE:
4002                         /* not setable */
4003                         if (goi->isconfigure) {
4004                                 Jim_SetResultFormatted(goi->interp,
4005                                                 "not settable: %s", n->name);
4006                                 return JIM_ERR;
4007                         } else {
4008 no_params:
4009                                 if (goi->argc != 0) {
4010                                         Jim_WrongNumArgs(goi->interp,
4011                                                         goi->argc, goi->argv,
4012                                                         "NO PARAMS");
4013                                         return JIM_ERR;
4014                                 }
4015                         }
4016                         Jim_SetResultString(goi->interp,
4017                                         target_type_name(target), -1);
4018                         /* loop for more */
4019                         break;
4020                 case TCFG_EVENT:
4021                         if (goi->argc == 0) {
4022                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4023                                 return JIM_ERR;
4024                         }
4025
4026                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4027                         if (e != JIM_OK) {
4028                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4029                                 return e;
4030                         }
4031
4032                         if (goi->isconfigure) {
4033                                 if (goi->argc != 1) {
4034                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4035                                         return JIM_ERR;
4036                                 }
4037                         } else {
4038                                 if (goi->argc != 0) {
4039                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4040                                         return JIM_ERR;
4041                                 }
4042                         }
4043
4044                         {
4045                                 struct target_event_action *teap;
4046
4047                                 teap = target->event_action;
4048                                 /* replace existing? */
4049                                 while (teap) {
4050                                         if (teap->event == (enum target_event)n->value)
4051                                                 break;
4052                                         teap = teap->next;
4053                                 }
4054
4055                                 if (goi->isconfigure) {
4056                                         bool replace = true;
4057                                         if (teap == NULL) {
4058                                                 /* create new */
4059                                                 teap = calloc(1, sizeof(*teap));
4060                                                 replace = false;
4061                                         }
4062                                         teap->event = n->value;
4063                                         teap->interp = goi->interp;
4064                                         Jim_GetOpt_Obj(goi, &o);
4065                                         if (teap->body)
4066                                                 Jim_DecrRefCount(teap->interp, teap->body);
4067                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
4068                                         /*
4069                                          * FIXME:
4070                                          *     Tcl/TK - "tk events" have a nice feature.
4071                                          *     See the "BIND" command.
4072                                          *    We should support that here.
4073                                          *     You can specify %X and %Y in the event code.
4074                                          *     The idea is: %T - target name.
4075                                          *     The idea is: %N - target number
4076                                          *     The idea is: %E - event name.
4077                                          */
4078                                         Jim_IncrRefCount(teap->body);
4079
4080                                         if (!replace) {
4081                                                 /* add to head of event list */
4082                                                 teap->next = target->event_action;
4083                                                 target->event_action = teap;
4084                                         }
4085                                         Jim_SetEmptyResult(goi->interp);
4086                                 } else {
4087                                         /* get */
4088                                         if (teap == NULL)
4089                                                 Jim_SetEmptyResult(goi->interp);
4090                                         else
4091                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4092                                 }
4093                         }
4094                         /* loop for more */
4095                         break;
4096
4097                 case TCFG_WORK_AREA_VIRT:
4098                         if (goi->isconfigure) {
4099                                 target_free_all_working_areas(target);
4100                                 e = Jim_GetOpt_Wide(goi, &w);
4101                                 if (e != JIM_OK)
4102                                         return e;
4103                                 target->working_area_virt = w;
4104                                 target->working_area_virt_spec = true;
4105                         } else {
4106                                 if (goi->argc != 0)
4107                                         goto no_params;
4108                         }
4109                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4110                         /* loop for more */
4111                         break;
4112
4113                 case TCFG_WORK_AREA_PHYS:
4114                         if (goi->isconfigure) {
4115                                 target_free_all_working_areas(target);
4116                                 e = Jim_GetOpt_Wide(goi, &w);
4117                                 if (e != JIM_OK)
4118                                         return e;
4119                                 target->working_area_phys = w;
4120                                 target->working_area_phys_spec = true;
4121                         } else {
4122                                 if (goi->argc != 0)
4123                                         goto no_params;
4124                         }
4125                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4126                         /* loop for more */
4127                         break;
4128
4129                 case TCFG_WORK_AREA_SIZE:
4130                         if (goi->isconfigure) {
4131                                 target_free_all_working_areas(target);
4132                                 e = Jim_GetOpt_Wide(goi, &w);
4133                                 if (e != JIM_OK)
4134                                         return e;
4135                                 target->working_area_size = w;
4136                         } else {
4137                                 if (goi->argc != 0)
4138                                         goto no_params;
4139                         }
4140                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4141                         /* loop for more */
4142                         break;
4143
4144                 case TCFG_WORK_AREA_BACKUP:
4145                         if (goi->isconfigure) {
4146                                 target_free_all_working_areas(target);
4147                                 e = Jim_GetOpt_Wide(goi, &w);
4148                                 if (e != JIM_OK)
4149                                         return e;
4150                                 /* make this exactly 1 or 0 */
4151                                 target->backup_working_area = (!!w);
4152                         } else {
4153                                 if (goi->argc != 0)
4154                                         goto no_params;
4155                         }
4156                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4157                         /* loop for more e*/
4158                         break;
4159
4160
4161                 case TCFG_ENDIAN:
4162                         if (goi->isconfigure) {
4163                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4164                                 if (e != JIM_OK) {
4165                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4166                                         return e;
4167                                 }
4168                                 target->endianness = n->value;
4169                         } else {
4170                                 if (goi->argc != 0)
4171                                         goto no_params;
4172                         }
4173                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4174                         if (n->name == NULL) {
4175                                 target->endianness = TARGET_LITTLE_ENDIAN;
4176                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4177                         }
4178                         Jim_SetResultString(goi->interp, n->name, -1);
4179                         /* loop for more */
4180                         break;
4181
4182                 case TCFG_VARIANT:
4183                         if (goi->isconfigure) {
4184                                 if (goi->argc < 1) {
4185                                         Jim_SetResultFormatted(goi->interp,
4186                                                                                    "%s ?STRING?",
4187                                                                                    n->name);
4188                                         return JIM_ERR;
4189                                 }
4190                                 if (target->variant)
4191                                         free((void *)(target->variant));
4192                                 e = Jim_GetOpt_String(goi, &cp, NULL);
4193                                 if (e != JIM_OK)
4194                                         return e;
4195                                 target->variant = strdup(cp);
4196                         } else {
4197                                 if (goi->argc != 0)
4198                                         goto no_params;
4199                         }
4200                         Jim_SetResultString(goi->interp, target->variant, -1);
4201                         /* loop for more */
4202                         break;
4203
4204                 case TCFG_COREID:
4205                         if (goi->isconfigure) {
4206                                 e = Jim_GetOpt_Wide(goi, &w);
4207                                 if (e != JIM_OK)
4208                                         return e;
4209                                 target->coreid = (int32_t)w;
4210                         } else {
4211                                 if (goi->argc != 0)
4212                                         goto no_params;
4213                         }
4214                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4215                         /* loop for more */
4216                         break;
4217
4218                 case TCFG_CHAIN_POSITION:
4219                         if (goi->isconfigure) {
4220                                 Jim_Obj *o_t;
4221                                 struct jtag_tap *tap;
4222                                 target_free_all_working_areas(target);
4223                                 e = Jim_GetOpt_Obj(goi, &o_t);
4224                                 if (e != JIM_OK)
4225                                         return e;
4226                                 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4227                                 if (tap == NULL)
4228                                         return JIM_ERR;
4229                                 /* make this exactly 1 or 0 */
4230                                 target->tap = tap;
4231                         } else {
4232                                 if (goi->argc != 0)
4233                                         goto no_params;
4234                         }
4235                         Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4236                         /* loop for more e*/
4237                         break;
4238                 case TCFG_DBGBASE:
4239                         if (goi->isconfigure) {
4240                                 e = Jim_GetOpt_Wide(goi, &w);
4241                                 if (e != JIM_OK)
4242                                         return e;
4243                                 target->dbgbase = (uint32_t)w;
4244                                 target->dbgbase_set = true;
4245                         } else {
4246                                 if (goi->argc != 0)
4247                                         goto no_params;
4248                         }
4249                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4250                         /* loop for more */
4251                         break;
4252
4253                 case TCFG_RTOS:
4254                         /* RTOS */
4255                         {
4256                                 int result = rtos_create(goi, target);
4257                                 if (result != JIM_OK)
4258                                         return result;
4259                         }
4260                         /* loop for more */
4261                         break;
4262                 }
4263         } /* while (goi->argc) */
4264
4265
4266                 /* done - we return */
4267         return JIM_OK;
4268 }
4269
4270 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4271 {
4272         Jim_GetOptInfo goi;
4273
4274         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4275         goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4276         int need_args = 1 + goi.isconfigure;
4277         if (goi.argc < need_args) {
4278                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4279                         goi.isconfigure
4280                                 ? "missing: -option VALUE ..."
4281                                 : "missing: -option ...");
4282                 return JIM_ERR;
4283         }
4284         struct target *target = Jim_CmdPrivData(goi.interp);
4285         return target_configure(&goi, target);
4286 }
4287
4288 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4289 {
4290         const char *cmd_name = Jim_GetString(argv[0], NULL);
4291
4292         Jim_GetOptInfo goi;
4293         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4294
4295         if (goi.argc < 2 || goi.argc > 4) {
4296                 Jim_SetResultFormatted(goi.interp,
4297                                 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4298                 return JIM_ERR;
4299         }
4300
4301         target_write_fn fn;
4302         fn = target_write_memory_fast;
4303
4304         int e;
4305         if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4306                 /* consume it */
4307                 struct Jim_Obj *obj;
4308                 e = Jim_GetOpt_Obj(&goi, &obj);
4309                 if (e != JIM_OK)
4310                         return e;
4311
4312                 fn = target_write_phys_memory;
4313         }
4314
4315         jim_wide a;
4316         e = Jim_GetOpt_Wide(&goi, &a);
4317         if (e != JIM_OK)
4318                 return e;
4319
4320         jim_wide b;
4321         e = Jim_GetOpt_Wide(&goi, &b);
4322         if (e != JIM_OK)
4323                 return e;
4324
4325         jim_wide c = 1;
4326         if (goi.argc == 1) {
4327                 e = Jim_GetOpt_Wide(&goi, &c);
4328                 if (e != JIM_OK)
4329                         return e;
4330         }
4331
4332         /* all args must be consumed */
4333         if (goi.argc != 0)
4334                 return JIM_ERR;
4335
4336         struct target *target = Jim_CmdPrivData(goi.interp);
4337         unsigned data_size;
4338         if (strcasecmp(cmd_name, "mww") == 0)
4339                 data_size = 4;
4340         else if (strcasecmp(cmd_name, "mwh") == 0)
4341                 data_size = 2;
4342         else if (strcasecmp(cmd_name, "mwb") == 0)
4343                 data_size = 1;
4344         else {
4345                 LOG_ERROR("command '%s' unknown: ", cmd_name);
4346                 return JIM_ERR;
4347         }
4348
4349         return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4350 }
4351
4352 /**
4353 *  @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4354 *
4355 *  Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4356 *         mdh [phys] <address> [<count>] - for 16 bit reads
4357 *         mdb [phys] <address> [<count>] - for  8 bit reads
4358 *
4359 *  Count defaults to 1.
4360 *
4361 *  Calls target_read_memory or target_read_phys_memory depending on
4362 *  the presence of the "phys" argument
4363 *  Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4364 *  to int representation in base16.
4365 *  Also outputs read data in a human readable form using command_print
4366 *
4367 *  @param phys if present target_read_phys_memory will be used instead of target_read_memory
4368 *  @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4369 *  @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4370 *  @returns:  JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4371 *  on success, with [<count>] number of elements.
4372 *
4373 *  In case of little endian target:
4374 *      Example1: "mdw 0x00000000"  returns "10123456"
4375 *      Exmaple2: "mdh 0x00000000 1" returns "3456"
4376 *      Example3: "mdb 0x00000000" returns "56"
4377 *      Example4: "mdh 0x00000000 2" returns "3456 1012"
4378 *      Example5: "mdb 0x00000000 3" returns "56 34 12"
4379 **/
4380 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4381 {
4382         const char *cmd_name = Jim_GetString(argv[0], NULL);
4383
4384         Jim_GetOptInfo goi;
4385         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4386
4387         if ((goi.argc < 1) || (goi.argc > 3)) {
4388                 Jim_SetResultFormatted(goi.interp,
4389                                 "usage: %s [phys] <address> [<count>]", cmd_name);
4390                 return JIM_ERR;
4391         }
4392
4393         int (*fn)(struct target *target,
4394                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4395         fn = target_read_memory;
4396
4397         int e;
4398         if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4399                 /* consume it */
4400                 struct Jim_Obj *obj;
4401                 e = Jim_GetOpt_Obj(&goi, &obj);
4402                 if (e != JIM_OK)
4403                         return e;
4404
4405                 fn = target_read_phys_memory;
4406         }
4407
4408         /* Read address parameter */
4409         jim_wide addr;
4410         e = Jim_GetOpt_Wide(&goi, &addr);
4411         if (e != JIM_OK)
4412                 return JIM_ERR;
4413
4414         /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4415         jim_wide count;
4416         if (goi.argc == 1) {
4417                 e = Jim_GetOpt_Wide(&goi, &count);
4418                 if (e != JIM_OK)
4419                         return JIM_ERR;
4420         } else
4421                 count = 1;
4422
4423         /* all args must be consumed */
4424         if (goi.argc != 0)
4425                 return JIM_ERR;
4426
4427         jim_wide dwidth = 1; /* shut up gcc */
4428         if (strcasecmp(cmd_name, "mdw") == 0)
4429                 dwidth = 4;
4430         else if (strcasecmp(cmd_name, "mdh") == 0)
4431                 dwidth = 2;
4432         else if (strcasecmp(cmd_name, "mdb") == 0)
4433                 dwidth = 1;
4434         else {
4435                 LOG_ERROR("command '%s' unknown: ", cmd_name);
4436                 return JIM_ERR;
4437         }
4438
4439         /* convert count to "bytes" */
4440         int bytes = count * dwidth;
4441
4442         struct target *target = Jim_CmdPrivData(goi.interp);
4443         uint8_t  target_buf[32];
4444         jim_wide x, y, z;
4445         while (bytes > 0) {
4446                 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4447
4448                 /* Try to read out next block */
4449                 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4450
4451                 if (e != ERROR_OK) {
4452                         Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4453                         return JIM_ERR;
4454                 }
4455
4456                 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4457                 switch (dwidth) {
4458                 case 4:
4459                         for (x = 0; x < 16 && x < y; x += 4) {
4460                                 z = target_buffer_get_u32(target, &(target_buf[x]));
4461                                 command_print_sameline(NULL, "%08x ", (int)(z));
4462                         }
4463                         for (; (x < 16) ; x += 4)
4464                                 command_print_sameline(NULL, "         ");
4465                         break;
4466                 case 2:
4467                         for (x = 0; x < 16 && x < y; x += 2) {
4468                                 z = target_buffer_get_u16(target, &(target_buf[x]));
4469                                 command_print_sameline(NULL, "%04x ", (int)(z));
4470                         }
4471                         for (; (x < 16) ; x += 2)
4472                                 command_print_sameline(NULL, "     ");
4473                         break;
4474                 case 1:
4475                 default:
4476                         for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4477                                 z = target_buffer_get_u8(target, &(target_buf[x]));
4478                                 command_print_sameline(NULL, "%02x ", (int)(z));
4479                         }
4480                         for (; (x < 16) ; x += 1)
4481                                 command_print_sameline(NULL, "   ");
4482                         break;
4483                 }
4484                 /* ascii-ify the bytes */
4485                 for (x = 0 ; x < y ; x++) {
4486                         if ((target_buf[x] >= 0x20) &&
4487                                 (target_buf[x] <= 0x7e)) {
4488                                 /* good */
4489                         } else {
4490                                 /* smack it */
4491                                 target_buf[x] = '.';
4492                         }
4493                 }
4494                 /* space pad  */
4495                 while (x < 16) {
4496                         target_buf[x] = ' ';
4497                         x++;
4498                 }
4499                 /* terminate */
4500                 target_buf[16] = 0;
4501                 /* print - with a newline */
4502                 command_print_sameline(NULL, "%s\n", target_buf);
4503                 /* NEXT... */
4504                 bytes -= 16;
4505                 addr += 16;
4506         }
4507         return JIM_OK;
4508 }
4509
4510 static int jim_target_mem2array(Jim_Interp *interp,
4511                 int argc, Jim_Obj *const *argv)
4512 {
4513         struct target *target = Jim_CmdPrivData(interp);
4514         return target_mem2array(interp, target, argc - 1, argv + 1);
4515 }
4516
4517 static int jim_target_array2mem(Jim_Interp *interp,
4518                 int argc, Jim_Obj *const *argv)
4519 {
4520         struct target *target = Jim_CmdPrivData(interp);
4521         return target_array2mem(interp, target, argc - 1, argv + 1);
4522 }
4523
4524 static int jim_target_tap_disabled(Jim_Interp *interp)
4525 {
4526         Jim_SetResultFormatted(interp, "[TAP is disabled]");
4527         return JIM_ERR;
4528 }
4529
4530 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4531 {
4532         if (argc != 1) {
4533                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4534                 return JIM_ERR;
4535         }
4536         struct target *target = Jim_CmdPrivData(interp);
4537         if (!target->tap->enabled)
4538                 return jim_target_tap_disabled(interp);
4539
4540         int e = target->type->examine(target);
4541         if (e != ERROR_OK)
4542                 return JIM_ERR;
4543         return JIM_OK;
4544 }
4545
4546 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4547 {
4548         if (argc != 1) {
4549                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4550                 return JIM_ERR;
4551         }
4552         struct target *target = Jim_CmdPrivData(interp);
4553
4554         if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4555                 return JIM_ERR;
4556
4557         return JIM_OK;
4558 }
4559
4560 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4561 {
4562         if (argc != 1) {
4563                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4564                 return JIM_ERR;
4565         }
4566         struct target *target = Jim_CmdPrivData(interp);
4567         if (!target->tap->enabled)
4568                 return jim_target_tap_disabled(interp);
4569
4570         int e;
4571         if (!(target_was_examined(target)))
4572                 e = ERROR_TARGET_NOT_EXAMINED;
4573         else
4574                 e = target->type->poll(target);
4575         if (e != ERROR_OK)
4576                 return JIM_ERR;
4577         return JIM_OK;
4578 }
4579
4580 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4581 {
4582         Jim_GetOptInfo goi;
4583         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4584
4585         if (goi.argc != 2) {
4586                 Jim_WrongNumArgs(interp, 0, argv,
4587                                 "([tT]|[fF]|assert|deassert) BOOL");
4588                 return JIM_ERR;
4589         }
4590
4591         Jim_Nvp *n;
4592         int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4593         if (e != JIM_OK) {
4594                 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4595                 return e;
4596         }
4597         /* the halt or not param */
4598         jim_wide a;
4599         e = Jim_GetOpt_Wide(&goi, &a);
4600         if (e != JIM_OK)
4601                 return e;
4602
4603         struct target *target = Jim_CmdPrivData(goi.interp);
4604         if (!target->tap->enabled)
4605                 return jim_target_tap_disabled(interp);
4606         if (!(target_was_examined(target))) {
4607                 LOG_ERROR("Target not examined yet");
4608                 return ERROR_TARGET_NOT_EXAMINED;
4609         }
4610         if (!target->type->assert_reset || !target->type->deassert_reset) {
4611                 Jim_SetResultFormatted(interp,
4612                                 "No target-specific reset for %s",
4613                                 target_name(target));
4614                 return JIM_ERR;
4615         }
4616         /* determine if we should halt or not. */
4617         target->reset_halt = !!a;
4618         /* When this happens - all workareas are invalid. */
4619         target_free_all_working_areas_restore(target, 0);
4620
4621         /* do the assert */
4622         if (n->value == NVP_ASSERT)
4623                 e = target->type->assert_reset(target);
4624         else
4625                 e = target->type->deassert_reset(target);
4626         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4627 }
4628
4629 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4630 {
4631         if (argc != 1) {
4632                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4633                 return JIM_ERR;
4634         }
4635         struct target *target = Jim_CmdPrivData(interp);
4636         if (!target->tap->enabled)
4637                 return jim_target_tap_disabled(interp);
4638         int e = target->type->halt(target);
4639         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4640 }
4641
4642 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4643 {
4644         Jim_GetOptInfo goi;
4645         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4646
4647         /* params:  <name>  statename timeoutmsecs */
4648         if (goi.argc != 2) {
4649                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4650                 Jim_SetResultFormatted(goi.interp,
4651                                 "%s <state_name> <timeout_in_msec>", cmd_name);
4652                 return JIM_ERR;
4653         }
4654
4655         Jim_Nvp *n;
4656         int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4657         if (e != JIM_OK) {
4658                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4659                 return e;
4660         }
4661         jim_wide a;
4662         e = Jim_GetOpt_Wide(&goi, &a);
4663         if (e != JIM_OK)
4664                 return e;
4665         struct target *target = Jim_CmdPrivData(interp);
4666         if (!target->tap->enabled)
4667                 return jim_target_tap_disabled(interp);
4668
4669         e = target_wait_state(target, n->value, a);
4670         if (e != ERROR_OK) {
4671                 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4672                 Jim_SetResultFormatted(goi.interp,
4673                                 "target: %s wait %s fails (%#s) %s",
4674                                 target_name(target), n->name,
4675                                 eObj, target_strerror_safe(e));
4676                 Jim_FreeNewObj(interp, eObj);
4677                 return JIM_ERR;
4678         }
4679         return JIM_OK;
4680 }
4681 /* List for human, Events defined for this target.
4682  * scripts/programs should use 'name cget -event NAME'
4683  */
4684 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4685 {
4686         struct command_context *cmd_ctx = current_command_context(interp);
4687         assert(cmd_ctx != NULL);
4688
4689         struct target *target = Jim_CmdPrivData(interp);
4690         struct target_event_action *teap = target->event_action;
4691         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4692                                    target->target_number,
4693                                    target_name(target));
4694         command_print(cmd_ctx, "%-25s | Body", "Event");
4695         command_print(cmd_ctx, "------------------------- | "
4696                         "----------------------------------------");
4697         while (teap) {
4698                 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4699                 command_print(cmd_ctx, "%-25s | %s",
4700                                 opt->name, Jim_GetString(teap->body, NULL));
4701                 teap = teap->next;
4702         }
4703         command_print(cmd_ctx, "***END***");
4704         return JIM_OK;
4705 }
4706 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4707 {
4708         if (argc != 1) {
4709                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4710                 return JIM_ERR;
4711         }
4712         struct target *target = Jim_CmdPrivData(interp);
4713         Jim_SetResultString(interp, target_state_name(target), -1);
4714         return JIM_OK;
4715 }
4716 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4717 {
4718         Jim_GetOptInfo goi;
4719         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4720         if (goi.argc != 1) {
4721                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4722                 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4723                 return JIM_ERR;
4724         }
4725         Jim_Nvp *n;
4726         int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4727         if (e != JIM_OK) {
4728                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4729                 return e;
4730         }
4731         struct target *target = Jim_CmdPrivData(interp);
4732         target_handle_event(target, n->value);
4733         return JIM_OK;
4734 }
4735
4736 static const struct command_registration target_instance_command_handlers[] = {
4737         {
4738                 .name = "configure",
4739                 .mode = COMMAND_CONFIG,
4740                 .jim_handler = jim_target_configure,
4741                 .help  = "configure a new target for use",
4742                 .usage = "[target_attribute ...]",
4743         },
4744         {
4745                 .name = "cget",
4746                 .mode = COMMAND_ANY,
4747                 .jim_handler = jim_target_configure,
4748                 .help  = "returns the specified target attribute",
4749                 .usage = "target_attribute",
4750         },
4751         {
4752                 .name = "mww",
4753                 .mode = COMMAND_EXEC,
4754                 .jim_handler = jim_target_mw,
4755                 .help = "Write 32-bit word(s) to target memory",
4756                 .usage = "address data [count]",
4757         },
4758         {
4759                 .name = "mwh",
4760                 .mode = COMMAND_EXEC,
4761                 .jim_handler = jim_target_mw,
4762                 .help = "Write 16-bit half-word(s) to target memory",
4763                 .usage = "address data [count]",
4764         },
4765         {
4766                 .name = "mwb",
4767                 .mode = COMMAND_EXEC,
4768                 .jim_handler = jim_target_mw,
4769                 .help = "Write byte(s) to target memory",
4770                 .usage = "address data [count]",
4771         },
4772         {
4773                 .name = "mdw",
4774                 .mode = COMMAND_EXEC,
4775                 .jim_handler = jim_target_md,
4776                 .help = "Display target memory as 32-bit words",
4777                 .usage = "address [count]",
4778         },
4779         {
4780                 .name = "mdh",
4781                 .mode = COMMAND_EXEC,
4782                 .jim_handler = jim_target_md,
4783                 .help = "Display target memory as 16-bit half-words",
4784                 .usage = "address [count]",
4785         },
4786         {
4787                 .name = "mdb",
4788                 .mode = COMMAND_EXEC,
4789                 .jim_handler = jim_target_md,
4790                 .help = "Display target memory as 8-bit bytes",
4791                 .usage = "address [count]",
4792         },
4793         {
4794                 .name = "array2mem",
4795                 .mode = COMMAND_EXEC,
4796                 .jim_handler = jim_target_array2mem,
4797                 .help = "Writes Tcl array of 8/16/32 bit numbers "
4798                         "to target memory",
4799                 .usage = "arrayname bitwidth address count",
4800         },
4801         {
4802                 .name = "mem2array",
4803                 .mode = COMMAND_EXEC,
4804                 .jim_handler = jim_target_mem2array,
4805                 .help = "Loads Tcl array of 8/16/32 bit numbers "
4806                         "from target memory",
4807                 .usage = "arrayname bitwidth address count",
4808         },
4809         {
4810                 .name = "eventlist",
4811                 .mode = COMMAND_EXEC,
4812                 .jim_handler = jim_target_event_list,
4813                 .help = "displays a table of events defined for this target",
4814         },
4815         {
4816                 .name = "curstate",
4817                 .mode = COMMAND_EXEC,
4818                 .jim_handler = jim_target_current_state,
4819                 .help = "displays the current state of this target",
4820         },
4821         {
4822                 .name = "arp_examine",
4823                 .mode = COMMAND_EXEC,
4824                 .jim_handler = jim_target_examine,
4825                 .help = "used internally for reset processing",
4826         },
4827         {
4828                 .name = "arp_halt_gdb",
4829                 .mode = COMMAND_EXEC,
4830                 .jim_handler = jim_target_halt_gdb,
4831                 .help = "used internally for reset processing to halt GDB",
4832         },
4833         {
4834                 .name = "arp_poll",
4835                 .mode = COMMAND_EXEC,
4836                 .jim_handler = jim_target_poll,
4837                 .help = "used internally for reset processing",
4838         },
4839         {
4840                 .name = "arp_reset",
4841                 .mode = COMMAND_EXEC,
4842                 .jim_handler = jim_target_reset,
4843                 .help = "used internally for reset processing",
4844         },
4845         {
4846                 .name = "arp_halt",
4847                 .mode = COMMAND_EXEC,
4848                 .jim_handler = jim_target_halt,
4849                 .help = "used internally for reset processing",
4850         },
4851         {
4852                 .name = "arp_waitstate",
4853                 .mode = COMMAND_EXEC,
4854                 .jim_handler = jim_target_wait_state,
4855                 .help = "used internally for reset processing",
4856         },
4857         {
4858                 .name = "invoke-event",
4859                 .mode = COMMAND_EXEC,
4860                 .jim_handler = jim_target_invoke_event,
4861                 .help = "invoke handler for specified event",
4862                 .usage = "event_name",
4863         },
4864         COMMAND_REGISTRATION_DONE
4865 };
4866
4867 static int target_create(Jim_GetOptInfo *goi)
4868 {
4869         Jim_Obj *new_cmd;
4870         Jim_Cmd *cmd;
4871         const char *cp;
4872         char *cp2;
4873         int e;
4874         int x;
4875         struct target *target;
4876         struct command_context *cmd_ctx;
4877
4878         cmd_ctx = current_command_context(goi->interp);
4879         assert(cmd_ctx != NULL);
4880
4881         if (goi->argc < 3) {
4882                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4883                 return JIM_ERR;
4884         }
4885
4886         /* COMMAND */
4887         Jim_GetOpt_Obj(goi, &new_cmd);
4888         /* does this command exist? */
4889         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4890         if (cmd) {
4891                 cp = Jim_GetString(new_cmd, NULL);
4892                 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4893                 return JIM_ERR;
4894         }
4895
4896         /* TYPE */
4897         e = Jim_GetOpt_String(goi, &cp2, NULL);
4898         if (e != JIM_OK)
4899                 return e;
4900         cp = cp2;
4901         /* now does target type exist */
4902         for (x = 0 ; target_types[x] ; x++) {
4903                 if (0 == strcmp(cp, target_types[x]->name)) {
4904                         /* found */
4905                         break;
4906                 }
4907
4908                 /* check for deprecated name */
4909                 if (target_types[x]->deprecated_name) {
4910                         if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
4911                                 /* found */
4912                                 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
4913                                 break;
4914                         }
4915                 }
4916         }
4917         if (target_types[x] == NULL) {
4918                 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4919                 for (x = 0 ; target_types[x] ; x++) {
4920                         if (target_types[x + 1]) {
4921                                 Jim_AppendStrings(goi->interp,
4922                                                                    Jim_GetResult(goi->interp),
4923                                                                    target_types[x]->name,
4924                                                                    ", ", NULL);
4925                         } else {
4926                                 Jim_AppendStrings(goi->interp,
4927                                                                    Jim_GetResult(goi->interp),
4928                                                                    " or ",
4929                                                                    target_types[x]->name, NULL);
4930                         }
4931                 }
4932                 return JIM_ERR;
4933         }
4934
4935         /* Create it */
4936         target = calloc(1, sizeof(struct target));
4937         /* set target number */
4938         target->target_number = new_target_number();
4939
4940         /* allocate memory for each unique target type */
4941         target->type = (struct target_type *)calloc(1, sizeof(struct target_type));
4942
4943         memcpy(target->type, target_types[x], sizeof(struct target_type));
4944
4945         /* will be set by "-endian" */
4946         target->endianness = TARGET_ENDIAN_UNKNOWN;
4947
4948         /* default to first core, override with -coreid */
4949         target->coreid = 0;
4950
4951         target->working_area        = 0x0;
4952         target->working_area_size   = 0x0;
4953         target->working_areas       = NULL;
4954         target->backup_working_area = 0;
4955
4956         target->state               = TARGET_UNKNOWN;
4957         target->debug_reason        = DBG_REASON_UNDEFINED;
4958         target->reg_cache           = NULL;
4959         target->breakpoints         = NULL;
4960         target->watchpoints         = NULL;
4961         target->next                = NULL;
4962         target->arch_info           = NULL;
4963
4964         target->display             = 1;
4965
4966         target->halt_issued                     = false;
4967
4968         /* initialize trace information */
4969         target->trace_info = malloc(sizeof(struct trace));
4970         target->trace_info->num_trace_points         = 0;
4971         target->trace_info->trace_points_size        = 0;
4972         target->trace_info->trace_points             = NULL;
4973         target->trace_info->trace_history_size       = 0;
4974         target->trace_info->trace_history            = NULL;
4975         target->trace_info->trace_history_pos        = 0;
4976         target->trace_info->trace_history_overflowed = 0;
4977
4978         target->dbgmsg          = NULL;
4979         target->dbg_msg_enabled = 0;
4980
4981         target->endianness = TARGET_ENDIAN_UNKNOWN;
4982
4983         target->rtos = NULL;
4984         target->rtos_auto_detect = false;
4985
4986         /* Do the rest as "configure" options */
4987         goi->isconfigure = 1;
4988         e = target_configure(goi, target);
4989
4990         if (target->tap == NULL) {
4991                 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4992                 e = JIM_ERR;
4993         }
4994
4995         if (e != JIM_OK) {
4996                 free(target->type);
4997                 free(target);
4998                 return e;
4999         }
5000
5001         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5002                 /* default endian to little if not specified */
5003                 target->endianness = TARGET_LITTLE_ENDIAN;
5004         }
5005
5006         /* incase variant is not set */
5007         if (!target->variant)
5008                 target->variant = strdup("");
5009
5010         cp = Jim_GetString(new_cmd, NULL);
5011         target->cmd_name = strdup(cp);
5012
5013         /* create the target specific commands */
5014         if (target->type->commands) {
5015                 e = register_commands(cmd_ctx, NULL, target->type->commands);
5016                 if (ERROR_OK != e)
5017                         LOG_ERROR("unable to register '%s' commands", cp);
5018         }
5019         if (target->type->target_create)
5020                 (*(target->type->target_create))(target, goi->interp);
5021
5022         /* append to end of list */
5023         {
5024                 struct target **tpp;
5025                 tpp = &(all_targets);
5026                 while (*tpp)
5027                         tpp = &((*tpp)->next);
5028                 *tpp = target;
5029         }
5030
5031         /* now - create the new target name command */
5032         const const struct command_registration target_subcommands[] = {
5033                 {
5034                         .chain = target_instance_command_handlers,
5035                 },
5036                 {
5037                         .chain = target->type->commands,
5038                 },
5039                 COMMAND_REGISTRATION_DONE
5040         };
5041         const const struct command_registration target_commands[] = {
5042                 {
5043                         .name = cp,
5044                         .mode = COMMAND_ANY,
5045                         .help = "target command group",
5046                         .usage = "",
5047                         .chain = target_subcommands,
5048                 },
5049                 COMMAND_REGISTRATION_DONE
5050         };
5051         e = register_commands(cmd_ctx, NULL, target_commands);
5052         if (ERROR_OK != e)
5053                 return JIM_ERR;
5054
5055         struct command *c = command_find_in_context(cmd_ctx, cp);
5056         assert(c);
5057         command_set_handler_data(c, target);
5058
5059         return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5060 }
5061
5062 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5063 {
5064         if (argc != 1) {
5065                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5066                 return JIM_ERR;
5067         }
5068         struct command_context *cmd_ctx = current_command_context(interp);
5069         assert(cmd_ctx != NULL);
5070
5071         Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5072         return JIM_OK;
5073 }
5074
5075 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5076 {
5077         if (argc != 1) {
5078                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5079                 return JIM_ERR;
5080         }
5081         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5082         for (unsigned x = 0; NULL != target_types[x]; x++) {
5083                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5084                         Jim_NewStringObj(interp, target_types[x]->name, -1));
5085         }
5086         return JIM_OK;
5087 }
5088
5089 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5090 {
5091         if (argc != 1) {
5092                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5093                 return JIM_ERR;
5094         }
5095         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5096         struct target *target = all_targets;
5097         while (target) {
5098                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5099                         Jim_NewStringObj(interp, target_name(target), -1));
5100                 target = target->next;
5101         }
5102         return JIM_OK;
5103 }
5104
5105 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5106 {
5107         int i;
5108         const char *targetname;
5109         int retval, len;
5110         struct target *target = (struct target *) NULL;
5111         struct target_list *head, *curr, *new;
5112         curr = (struct target_list *) NULL;
5113         head = (struct target_list *) NULL;
5114
5115         retval = 0;
5116         LOG_DEBUG("%d", argc);
5117         /* argv[1] = target to associate in smp
5118          * argv[2] = target to assoicate in smp
5119          * argv[3] ...
5120          */
5121
5122         for (i = 1; i < argc; i++) {
5123
5124                 targetname = Jim_GetString(argv[i], &len);
5125                 target = get_target(targetname);
5126                 LOG_DEBUG("%s ", targetname);
5127                 if (target) {
5128                         new = malloc(sizeof(struct target_list));
5129                         new->target = target;
5130                         new->next = (struct target_list *)NULL;
5131                         if (head == (struct target_list *)NULL) {
5132                                 head = new;
5133                                 curr = head;
5134                         } else {
5135                                 curr->next = new;
5136                                 curr = new;
5137                         }
5138                 }
5139         }
5140         /*  now parse the list of cpu and put the target in smp mode*/
5141         curr = head;
5142
5143         while (curr != (struct target_list *)NULL) {
5144                 target = curr->target;
5145                 target->smp = 1;
5146                 target->head = head;
5147                 curr = curr->next;
5148         }
5149
5150         if (target && target->rtos)
5151                 retval = rtos_smp_init(head->target);
5152
5153         return retval;
5154 }
5155
5156
5157 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5158 {
5159         Jim_GetOptInfo goi;
5160         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5161         if (goi.argc < 3) {
5162                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5163                         "<name> <target_type> [<target_options> ...]");
5164                 return JIM_ERR;
5165         }
5166         return target_create(&goi);
5167 }
5168
5169 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5170 {
5171         Jim_GetOptInfo goi;
5172         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5173
5174         /* It's OK to remove this mechanism sometime after August 2010 or so */
5175         LOG_WARNING("don't use numbers as target identifiers; use names");
5176         if (goi.argc != 1) {
5177                 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5178                 return JIM_ERR;
5179         }
5180         jim_wide w;
5181         int e = Jim_GetOpt_Wide(&goi, &w);
5182         if (e != JIM_OK)
5183                 return JIM_ERR;
5184
5185         struct target *target;
5186         for (target = all_targets; NULL != target; target = target->next) {
5187                 if (target->target_number != w)
5188                         continue;
5189
5190                 Jim_SetResultString(goi.interp, target_name(target), -1);
5191                 return JIM_OK;
5192         }
5193         {
5194                 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5195                 Jim_SetResultFormatted(goi.interp,
5196                         "Target: number %#s does not exist", wObj);
5197                 Jim_FreeNewObj(interp, wObj);
5198         }
5199         return JIM_ERR;
5200 }
5201
5202 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5203 {
5204         if (argc != 1) {
5205                 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5206                 return JIM_ERR;
5207         }
5208         unsigned count = 0;
5209         struct target *target = all_targets;
5210         while (NULL != target) {
5211                 target = target->next;
5212                 count++;
5213         }
5214         Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5215         return JIM_OK;
5216 }
5217
5218 static const struct command_registration target_subcommand_handlers[] = {
5219         {
5220                 .name = "init",
5221                 .mode = COMMAND_CONFIG,
5222                 .handler = handle_target_init_command,
5223                 .help = "initialize targets",
5224         },
5225         {
5226                 .name = "create",
5227                 /* REVISIT this should be COMMAND_CONFIG ... */
5228                 .mode = COMMAND_ANY,
5229                 .jim_handler = jim_target_create,
5230                 .usage = "name type '-chain-position' name [options ...]",
5231                 .help = "Creates and selects a new target",
5232         },
5233         {
5234                 .name = "current",
5235                 .mode = COMMAND_ANY,
5236                 .jim_handler = jim_target_current,
5237                 .help = "Returns the currently selected target",
5238         },
5239         {
5240                 .name = "types",
5241                 .mode = COMMAND_ANY,
5242                 .jim_handler = jim_target_types,
5243                 .help = "Returns the available target types as "
5244                                 "a list of strings",
5245         },
5246         {
5247                 .name = "names",
5248                 .mode = COMMAND_ANY,
5249                 .jim_handler = jim_target_names,
5250                 .help = "Returns the names of all targets as a list of strings",
5251         },
5252         {
5253                 .name = "number",
5254                 .mode = COMMAND_ANY,
5255                 .jim_handler = jim_target_number,
5256                 .usage = "number",
5257                 .help = "Returns the name of the numbered target "
5258                         "(DEPRECATED)",
5259         },
5260         {
5261                 .name = "count",
5262                 .mode = COMMAND_ANY,
5263                 .jim_handler = jim_target_count,
5264                 .help = "Returns the number of targets as an integer "
5265                         "(DEPRECATED)",
5266         },
5267         {
5268                 .name = "smp",
5269                 .mode = COMMAND_ANY,
5270                 .jim_handler = jim_target_smp,
5271                 .usage = "targetname1 targetname2 ...",
5272                 .help = "gather several target in a smp list"
5273         },
5274
5275         COMMAND_REGISTRATION_DONE
5276 };
5277
5278 struct FastLoad {
5279         uint32_t address;
5280         uint8_t *data;
5281         int length;
5282
5283 };
5284
5285 static int fastload_num;
5286 static struct FastLoad *fastload;
5287
5288 static void free_fastload(void)
5289 {
5290         if (fastload != NULL) {
5291                 int i;
5292                 for (i = 0; i < fastload_num; i++) {
5293                         if (fastload[i].data)
5294                                 free(fastload[i].data);
5295                 }
5296                 free(fastload);
5297                 fastload = NULL;
5298         }
5299 }
5300
5301 COMMAND_HANDLER(handle_fast_load_image_command)
5302 {
5303         uint8_t *buffer;
5304         size_t buf_cnt;
5305         uint32_t image_size;
5306         uint32_t min_address = 0;
5307         uint32_t max_address = 0xffffffff;
5308         int i;
5309
5310         struct image image;
5311
5312         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5313                         &image, &min_address, &max_address);
5314         if (ERROR_OK != retval)
5315                 return retval;
5316
5317         struct duration bench;
5318         duration_start(&bench);
5319
5320         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5321         if (retval != ERROR_OK)
5322                 return retval;
5323
5324         image_size = 0x0;
5325         retval = ERROR_OK;
5326         fastload_num = image.num_sections;
5327         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5328         if (fastload == NULL) {
5329                 command_print(CMD_CTX, "out of memory");
5330                 image_close(&image);
5331                 return ERROR_FAIL;
5332         }
5333         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5334         for (i = 0; i < image.num_sections; i++) {
5335                 buffer = malloc(image.sections[i].size);
5336                 if (buffer == NULL) {
5337                         command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5338                                                   (int)(image.sections[i].size));
5339                         retval = ERROR_FAIL;
5340                         break;
5341                 }
5342
5343                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5344                 if (retval != ERROR_OK) {
5345                         free(buffer);
5346                         break;
5347                 }
5348
5349                 uint32_t offset = 0;
5350                 uint32_t length = buf_cnt;
5351
5352                 /* DANGER!!! beware of unsigned comparision here!!! */
5353
5354                 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5355                                 (image.sections[i].base_address < max_address)) {
5356                         if (image.sections[i].base_address < min_address) {
5357                                 /* clip addresses below */
5358                                 offset += min_address-image.sections[i].base_address;
5359                                 length -= offset;
5360                         }
5361
5362                         if (image.sections[i].base_address + buf_cnt > max_address)
5363                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5364
5365                         fastload[i].address = image.sections[i].base_address + offset;
5366                         fastload[i].data = malloc(length);
5367                         if (fastload[i].data == NULL) {
5368                                 free(buffer);
5369                                 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5370                                                           length);
5371                                 retval = ERROR_FAIL;
5372                                 break;
5373                         }
5374                         memcpy(fastload[i].data, buffer + offset, length);
5375                         fastload[i].length = length;
5376
5377                         image_size += length;
5378                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5379                                                   (unsigned int)length,
5380                                                   ((unsigned int)(image.sections[i].base_address + offset)));
5381                 }
5382
5383                 free(buffer);
5384         }
5385
5386         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5387                 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5388                                 "in %fs (%0.3f KiB/s)", image_size,
5389                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5390
5391                 command_print(CMD_CTX,
5392                                 "WARNING: image has not been loaded to target!"
5393                                 "You can issue a 'fast_load' to finish loading.");
5394         }
5395
5396         image_close(&image);
5397
5398         if (retval != ERROR_OK)
5399                 free_fastload();
5400
5401         return retval;
5402 }
5403
5404 COMMAND_HANDLER(handle_fast_load_command)
5405 {
5406         if (CMD_ARGC > 0)
5407                 return ERROR_COMMAND_SYNTAX_ERROR;
5408         if (fastload == NULL) {
5409                 LOG_ERROR("No image in memory");
5410                 return ERROR_FAIL;
5411         }
5412         int i;
5413         int ms = timeval_ms();
5414         int size = 0;
5415         int retval = ERROR_OK;
5416         for (i = 0; i < fastload_num; i++) {
5417                 struct target *target = get_current_target(CMD_CTX);
5418                 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5419                                           (unsigned int)(fastload[i].address),
5420                                           (unsigned int)(fastload[i].length));
5421                 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5422                 if (retval != ERROR_OK)
5423                         break;
5424                 size += fastload[i].length;
5425         }
5426         if (retval == ERROR_OK) {
5427                 int after = timeval_ms();
5428                 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5429         }
5430         return retval;
5431 }
5432
5433 static const struct command_registration target_command_handlers[] = {
5434         {
5435                 .name = "targets",
5436                 .handler = handle_targets_command,
5437                 .mode = COMMAND_ANY,
5438                 .help = "change current default target (one parameter) "
5439                         "or prints table of all targets (no parameters)",
5440                 .usage = "[target]",
5441         },
5442         {
5443                 .name = "target",
5444                 .mode = COMMAND_CONFIG,
5445                 .help = "configure target",
5446
5447                 .chain = target_subcommand_handlers,
5448         },
5449         COMMAND_REGISTRATION_DONE
5450 };
5451
5452 int target_register_commands(struct command_context *cmd_ctx)
5453 {
5454         return register_commands(cmd_ctx, NULL, target_command_handlers);
5455 }
5456
5457 static bool target_reset_nag = true;
5458
5459 bool get_target_reset_nag(void)
5460 {
5461         return target_reset_nag;
5462 }
5463
5464 COMMAND_HANDLER(handle_target_reset_nag)
5465 {
5466         return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5467                         &target_reset_nag, "Nag after each reset about options to improve "
5468                         "performance");
5469 }
5470
5471 COMMAND_HANDLER(handle_ps_command)
5472 {
5473         struct target *target = get_current_target(CMD_CTX);
5474         char *display;
5475         if (target->state != TARGET_HALTED) {
5476                 LOG_INFO("target not halted !!");
5477                 return ERROR_OK;
5478         }
5479
5480         if ((target->rtos) && (target->rtos->type)
5481                         && (target->rtos->type->ps_command)) {
5482                 display = target->rtos->type->ps_command(target);
5483                 command_print(CMD_CTX, "%s", display);
5484                 free(display);
5485                 return ERROR_OK;
5486         } else {
5487                 LOG_INFO("failed");
5488                 return ERROR_TARGET_FAILURE;
5489         }
5490 }
5491
5492 static const struct command_registration target_exec_command_handlers[] = {
5493         {
5494                 .name = "fast_load_image",
5495                 .handler = handle_fast_load_image_command,
5496                 .mode = COMMAND_ANY,
5497                 .help = "Load image into server memory for later use by "
5498                         "fast_load; primarily for profiling",
5499                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5500                         "[min_address [max_length]]",
5501         },
5502         {
5503                 .name = "fast_load",
5504                 .handler = handle_fast_load_command,
5505                 .mode = COMMAND_EXEC,
5506                 .help = "loads active fast load image to current target "
5507                         "- mainly for profiling purposes",
5508                 .usage = "",
5509         },
5510         {
5511                 .name = "profile",
5512                 .handler = handle_profile_command,
5513                 .mode = COMMAND_EXEC,
5514                 .usage = "seconds filename",
5515                 .help = "profiling samples the CPU PC",
5516         },
5517         /** @todo don't register virt2phys() unless target supports it */
5518         {
5519                 .name = "virt2phys",
5520                 .handler = handle_virt2phys_command,
5521                 .mode = COMMAND_ANY,
5522                 .help = "translate a virtual address into a physical address",
5523                 .usage = "virtual_address",
5524         },
5525         {
5526                 .name = "reg",
5527                 .handler = handle_reg_command,
5528                 .mode = COMMAND_EXEC,
5529                 .help = "display or set a register; with no arguments, "
5530                         "displays all registers and their values",
5531                 .usage = "[(register_name|register_number) [value]]",
5532         },
5533         {
5534                 .name = "poll",
5535                 .handler = handle_poll_command,
5536                 .mode = COMMAND_EXEC,
5537                 .help = "poll target state; or reconfigure background polling",
5538                 .usage = "['on'|'off']",
5539         },
5540         {
5541                 .name = "wait_halt",
5542                 .handler = handle_wait_halt_command,
5543                 .mode = COMMAND_EXEC,
5544                 .help = "wait up to the specified number of milliseconds "
5545                         "(default 5) for a previously requested halt",
5546                 .usage = "[milliseconds]",
5547         },
5548         {
5549                 .name = "halt",
5550                 .handler = handle_halt_command,
5551                 .mode = COMMAND_EXEC,
5552                 .help = "request target to halt, then wait up to the specified"
5553                         "number of milliseconds (default 5) for it to complete",
5554                 .usage = "[milliseconds]",
5555         },
5556         {
5557                 .name = "resume",
5558                 .handler = handle_resume_command,
5559                 .mode = COMMAND_EXEC,
5560                 .help = "resume target execution from current PC or address",
5561                 .usage = "[address]",
5562         },
5563         {
5564                 .name = "reset",
5565                 .handler = handle_reset_command,
5566                 .mode = COMMAND_EXEC,
5567                 .usage = "[run|halt|init]",
5568                 .help = "Reset all targets into the specified mode."
5569                         "Default reset mode is run, if not given.",
5570         },
5571         {
5572                 .name = "soft_reset_halt",
5573                 .handler = handle_soft_reset_halt_command,
5574                 .mode = COMMAND_EXEC,
5575                 .usage = "",
5576                 .help = "halt the target and do a soft reset",
5577         },
5578         {
5579                 .name = "step",
5580                 .handler = handle_step_command,
5581                 .mode = COMMAND_EXEC,
5582                 .help = "step one instruction from current PC or address",
5583                 .usage = "[address]",
5584         },
5585         {
5586                 .name = "mdw",
5587                 .handler = handle_md_command,
5588                 .mode = COMMAND_EXEC,
5589                 .help = "display memory words",
5590                 .usage = "['phys'] address [count]",
5591         },
5592         {
5593                 .name = "mdh",
5594                 .handler = handle_md_command,
5595                 .mode = COMMAND_EXEC,
5596                 .help = "display memory half-words",
5597                 .usage = "['phys'] address [count]",
5598         },
5599         {
5600                 .name = "mdb",
5601                 .handler = handle_md_command,
5602                 .mode = COMMAND_EXEC,
5603                 .help = "display memory bytes",
5604                 .usage = "['phys'] address [count]",
5605         },
5606         {
5607                 .name = "mww",
5608                 .handler = handle_mw_command,
5609                 .mode = COMMAND_EXEC,
5610                 .help = "write memory word",
5611                 .usage = "['phys'] address value [count]",
5612         },
5613         {
5614                 .name = "mwh",
5615                 .handler = handle_mw_command,
5616                 .mode = COMMAND_EXEC,
5617                 .help = "write memory half-word",
5618                 .usage = "['phys'] address value [count]",
5619         },
5620         {
5621                 .name = "mwb",
5622                 .handler = handle_mw_command,
5623                 .mode = COMMAND_EXEC,
5624                 .help = "write memory byte",
5625                 .usage = "['phys'] address value [count]",
5626         },
5627         {
5628                 .name = "bp",
5629                 .handler = handle_bp_command,
5630                 .mode = COMMAND_EXEC,
5631                 .help = "list or set hardware or software breakpoint",
5632                 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5633         },
5634         {
5635                 .name = "rbp",
5636                 .handler = handle_rbp_command,
5637                 .mode = COMMAND_EXEC,
5638                 .help = "remove breakpoint",
5639                 .usage = "address",
5640         },
5641         {
5642                 .name = "wp",
5643                 .handler = handle_wp_command,
5644                 .mode = COMMAND_EXEC,
5645                 .help = "list (no params) or create watchpoints",
5646                 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5647         },
5648         {
5649                 .name = "rwp",
5650                 .handler = handle_rwp_command,
5651                 .mode = COMMAND_EXEC,
5652                 .help = "remove watchpoint",
5653                 .usage = "address",
5654         },
5655         {
5656                 .name = "load_image",
5657                 .handler = handle_load_image_command,
5658                 .mode = COMMAND_EXEC,
5659                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5660                         "[min_address] [max_length]",
5661         },
5662         {
5663                 .name = "dump_image",
5664                 .handler = handle_dump_image_command,
5665                 .mode = COMMAND_EXEC,
5666                 .usage = "filename address size",
5667         },
5668         {
5669                 .name = "verify_image",
5670                 .handler = handle_verify_image_command,
5671                 .mode = COMMAND_EXEC,
5672                 .usage = "filename [offset [type]]",
5673         },
5674         {
5675                 .name = "test_image",
5676                 .handler = handle_test_image_command,
5677                 .mode = COMMAND_EXEC,
5678                 .usage = "filename [offset [type]]",
5679         },
5680         {
5681                 .name = "mem2array",
5682                 .mode = COMMAND_EXEC,
5683                 .jim_handler = jim_mem2array,
5684                 .help = "read 8/16/32 bit memory and return as a TCL array "
5685                         "for script processing",
5686                 .usage = "arrayname bitwidth address count",
5687         },
5688         {
5689                 .name = "array2mem",
5690                 .mode = COMMAND_EXEC,
5691                 .jim_handler = jim_array2mem,
5692                 .help = "convert a TCL array to memory locations "
5693                         "and write the 8/16/32 bit values",
5694                 .usage = "arrayname bitwidth address count",
5695         },
5696         {
5697                 .name = "reset_nag",
5698                 .handler = handle_target_reset_nag,
5699                 .mode = COMMAND_ANY,
5700                 .help = "Nag after each reset about options that could have been "
5701                                 "enabled to improve performance. ",
5702                 .usage = "['enable'|'disable']",
5703         },
5704         {
5705                 .name = "ps",
5706                 .handler = handle_ps_command,
5707                 .mode = COMMAND_EXEC,
5708                 .help = "list all tasks ",
5709                 .usage = " ",
5710         },
5711
5712         COMMAND_REGISTRATION_DONE
5713 };
5714 static int target_register_user_commands(struct command_context *cmd_ctx)
5715 {
5716         int retval = ERROR_OK;
5717         retval = target_request_register_commands(cmd_ctx);
5718         if (retval != ERROR_OK)
5719                 return retval;
5720
5721         retval = trace_register_commands(cmd_ctx);
5722         if (retval != ERROR_OK)
5723                 return retval;
5724
5725
5726         return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
5727 }