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