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