]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/jlink.c
jlink: Update for libjaylink API changes
[openocd] / src / jtag / drivers / jlink.c
1 /***************************************************************************
2  *   Copyright (C) 2007 by Juergen Stuber <juergen@jstuber.net>            *
3  *   based on Dominic Rath's and Benedikt Sauter's usbprog.c               *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   Copyright (C) 2011 by Jean-Christophe PLAGNIOL-VIILARD                *
9  *   plagnioj@jcrosoft.com                                                 *
10  *                                                                         *
11  *   Copyright (C) 2015 by Marc Schink                                     *
12  *   openocd-dev@marcschink.de                                             *
13  *                                                                         *
14  *   Copyright (C) 2015 by Paul Fertser                                    *
15  *   fercerpav@gmail.com                                                   *
16  *                                                                         *
17  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program; if not, write to the                         *
29  *   Free Software Foundation, Inc.,                                       *
30  ***************************************************************************/
31
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include <stdint.h>
37 #include <math.h>
38
39 #include <jtag/interface.h>
40 #include <jtag/swd.h>
41 #include <jtag/commands.h>
42
43 #include <libjaylink/libjaylink.h>
44
45 static struct jaylink_context *jayctx;
46 static struct jaylink_device_handle *devh;
47 static struct jaylink_connection conn;
48 static struct jaylink_connection connlist[JAYLINK_MAX_CONNECTIONS];
49 static enum jaylink_jtag_version jtag_command_version;
50 static uint8_t caps[JAYLINK_DEV_EXT_CAPS_SIZE];
51
52 static uint32_t serial_number;
53 static bool use_serial_number;
54 static enum jaylink_usb_address usb_address;
55 static bool use_usb_address;
56 static enum jaylink_target_interface iface = JAYLINK_TIF_JTAG;
57 static bool trace_enabled;
58
59 #define JLINK_MAX_SPEED                 12000
60 #define JLINK_TAP_BUFFER_SIZE   2048
61
62 static unsigned int swd_buffer_size = JLINK_TAP_BUFFER_SIZE;
63
64 /* 256 byte non-volatile memory */
65 struct device_config {
66         uint8_t usb_address;
67         /* 0ffset 0x01 to 0x03 */
68         uint8_t reserved_1[3];
69         uint32_t target_power;
70         /* 0ffset 0x08 to 0x1f */
71         uint8_t reserved_2[24];
72         /* IP only for J-Link Pro */
73         uint8_t ip_address[4];
74         uint8_t subnet_mask[4];
75         /* 0ffset 0x28 to 0x2f */
76         uint8_t reserved_3[8];
77         uint8_t mac_address[6];
78         /* 0ffset 0x36 to 0xff */
79         uint8_t reserved_4[202];
80 } __attribute__ ((packed));
81
82 static struct device_config config;
83 static struct device_config tmp_config;
84
85 /* Queue command functions */
86 static void jlink_end_state(tap_state_t state);
87 static void jlink_state_move(void);
88 static void jlink_path_move(int num_states, tap_state_t *path);
89 static void jlink_stableclocks(int num_cycles);
90 static void jlink_runtest(int num_cycles);
91 static void jlink_reset(int trst, int srst);
92 static int jlink_swd_run_queue(void);
93 static void jlink_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk);
94 static int jlink_swd_switch_seq(enum swd_special_seq seq);
95
96 /* J-Link tap buffer functions */
97 static void jlink_tap_init(void);
98 static int jlink_flush(void);
99 /**
100  * Queue data to go out and in, flushing the queue as many times as
101  * necessary.
102  *
103  * @param out A pointer to TDI data, if NULL, old stale data will be used.
104  * @param out_offset A bit offset for TDI data.
105  * @param tms_out A pointer to TMS data, if NULL, zeroes will be emitted.
106  * @param tms_offset A bit offset for TMS data.
107  * @param in A pointer to store TDO data to, if NULL the data will be discarded.
108  * @param in_offset A bit offset for TDO data.
109  * @param length Amount of bits to transfer out and in.
110  *
111  * @retval This function doesn't return any value.
112  */
113 static void jlink_clock_data(const uint8_t *out, unsigned out_offset,
114                              const uint8_t *tms_out, unsigned tms_offset,
115                              uint8_t *in, unsigned in_offset,
116                              unsigned length);
117
118 static enum tap_state jlink_last_state = TAP_RESET;
119 static int queued_retval;
120
121 /***************************************************************************/
122 /* External interface implementation */
123
124 static void jlink_execute_stableclocks(struct jtag_command *cmd)
125 {
126         DEBUG_JTAG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
127         jlink_stableclocks(cmd->cmd.runtest->num_cycles);
128 }
129
130 static void jlink_execute_runtest(struct jtag_command *cmd)
131 {
132         DEBUG_JTAG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
133                 cmd->cmd.runtest->end_state);
134
135         jlink_end_state(cmd->cmd.runtest->end_state);
136         jlink_runtest(cmd->cmd.runtest->num_cycles);
137 }
138
139 static void jlink_execute_statemove(struct jtag_command *cmd)
140 {
141         DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
142
143         jlink_end_state(cmd->cmd.statemove->end_state);
144         jlink_state_move();
145 }
146
147 static void jlink_execute_pathmove(struct jtag_command *cmd)
148 {
149         DEBUG_JTAG_IO("pathmove: %i states, end in %i",
150                 cmd->cmd.pathmove->num_states,
151                 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
152
153         jlink_path_move(cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path);
154 }
155
156 static void jlink_execute_scan(struct jtag_command *cmd)
157 {
158         DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
159                 jtag_scan_type(cmd->cmd.scan));
160
161         /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
162         while (cmd->cmd.scan->num_fields > 0
163                         && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
164                 cmd->cmd.scan->num_fields--;
165                 LOG_DEBUG("discarding trailing empty field");
166         }
167
168         if (cmd->cmd.scan->num_fields == 0) {
169                 LOG_DEBUG("empty scan, doing nothing");
170                 return;
171         }
172
173         if (cmd->cmd.scan->ir_scan) {
174                 if (tap_get_state() != TAP_IRSHIFT) {
175                         jlink_end_state(TAP_IRSHIFT);
176                         jlink_state_move();
177                 }
178         } else {
179                 if (tap_get_state() != TAP_DRSHIFT) {
180                         jlink_end_state(TAP_DRSHIFT);
181                         jlink_state_move();
182                 }
183         }
184
185         jlink_end_state(cmd->cmd.scan->end_state);
186
187         struct scan_field *field = cmd->cmd.scan->fields;
188         unsigned scan_size = 0;
189
190         for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
191                 scan_size += field->num_bits;
192                 DEBUG_JTAG_IO("%s%s field %d/%d %d bits",
193                         field->in_value ? "in" : "",
194                         field->out_value ? "out" : "",
195                         i,
196                         cmd->cmd.scan->num_fields,
197                         field->num_bits);
198
199                 if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
200                         /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
201                          * movement. This last field can't have length zero, it was checked above. */
202                         jlink_clock_data(field->out_value,
203                                          0,
204                                          NULL,
205                                          0,
206                                          field->in_value,
207                                          0,
208                                          field->num_bits - 1);
209                         uint8_t last_bit = 0;
210                         if (field->out_value)
211                                 bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
212                         uint8_t tms_bits = 0x01;
213                         jlink_clock_data(&last_bit,
214                                          0,
215                                          &tms_bits,
216                                          0,
217                                          field->in_value,
218                                          field->num_bits - 1,
219                                          1);
220                         tap_set_state(tap_state_transition(tap_get_state(), 1));
221                         jlink_clock_data(&last_bit,
222                                          0,
223                                          &tms_bits,
224                                          1,
225                                          NULL,
226                                          0,
227                                          1);
228                         tap_set_state(tap_state_transition(tap_get_state(), 0));
229                 } else
230                         jlink_clock_data(field->out_value,
231                                          0,
232                                          NULL,
233                                          0,
234                                          field->in_value,
235                                          0,
236                                          field->num_bits);
237         }
238
239         if (tap_get_state() != tap_get_end_state()) {
240                 jlink_end_state(tap_get_end_state());
241                 jlink_state_move();
242         }
243
244         DEBUG_JTAG_IO("%s scan, %i bits, end in %s",
245                 (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
246                 tap_state_name(tap_get_end_state()));
247 }
248
249 static void jlink_execute_reset(struct jtag_command *cmd)
250 {
251         DEBUG_JTAG_IO("reset trst: %i srst %i", cmd->cmd.reset->trst,
252                 cmd->cmd.reset->srst);
253
254         jlink_flush();
255         jlink_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
256         jlink_flush();
257 }
258
259 static void jlink_execute_sleep(struct jtag_command *cmd)
260 {
261         DEBUG_JTAG_IO("sleep %" PRIi32 "", cmd->cmd.sleep->us);
262         jlink_flush();
263         jtag_sleep(cmd->cmd.sleep->us);
264 }
265
266 static int jlink_execute_command(struct jtag_command *cmd)
267 {
268         switch (cmd->type) {
269                 case JTAG_STABLECLOCKS:
270                         jlink_execute_stableclocks(cmd);
271                         break;
272                 case JTAG_RUNTEST:
273                         jlink_execute_runtest(cmd);
274                         break;
275                 case JTAG_TLR_RESET:
276                         jlink_execute_statemove(cmd);
277                         break;
278                 case JTAG_PATHMOVE:
279                         jlink_execute_pathmove(cmd);
280                         break;
281                 case JTAG_SCAN:
282                         jlink_execute_scan(cmd);
283                         break;
284                 case JTAG_RESET:
285                         jlink_execute_reset(cmd);
286                         break;
287                 case JTAG_SLEEP:
288                         jlink_execute_sleep(cmd);
289                         break;
290                 default:
291                         LOG_ERROR("BUG: Unknown JTAG command type encountered.");
292                         return ERROR_JTAG_QUEUE_FAILED;
293         }
294
295         return ERROR_OK;
296 }
297
298 static int jlink_execute_queue(void)
299 {
300         int ret;
301         struct jtag_command *cmd = jtag_command_queue;
302
303         while (cmd != NULL) {
304                 ret = jlink_execute_command(cmd);
305
306                 if (ret != ERROR_OK)
307                         return ret;
308
309                 cmd = cmd->next;
310         }
311
312         return jlink_flush();
313 }
314
315 static int jlink_speed(int speed)
316 {
317         int ret;
318         uint32_t freq;
319         uint16_t divider;
320         int max_speed;
321
322         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_SPEEDS)) {
323                 ret = jaylink_get_speeds(devh, &freq, &divider);
324
325                 if (ret != JAYLINK_OK) {
326                         LOG_ERROR("jaylink_get_speeds() failed: %s.",
327                                 jaylink_strerror_name(ret));
328                         return ERROR_JTAG_DEVICE_ERROR;
329                 }
330
331                 freq = freq / 1000;
332                 max_speed = freq / divider;
333         } else {
334                 max_speed = JLINK_MAX_SPEED;
335         }
336
337         if (!speed) {
338                 if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ADAPTIVE_CLOCKING)) {
339                         LOG_ERROR("Adaptive clocking is not supported by the device.");
340                         return ERROR_JTAG_NOT_IMPLEMENTED;
341                 }
342
343                 speed = JAYLINK_SPEED_ADAPTIVE_CLOCKING;
344         } else if (speed > max_speed) {
345                 LOG_INFO("Reduced speed from %d kHz to %d kHz (maximum).", speed,
346                         max_speed);
347                 speed = max_speed;
348         }
349
350         ret = jaylink_set_speed(devh, speed);
351
352         if (ret != JAYLINK_OK) {
353                 LOG_ERROR("jaylink_set_speed() failed: %s.",
354                         jaylink_strerror_name(ret));
355                 return ERROR_JTAG_DEVICE_ERROR;
356         }
357
358         return ERROR_OK;
359 }
360
361 static int jlink_speed_div(int speed, int *khz)
362 {
363         *khz = speed;
364
365         return ERROR_OK;
366 }
367
368 static int jlink_khz(int khz, int *jtag_speed)
369 {
370         *jtag_speed = khz;
371
372         return ERROR_OK;
373 }
374
375 static bool read_device_config(struct device_config *cfg)
376 {
377         int ret;
378
379         ret = jaylink_read_raw_config(devh, (uint8_t *)cfg);
380
381         if (ret != JAYLINK_OK) {
382                 LOG_ERROR("jaylink_read_raw_config() failed: %s.",
383                         jaylink_strerror_name(ret));
384                 return false;
385         }
386
387         if (cfg->usb_address == 0xff)
388                 cfg->usb_address = 0x00;
389
390         if (cfg->target_power == 0xffffffff)
391                 cfg->target_power = 0;
392
393         return true;
394 }
395
396 static int select_interface(void)
397 {
398         int ret;
399         uint32_t interfaces;
400
401         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SELECT_TIF)) {
402                 if (iface != JAYLINK_TIF_JTAG) {
403                         LOG_ERROR("Device supports JTAG transport only.");
404                         return ERROR_JTAG_INIT_FAILED;
405                 }
406
407                 return ERROR_OK;
408         }
409
410         ret = jaylink_get_available_interfaces(devh, &interfaces);
411
412         if (ret != JAYLINK_OK) {
413                 LOG_ERROR("jaylink_get_available_interfaces() failed: %s.",
414                         jaylink_strerror_name(ret));
415                 return ERROR_JTAG_INIT_FAILED;
416         }
417
418         if (!(interfaces & (1 << iface))) {
419                 LOG_ERROR("Selected transport is not supported by the device.");
420                 return ERROR_JTAG_INIT_FAILED;
421         }
422
423         ret = jaylink_select_interface(devh, iface, NULL);
424
425         if (ret < 0) {
426                 LOG_ERROR("jaylink_select_interface() failed: %s.",
427                         jaylink_strerror_name(ret));
428                 return ERROR_JTAG_INIT_FAILED;
429         }
430
431         return ERROR_OK;
432 }
433
434 static int jlink_register(void)
435 {
436         int ret;
437         int i;
438         bool handle_found;
439
440         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_REGISTER))
441                 return ERROR_OK;
442
443         ret = jaylink_register(devh, &conn, connlist, NULL, NULL);
444
445         if (ret < 0) {
446                 LOG_ERROR("jaylink_register() failed: %s.",
447                         jaylink_strerror_name(ret));
448                 return ERROR_FAIL;
449         }
450
451         handle_found = false;
452
453         for (i = 0; i < ret; i++) {
454                 if (connlist[i].handle == conn.handle) {
455                         handle_found = true;
456                         break;
457                 }
458         }
459
460         if (!handle_found) {
461                 LOG_ERROR("Registration failed: maximum number of connections on the "
462                         "device reached.");
463                 return ERROR_FAIL;
464         }
465
466         return ERROR_OK;
467 }
468
469 /*
470  * Adjust the SWD transaction buffer size depending on the free device internal
471  * memory. This ensures that the SWD transactions sent to the device do not
472  * exceed the internal memory of the device.
473  */
474 static bool adjust_swd_buffer_size(void)
475 {
476         int ret;
477         uint32_t tmp;
478
479         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY))
480                 return true;
481
482         ret = jaylink_get_free_memory(devh, &tmp);
483
484         if (ret != JAYLINK_OK) {
485                 LOG_ERROR("jaylink_get_free_memory() failed: %s.",
486                         jaylink_strerror_name(ret));
487                 return false;
488         }
489
490         if (tmp < 143) {
491                 LOG_ERROR("Not enough free device internal memory: %u bytes.", tmp);
492                 return false;
493         }
494
495         tmp = MIN(JLINK_TAP_BUFFER_SIZE, (tmp - 16) / 2);
496
497         if (tmp != swd_buffer_size) {
498                 swd_buffer_size = tmp;
499                 LOG_DEBUG("Adjusted SWD transaction buffer size to %u bytes.",
500                         swd_buffer_size);
501         }
502
503         return true;
504 }
505
506 static int jlink_init(void)
507 {
508         int ret;
509         struct jaylink_device **devs;
510         unsigned int i;
511         bool found_device;
512         uint32_t tmp;
513         char *firmware_version;
514         struct jaylink_hardware_version hwver;
515         struct jaylink_hardware_status hwstatus;
516         enum jaylink_usb_address address;
517         size_t length;
518
519         ret = jaylink_init(&jayctx);
520
521         if (ret != JAYLINK_OK) {
522                 LOG_ERROR("jaylink_init() failed: %s.",
523                         jaylink_strerror_name(ret));
524                 return ERROR_JTAG_INIT_FAILED;
525         }
526
527         ret = jaylink_get_device_list(jayctx, &devs);
528
529         if (ret < 0) {
530                 LOG_ERROR("jaylink_get_device_list() failed: %s.",
531                         jaylink_strerror_name(ret));
532                 jaylink_exit(jayctx);
533                 return ERROR_JTAG_INIT_FAILED;
534         }
535
536         found_device = false;
537
538         if (!use_serial_number && !use_usb_address)
539                 LOG_INFO("No device selected, using first device.");
540
541         for (i = 0; devs[i]; i++) {
542                 if (use_serial_number) {
543                         ret = jaylink_device_get_serial_number(devs[i], &tmp);
544
545                         if (ret == JAYLINK_ERR_NOT_AVAILABLE) {
546                                 continue;
547                         } else if (ret != JAYLINK_OK) {
548                                 LOG_WARNING("jaylink_device_get_serial_number() failed: %s.",
549                                         jaylink_strerror_name(ret));
550                                 continue;
551                         }
552
553                         if (serial_number != tmp)
554                                 continue;
555                 }
556
557                 if (use_usb_address) {
558                         ret = jaylink_device_get_usb_address(devs[i], &address);
559
560                         if (ret != JAYLINK_OK) {
561                                 LOG_WARNING("jaylink_device_get_usb_address() failed: %s.",
562                                         jaylink_strerror_name(ret));
563                                 continue;
564                         }
565
566                         if (usb_address != address)
567                                 continue;
568                 }
569
570                 ret = jaylink_open(devs[i], &devh);
571
572                 if (ret == JAYLINK_OK) {
573                         found_device = true;
574                         break;
575                 }
576
577                 LOG_ERROR("Failed to open device: %s.", jaylink_strerror_name(ret));
578         }
579
580         jaylink_free_device_list(devs, 1);
581
582         if (!found_device) {
583                 LOG_ERROR("No J-Link device found.");
584                 jaylink_exit(jayctx);
585                 return ERROR_JTAG_INIT_FAILED;
586         }
587
588         /*
589          * Be careful with changing the following initialization sequence because
590          * some devices are known to be sensitive regarding the order.
591          */
592
593         ret = jaylink_get_firmware_version(devh, &firmware_version, &length);
594
595         if (ret != JAYLINK_OK) {
596                 LOG_ERROR("jaylink_get_firmware_version() failed: %s.",
597                         jaylink_strerror_name(ret));
598                 jaylink_close(devh);
599                 jaylink_exit(jayctx);
600                 return ERROR_JTAG_INIT_FAILED;
601         } else if (length > 0) {
602                 LOG_INFO("%s", firmware_version);
603                 free(firmware_version);
604         } else {
605                 LOG_WARNING("Device responds empty firmware version string.");
606         }
607
608         memset(caps, 0, JAYLINK_DEV_EXT_CAPS_SIZE);
609         ret = jaylink_get_caps(devh, caps);
610
611         if (ret != JAYLINK_OK) {
612                 LOG_ERROR("jaylink_get_caps() failed: %s.", jaylink_strerror_name(ret));
613                 jaylink_close(devh);
614                 jaylink_exit(jayctx);
615                 return ERROR_JTAG_INIT_FAILED;
616         }
617
618         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_EXT_CAPS)) {
619                 ret = jaylink_get_extended_caps(devh, caps);
620
621                 if (ret != JAYLINK_OK) {
622                         LOG_ERROR("jaylink_get_extended_caps() failed:  %s.",
623                                 jaylink_strerror_name(ret));
624                         jaylink_close(devh);
625                         jaylink_exit(jayctx);
626                         return ERROR_JTAG_INIT_FAILED;
627                 }
628         }
629
630         jtag_command_version = JAYLINK_JTAG_V2;
631
632         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_HW_VERSION)) {
633                 ret = jaylink_get_hardware_version(devh, &hwver);
634
635                 if (ret != JAYLINK_OK) {
636                         LOG_ERROR("Failed to retrieve hardware version: %s.",
637                                 jaylink_strerror_name(ret));
638                         jaylink_close(devh);
639                         jaylink_exit(jayctx);
640                         return ERROR_JTAG_INIT_FAILED;
641                 }
642
643                 LOG_INFO("Hardware version: %u.%02u", hwver.major, hwver.minor);
644
645                 if (hwver.major >= 5)
646                         jtag_command_version = JAYLINK_JTAG_V3;
647         }
648
649         if (iface == JAYLINK_TIF_SWD) {
650                 /*
651                  * Adjust the SWD transaction buffer size in case there is already
652                  * allocated memory on the device. This happens for example if the
653                  * memory for SWO capturing is still allocated because the software
654                  * which used the device before has not been shut down properly.
655                  */
656                 if (!adjust_swd_buffer_size()) {
657                         jaylink_close(devh);
658                         jaylink_exit(jayctx);
659                         return ERROR_JTAG_INIT_FAILED;
660                 }
661         }
662
663         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
664                 if (!read_device_config(&config)) {
665                         LOG_ERROR("Failed to read device configuration data.");
666                         jaylink_close(devh);
667                         jaylink_exit(jayctx);
668                         return ERROR_JTAG_INIT_FAILED;
669                 }
670
671                 memcpy(&tmp_config, &config, sizeof(struct device_config));
672         }
673
674         ret = jaylink_get_hardware_status(devh, &hwstatus);
675
676         if (ret != JAYLINK_OK) {
677                 LOG_ERROR("jaylink_get_hardware_status() failed: %s.",
678                         jaylink_strerror_name(ret));
679                 jaylink_close(devh);
680                 jaylink_exit(jayctx);
681                 return ERROR_JTAG_INIT_FAILED;
682         }
683
684         LOG_INFO("VTarget = %u.%03u V", hwstatus.target_voltage / 1000,
685                 hwstatus.target_voltage % 1000);
686
687         conn.handle = 0;
688         conn.pid = 0;
689         conn.hid = 0;
690         conn.iid = 0;
691         conn.cid = 0;
692
693         ret = jlink_register();
694
695         if (ret != ERROR_OK) {
696                 jaylink_close(devh);
697                 jaylink_exit(jayctx);
698                 return ERROR_JTAG_INIT_FAILED;
699         }
700
701         ret = select_interface();
702
703         if (ret != ERROR_OK) {
704                 jaylink_close(devh);
705                 jaylink_exit(jayctx);
706                 return ret;
707         }
708
709         jlink_reset(0, 0);
710         jtag_sleep(3000);
711         jlink_tap_init();
712
713         jlink_speed(jtag_get_speed_khz());
714
715         if (iface == JAYLINK_TIF_JTAG) {
716                 /*
717                  * J-Link devices with firmware version v5 and v6 seems to have an issue
718                  * if the first tap move is not divisible by 8, so we send a TLR on
719                  * first power up.
720                  */
721                 uint8_t tms = 0xff;
722                 jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 8);
723
724                 jlink_flush();
725         }
726
727         return ERROR_OK;
728 }
729
730 static int jlink_quit(void)
731 {
732         int ret;
733
734         if (trace_enabled) {
735                 ret = jaylink_swo_stop(devh);
736
737                 if (ret != JAYLINK_OK)
738                         LOG_ERROR("jaylink_swo_stop() failed: %s.",
739                                 jaylink_strerror_name(ret));
740         }
741
742         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_REGISTER)) {
743                 ret = jaylink_unregister(devh, &conn, connlist, NULL, NULL);
744
745                 if (ret < 0)
746                         LOG_ERROR("jaylink_unregister() failed: %s.",
747                                 jaylink_strerror_name(ret));
748         }
749
750         jaylink_close(devh);
751         jaylink_exit(jayctx);
752
753         return ERROR_OK;
754 }
755
756 /***************************************************************************/
757 /* Queue command implementations */
758
759 static void jlink_end_state(tap_state_t state)
760 {
761         if (tap_is_state_stable(state))
762                 tap_set_end_state(state);
763         else {
764                 LOG_ERROR("BUG: %i is not a valid end state", state);
765                 exit(-1);
766         }
767 }
768
769 /* Goes to the end state. */
770 static void jlink_state_move(void)
771 {
772         uint8_t tms_scan;
773         uint8_t tms_scan_bits;
774
775         tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
776         tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
777
778         jlink_clock_data(NULL, 0, &tms_scan, 0, NULL, 0, tms_scan_bits);
779
780         tap_set_state(tap_get_end_state());
781 }
782
783 static void jlink_path_move(int num_states, tap_state_t *path)
784 {
785         int i;
786         uint8_t tms = 0xff;
787
788         for (i = 0; i < num_states; i++) {
789                 if (path[i] == tap_state_transition(tap_get_state(), false))
790                         jlink_clock_data(NULL, 0, NULL, 0, NULL, 0, 1);
791                 else if (path[i] == tap_state_transition(tap_get_state(), true))
792                         jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 1);
793                 else {
794                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
795                                 tap_state_name(tap_get_state()), tap_state_name(path[i]));
796                         exit(-1);
797                 }
798
799                 tap_set_state(path[i]);
800         }
801
802         tap_set_end_state(tap_get_state());
803 }
804
805 static void jlink_stableclocks(int num_cycles)
806 {
807         int i;
808
809         uint8_t tms = tap_get_state() == TAP_RESET;
810         /* Execute num_cycles. */
811         for (i = 0; i < num_cycles; i++)
812                 jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 1);
813 }
814
815 static void jlink_runtest(int num_cycles)
816 {
817         tap_state_t saved_end_state = tap_get_end_state();
818
819         /* Only do a state_move when we're not already in IDLE. */
820         if (tap_get_state() != TAP_IDLE) {
821                 jlink_end_state(TAP_IDLE);
822                 jlink_state_move();
823                 /* num_cycles--; */
824         }
825
826         jlink_stableclocks(num_cycles);
827
828         /* Finish in end_state. */
829         jlink_end_state(saved_end_state);
830
831         if (tap_get_state() != tap_get_end_state())
832                 jlink_state_move();
833 }
834
835 static void jlink_reset(int trst, int srst)
836 {
837         LOG_DEBUG("TRST: %i, SRST: %i.", trst, srst);
838
839         /* Signals are active low. */
840         if (srst == 0)
841                 jaylink_set_reset(devh);
842
843         if (srst == 1)
844                 jaylink_clear_reset(devh);
845
846         if (trst == 1)
847                 jaylink_jtag_clear_trst(devh);
848
849         if (trst == 0)
850                 jaylink_jtag_set_trst(devh);
851 }
852
853 COMMAND_HANDLER(jlink_usb_command)
854 {
855         int tmp;
856
857         if (CMD_ARGC != 1) {
858                 command_print(CMD_CTX, "Need exactly one argument for jlink usb.");
859                 return ERROR_COMMAND_SYNTAX_ERROR;
860         }
861
862         if (sscanf(CMD_ARGV[0], "%i", &tmp) != 1) {
863                 command_print(CMD_CTX, "Invalid USB address: %s.", CMD_ARGV[0]);
864                 return ERROR_FAIL;
865         }
866
867         if (tmp < JAYLINK_USB_ADDRESS_0 || tmp > JAYLINK_USB_ADDRESS_3) {
868                 command_print(CMD_CTX, "Invalid USB address: %s.", CMD_ARGV[0]);
869                 return ERROR_FAIL;
870         }
871
872         usb_address = tmp;
873
874         use_serial_number = false;
875         use_usb_address = true;
876
877         return ERROR_OK;
878 }
879
880 COMMAND_HANDLER(jlink_serial_command)
881 {
882         if (CMD_ARGC != 1) {
883                 command_print(CMD_CTX, "Need exactly one argument for jlink serial.");
884                 return ERROR_COMMAND_SYNTAX_ERROR;
885         }
886
887         if (sscanf(CMD_ARGV[0], "%" SCNd32, &serial_number) != 1) {
888                 command_print(CMD_CTX, "Invalid serial number: %s.", CMD_ARGV[0]);
889                 return ERROR_FAIL;
890         }
891
892         use_serial_number = true;
893         use_usb_address = false;
894
895         return ERROR_OK;
896 }
897
898 COMMAND_HANDLER(jlink_handle_hwstatus_command)
899 {
900         int ret;
901         struct jaylink_hardware_status status;
902
903         ret = jaylink_get_hardware_status(devh, &status);
904
905         if (ret != JAYLINK_OK) {
906                 command_print(CMD_CTX, "jaylink_get_hardware_status() failed: %s.",
907                         jaylink_strerror_name(ret));
908                 return ERROR_FAIL;
909         }
910
911         command_print(CMD_CTX, "VTarget = %u.%03u V",
912                 status.target_voltage / 1000, status.target_voltage % 1000);
913
914         command_print(CMD_CTX, "TCK = %u TDI = %u TDO = %u TMS = %u SRST = %u "
915                 "TRST = %u", status.tck, status.tdi, status.tdo, status.tms,
916                 status.tres, status.trst);
917
918         if (status.target_voltage < 1500)
919                 command_print(CMD_CTX, "Target voltage too low. Check target power.");
920
921         return ERROR_OK;
922 }
923
924 COMMAND_HANDLER(jlink_handle_free_memory_command)
925 {
926         int ret;
927         uint32_t tmp;
928
929         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY)) {
930                 command_print(CMD_CTX, "Retrieval of free memory is not supported by "
931                         "the device.");
932                 return ERROR_OK;
933         }
934
935         ret = jaylink_get_free_memory(devh, &tmp);
936
937         if (ret != JAYLINK_OK) {
938                 command_print(CMD_CTX, "jaylink_get_free_memory() failed: %s.",
939                         jaylink_strerror_name(ret));
940                 return ERROR_FAIL;
941         }
942
943         command_print(CMD_CTX, "Device has %u bytes of free memory.", tmp);
944
945         return ERROR_OK;
946 }
947
948 COMMAND_HANDLER(jlink_handle_jlink_jtag_command)
949 {
950         int tmp;
951         int version;
952
953         if (!CMD_ARGC) {
954                 switch (jtag_command_version) {
955                         case JAYLINK_JTAG_V2:
956                                 version = 2;
957                                 break;
958                         case JAYLINK_JTAG_V3:
959                                 version = 3;
960                                 break;
961                         default:
962                                 return ERROR_FAIL;
963                 }
964
965                 command_print(CMD_CTX, "JTAG command version: %i", version);
966         } else if (CMD_ARGC == 1) {
967                 if (sscanf(CMD_ARGV[0], "%i", &tmp) != 1) {
968                         command_print(CMD_CTX, "Invalid argument: %s.", CMD_ARGV[0]);
969                         return ERROR_COMMAND_SYNTAX_ERROR;
970                 }
971
972                 switch (tmp) {
973                         case 2:
974                                 jtag_command_version = JAYLINK_JTAG_V2;
975                                 break;
976                         case 3:
977                                 jtag_command_version = JAYLINK_JTAG_V3;
978                                 break;
979                         default:
980                                 command_print(CMD_CTX, "Invalid argument: %s.", CMD_ARGV[0]);
981                                 return ERROR_COMMAND_SYNTAX_ERROR;
982                 }
983         } else {
984                 command_print(CMD_CTX, "Need exactly one argument for jlink jtag.");
985                 return ERROR_COMMAND_SYNTAX_ERROR;
986         }
987
988         return ERROR_OK;
989 }
990
991 COMMAND_HANDLER(jlink_handle_target_power_command)
992 {
993         int ret;
994         int enable;
995
996         if (CMD_ARGC != 1) {
997                 command_print(CMD_CTX, "Need exactly one argument for jlink "
998                         "targetpower.");
999                 return ERROR_COMMAND_SYNTAX_ERROR;
1000         }
1001
1002         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER)) {
1003                 command_print(CMD_CTX, "Target power supply is not supported by the "
1004                         "device.");
1005                 return ERROR_OK;
1006         }
1007
1008         if (!strcmp(CMD_ARGV[0], "on")) {
1009                 enable = true;
1010         } else if (!strcmp(CMD_ARGV[0], "off")) {
1011                 enable = false;
1012         } else {
1013                 command_print(CMD_CTX, "Invalid argument: %s.", CMD_ARGV[0]);
1014                 return ERROR_FAIL;
1015         }
1016
1017         ret = jaylink_set_target_power(devh, enable);
1018
1019         if (ret != JAYLINK_OK) {
1020                 command_print(CMD_CTX, "jaylink_set_target_power() failed: %s.",
1021                         jaylink_strerror_name(ret));
1022                 return ERROR_FAIL;
1023         }
1024
1025         return ERROR_OK;
1026 }
1027
1028 static void show_config_usb_address(struct command_context *ctx)
1029 {
1030         if (config.usb_address != tmp_config.usb_address)
1031                 command_print(ctx, "USB address: %u [%u]", config.usb_address,
1032                         tmp_config.usb_address);
1033         else
1034                 command_print(ctx, "USB address: %u", config.usb_address);
1035 }
1036
1037 static void show_config_ip_address(struct command_context *ctx)
1038 {
1039         if (!memcmp(config.ip_address, tmp_config.ip_address, 4))
1040                 command_print(ctx, "IP address: %d.%d.%d.%d",
1041                         config.ip_address[3], config.ip_address[2],
1042                         config.ip_address[1], config.ip_address[0]);
1043         else
1044                 command_print(ctx, "IP address: %d.%d.%d.%d [%d.%d.%d.%d]",
1045                         config.ip_address[3], config.ip_address[2],
1046                         config.ip_address[1], config.ip_address[0],
1047                         tmp_config.ip_address[3], tmp_config.ip_address[2],
1048                         tmp_config.ip_address[1], tmp_config.ip_address[0]);
1049
1050         if (!memcmp(config.subnet_mask, tmp_config.subnet_mask, 4))
1051                 command_print(ctx, "Subnet mask: %d.%d.%d.%d",
1052                         config.subnet_mask[3], config.subnet_mask[2],
1053                         config.subnet_mask[1], config.subnet_mask[0]);
1054         else
1055                 command_print(ctx, "Subnet mask: %d.%d.%d.%d [%d.%d.%d.%d]",
1056                         config.subnet_mask[3], config.subnet_mask[2],
1057                         config.subnet_mask[1], config.subnet_mask[0],
1058                         tmp_config.subnet_mask[3], tmp_config.subnet_mask[2],
1059                         tmp_config.subnet_mask[1], tmp_config.subnet_mask[0]);
1060 }
1061
1062 static void show_config_mac_address(struct command_context *ctx)
1063 {
1064         if (!memcmp(config.mac_address, tmp_config.mac_address, 6))
1065                 command_print(ctx, "MAC address: %.02x:%.02x:%.02x:%.02x:%.02x:%.02x",
1066                         config.mac_address[5], config.mac_address[4],
1067                         config.mac_address[3], config.mac_address[2],
1068                         config.mac_address[1], config.mac_address[0]);
1069         else
1070                 command_print(ctx, "MAC address: %.02x:%.02x:%.02x:%.02x:%.02x:%.02x "
1071                         "[%.02x:%.02x:%.02x:%.02x:%.02x:%.02x]",
1072                         config.mac_address[5], config.mac_address[4],
1073                         config.mac_address[3], config.mac_address[2],
1074                         config.mac_address[1], config.mac_address[0],
1075                         tmp_config.mac_address[5], tmp_config.mac_address[4],
1076                         tmp_config.mac_address[3], tmp_config.mac_address[2],
1077                         tmp_config.mac_address[1], tmp_config.mac_address[0]);
1078 }
1079
1080 static void show_config_target_power(struct command_context *ctx)
1081 {
1082         const char *target_power;
1083         const char *current_target_power;
1084
1085         if (!config.target_power)
1086                 target_power = "off";
1087         else
1088                 target_power = "on";
1089
1090         if (!tmp_config.target_power)
1091                 current_target_power = "off";
1092         else
1093                 current_target_power = "on";
1094
1095         if (config.target_power != tmp_config.target_power)
1096                 command_print(ctx, "Target power supply: %s [%s]", target_power,
1097                         current_target_power);
1098         else
1099                 command_print(ctx, "Target power supply: %s", target_power);
1100 }
1101
1102 static void show_config(struct command_context *ctx)
1103 {
1104         command_print(ctx, "J-Link device configuration:");
1105
1106         show_config_usb_address(ctx);
1107
1108         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER))
1109                 show_config_target_power(ctx);
1110
1111         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1112                 show_config_ip_address(ctx);
1113                 show_config_mac_address(ctx);
1114         }
1115 }
1116
1117 static int poll_trace(uint8_t *buf, size_t *size)
1118 {
1119         int ret;
1120         uint32_t length;
1121
1122         length = *size;
1123
1124         ret = jaylink_swo_read(devh, buf, &length);
1125
1126         if (ret != JAYLINK_OK) {
1127                 LOG_ERROR("jaylink_swo_read() failed: %s.", jaylink_strerror_name(ret));
1128                 return ERROR_FAIL;
1129         }
1130
1131         *size = length;
1132
1133         return ERROR_OK;
1134 }
1135
1136 static uint32_t calculate_trace_buffer_size(void)
1137 {
1138         int ret;
1139         uint32_t tmp;
1140
1141         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY))
1142                 return 0;
1143
1144         ret = jaylink_get_free_memory(devh, &tmp);
1145
1146         if (ret != JAYLINK_OK) {
1147                 LOG_ERROR("jaylink_get_free_memory() failed: %s.",
1148                         jaylink_strerror_name(ret));
1149                 return ERROR_FAIL;
1150         }
1151
1152         if (tmp > 0x3fff || tmp <= 0x600)
1153                 tmp = tmp >> 1;
1154         else
1155                 tmp = tmp - 0x400;
1156
1157         return tmp & 0xffffff00;
1158 }
1159
1160 static bool check_trace_freq(struct jaylink_swo_speed speed,
1161                 uint32_t trace_freq)
1162 {
1163         double min;
1164         double deviation;
1165         uint32_t divider;
1166
1167         min = fabs(1.0 - (speed.freq / ((double)trace_freq * speed.min_div)));
1168
1169         for (divider = speed.min_div; divider < speed.max_div; divider++) {
1170                 deviation = fabs(1.0 - (speed.freq / ((double)trace_freq * divider)));
1171
1172                 if (deviation < 0.03) {
1173                         LOG_DEBUG("Found suitable frequency divider %u with deviation of "
1174                                 "%.02f %%.", divider, deviation);
1175                         return true;
1176                 }
1177
1178                 if (deviation < min)
1179                         min = deviation;
1180         }
1181
1182         LOG_ERROR("Selected trace frequency is not supported by the device. "
1183                 "Please choose a different trace frequency.");
1184         LOG_ERROR("Maximum permitted deviation is 3.00 %%, but only %.02f %% "
1185                 "could be achieved.", min * 100);
1186
1187         return false;
1188 }
1189
1190 static int config_trace(bool enabled, enum tpio_pin_protocol pin_protocol,
1191                 uint32_t port_size, unsigned int *trace_freq)
1192 {
1193         int ret;
1194         uint32_t buffer_size;
1195         struct jaylink_swo_speed speed;
1196
1197         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SWO)) {
1198                 LOG_ERROR("Trace capturing is not supported by the device.");
1199                 return ERROR_FAIL;
1200         }
1201
1202         if (pin_protocol != ASYNC_UART) {
1203                 LOG_ERROR("Selected pin protocol is not supported.");
1204                 return ERROR_FAIL;
1205         }
1206
1207         trace_enabled = enabled;
1208
1209         ret = jaylink_swo_stop(devh);
1210
1211         if (ret != JAYLINK_OK) {
1212                 LOG_ERROR("jaylink_swo_stop() failed: %s.", jaylink_strerror_name(ret));
1213                 return ERROR_FAIL;
1214         }
1215
1216         if (!enabled) {
1217                 /*
1218                  * Adjust the SWD transaction buffer size as stopping SWO capturing
1219                  * deallocates device internal memory.
1220                  */
1221                 if (!adjust_swd_buffer_size())
1222                         return ERROR_FAIL;
1223
1224                 return ERROR_OK;
1225         }
1226
1227         buffer_size = calculate_trace_buffer_size();
1228
1229         if (!buffer_size) {
1230                 LOG_ERROR("Not enough free device memory to start trace capturing.");
1231                 return ERROR_FAIL;
1232         }
1233
1234         ret = jaylink_swo_get_speeds(devh, JAYLINK_SWO_MODE_UART, &speed);
1235
1236         if (ret != JAYLINK_OK) {
1237                 LOG_ERROR("jaylink_swo_get_speeds() failed: %s.",
1238                         jaylink_strerror_name(ret));
1239                 return ERROR_FAIL;
1240         }
1241
1242         if (!*trace_freq)
1243                 *trace_freq = speed.freq / speed.min_div;
1244
1245         if (!check_trace_freq(speed, *trace_freq))
1246                 return ERROR_FAIL;
1247
1248         LOG_DEBUG("Using %u bytes device memory for trace capturing.", buffer_size);
1249
1250         ret = jaylink_swo_start(devh, JAYLINK_SWO_MODE_UART, *trace_freq,
1251                 buffer_size);
1252
1253         if (ret != JAYLINK_OK) {
1254                 LOG_ERROR("jaylink_start_swo() failed: %s.",
1255                         jaylink_strerror_name(ret));
1256                 return ERROR_FAIL;
1257         }
1258
1259         /*
1260          * Adjust the SWD transaction buffer size as starting SWO capturing
1261          * allocates device internal memory.
1262          */
1263         if (!adjust_swd_buffer_size())
1264                 return ERROR_FAIL;
1265
1266         return ERROR_OK;
1267 }
1268
1269 COMMAND_HANDLER(jlink_handle_config_usb_address_command)
1270 {
1271         uint8_t tmp;
1272
1273         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1274                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1275                         "device.");
1276                 return ERROR_OK;
1277         }
1278
1279         if (!CMD_ARGC) {
1280                 show_config_usb_address(CMD_CTX);
1281         } else if (CMD_ARGC == 1) {
1282                 if (sscanf(CMD_ARGV[0], "%" SCNd8, &tmp) != 1) {
1283                         command_print(CMD_CTX, "Invalid USB address: %s.", CMD_ARGV[0]);
1284                         return ERROR_FAIL;
1285                 }
1286
1287                 if (tmp > JAYLINK_USB_ADDRESS_3) {
1288                         command_print(CMD_CTX, "Invalid USB address: %u.", tmp);
1289                         return ERROR_FAIL;
1290                 }
1291
1292                 tmp_config.usb_address = tmp;
1293         } else {
1294                 command_print(CMD_CTX, "Need exactly one argument for jlink config "
1295                         "usb.");
1296                 return ERROR_COMMAND_SYNTAX_ERROR;
1297         }
1298
1299         return ERROR_OK;
1300 }
1301
1302 COMMAND_HANDLER(jlink_handle_config_target_power_command)
1303 {
1304         int enable;
1305
1306         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1307                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1308                         "device.");
1309                 return ERROR_OK;
1310         }
1311
1312         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER)) {
1313                 command_print(CMD_CTX, "Target power supply is not supported by the "
1314                         "device.");
1315                 return ERROR_OK;
1316         }
1317
1318         if (!CMD_ARGC) {
1319                 show_config_target_power(CMD_CTX);
1320         } else if (CMD_ARGC == 1) {
1321                 if (!strcmp(CMD_ARGV[0], "on")) {
1322                         enable = true;
1323                 } else if (!strcmp(CMD_ARGV[0], "off")) {
1324                         enable = false;
1325                 } else {
1326                         command_print(CMD_CTX, "Invalid argument: %s.", CMD_ARGV[0]);
1327                         return ERROR_FAIL;
1328                 }
1329
1330                 tmp_config.target_power = enable;
1331         } else {
1332                 command_print(CMD_CTX, "Need exactly one argument for jlink config "
1333                         "targetpower.");
1334                 return ERROR_COMMAND_SYNTAX_ERROR;
1335         }
1336
1337         return ERROR_OK;
1338 }
1339
1340 COMMAND_HANDLER(jlink_handle_config_mac_address_command)
1341 {
1342         uint8_t addr[6];
1343         int i;
1344         char *e;
1345         const char *str;
1346
1347         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1348                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1349                         "device.");
1350                 return ERROR_OK;
1351         }
1352
1353         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1354                 command_print(CMD_CTX, "Ethernet connectivity is not supported by the "
1355                         "device.");
1356                 return ERROR_OK;
1357         }
1358
1359         if (!CMD_ARGC) {
1360                 show_config_mac_address(CMD_CTX);
1361         } else if (CMD_ARGC == 1) {
1362                 str = CMD_ARGV[0];
1363
1364                 if ((strlen(str) != 17) || (str[2] != ':' || str[5] != ':' || \
1365                                 str[8] != ':' || str[11] != ':' || str[14] != ':')) {
1366                         command_print(CMD_CTX, "Invalid MAC address format.");
1367                         return ERROR_COMMAND_SYNTAX_ERROR;
1368                 }
1369
1370                 for (i = 5; i >= 0; i--) {
1371                         addr[i] = strtoul(str, &e, 16);
1372                         str = e + 1;
1373                 }
1374
1375                 if (!(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5])) {
1376                         command_print(CMD_CTX, "Invalid MAC address: zero address.");
1377                         return ERROR_COMMAND_SYNTAX_ERROR;
1378                 }
1379
1380                 if (!(0x01 & addr[0])) {
1381                         command_print(CMD_CTX, "Invalid MAC address: multicast address.");
1382                         return ERROR_COMMAND_SYNTAX_ERROR;
1383                 }
1384
1385                 memcpy(tmp_config.mac_address, addr, sizeof(addr));
1386         } else {
1387                 command_print(CMD_CTX, "Need exactly one argument for jlink config "
1388                         " mac.");
1389                 return ERROR_COMMAND_SYNTAX_ERROR;
1390         }
1391
1392         return ERROR_OK;
1393 }
1394
1395 static bool string_to_ip(const char *s, uint8_t *ip, int *pos)
1396 {
1397         uint8_t lip[4];
1398         char *e;
1399         const char *s_save = s;
1400         int i;
1401
1402         if (!s)
1403                 return false;
1404
1405         for (i = 0; i < 4; i++) {
1406                 lip[i] = strtoul(s, &e, 10);
1407
1408                 if (*e != '.' && i != 3)
1409                         return false;
1410
1411                 s = e + 1;
1412         }
1413
1414         *pos = e - s_save;
1415         memcpy(ip, lip, sizeof(lip));
1416
1417         return true;
1418 }
1419
1420 static void cpy_ip(uint8_t *dst, uint8_t *src)
1421 {
1422         int i, j;
1423
1424         for (i = 0, j = 3; i < 4; i++, j--)
1425                 dst[i] = src[j];
1426 }
1427
1428 COMMAND_HANDLER(jlink_handle_config_ip_address_command)
1429 {
1430         uint8_t ip_address[4];
1431         uint32_t subnet_mask = 0;
1432         int i, len;
1433         uint8_t subnet_bits = 24;
1434
1435         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1436                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1437                         "device.");
1438                 return ERROR_OK;
1439         }
1440
1441         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1442                 command_print(CMD_CTX, "Ethernet connectivity is not supported by the "
1443                         "device.");
1444                 return ERROR_OK;
1445         }
1446
1447         if (!CMD_ARGC) {
1448                 show_config_ip_address(CMD_CTX);
1449         } else {
1450                 if (!string_to_ip(CMD_ARGV[0], ip_address, &i))
1451                         return ERROR_COMMAND_SYNTAX_ERROR;
1452
1453                 len = strlen(CMD_ARGV[0]);
1454
1455                 /* Check for format A.B.C.D/E. */
1456                 if (i < len) {
1457                         if (CMD_ARGV[0][i] != '/')
1458                                 return ERROR_COMMAND_SYNTAX_ERROR;
1459
1460                         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[0] + i + 1, subnet_bits);
1461                 } else if (CMD_ARGC > 1) {
1462                         if (!string_to_ip(CMD_ARGV[1], (uint8_t *)&subnet_mask, &i))
1463                                 return ERROR_COMMAND_SYNTAX_ERROR;
1464                 }
1465
1466                 if (!subnet_mask)
1467                         subnet_mask = (uint32_t)(subnet_bits < 32 ?
1468                                 ((1ULL << subnet_bits) - 1) : 0xffffffff);
1469
1470                 cpy_ip(tmp_config.ip_address, ip_address);
1471                 cpy_ip(tmp_config.subnet_mask, (uint8_t *)&subnet_mask);
1472         }
1473
1474         return ERROR_OK;
1475 }
1476
1477 COMMAND_HANDLER(jlink_handle_config_reset_command)
1478 {
1479         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG))
1480                 return ERROR_OK;
1481
1482         memcpy(&tmp_config, &config, sizeof(struct device_config));
1483
1484         return ERROR_OK;
1485 }
1486
1487
1488 COMMAND_HANDLER(jlink_handle_config_write_command)
1489 {
1490         int ret;
1491
1492         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1493                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1494                         "device.");
1495                 return ERROR_OK;
1496         }
1497
1498         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_WRITE_CONFIG)) {
1499                 command_print(CMD_CTX, "Writing configuration is not supported by the "
1500                         "device.");
1501                 return ERROR_OK;
1502         }
1503
1504         if (!memcmp(&config, &tmp_config, sizeof(struct device_config))) {
1505                 command_print(CMD_CTX, "Operation not performed due to no changes in "
1506                         "the configuration.");
1507                 return ERROR_OK;
1508         }
1509
1510         ret = jaylink_write_raw_config(devh, (const uint8_t *)&tmp_config);
1511
1512         if (ret != JAYLINK_OK) {
1513                 LOG_ERROR("jaylink_write_raw_config() failed: %s.",
1514                         jaylink_strerror_name(ret));
1515                 return ERROR_FAIL;
1516         }
1517
1518         if (!read_device_config(&config)) {
1519                 LOG_ERROR("Failed to read device configuration for verification.");
1520                 return ERROR_FAIL;
1521         }
1522
1523         if (memcmp(&config, &tmp_config, sizeof(struct device_config))) {
1524                 LOG_ERROR("Verification of device configuration failed. Please check "
1525                         "your device.");
1526                 return ERROR_FAIL;
1527         }
1528
1529         memcpy(&tmp_config, &config, sizeof(struct device_config));
1530         command_print(CMD_CTX, "The new device configuration applies after power "
1531                 "cycling the J-Link device.");
1532
1533         return ERROR_OK;
1534 }
1535
1536 COMMAND_HANDLER(jlink_handle_config_command)
1537 {
1538         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1539                 command_print(CMD_CTX, "Device doesn't support reading configuration.");
1540                 return ERROR_OK;
1541         }
1542
1543         if (CMD_ARGC == 0)
1544                 show_config(CMD_CTX);
1545
1546         return ERROR_OK;
1547 }
1548
1549 static const struct command_registration jlink_config_subcommand_handlers[] = {
1550         {
1551                 .name = "usb",
1552                 .handler = &jlink_handle_config_usb_address_command,
1553                 .mode = COMMAND_EXEC,
1554                 .help = "set the USB address",
1555                 .usage = "[0-3]",
1556         },
1557         {
1558                 .name = "targetpower",
1559                 .handler = &jlink_handle_config_target_power_command,
1560                 .mode = COMMAND_EXEC,
1561                 .help = "set the target power supply",
1562                 .usage = "[on|off]"
1563         },
1564         {
1565                 .name = "mac",
1566                 .handler = &jlink_handle_config_mac_address_command,
1567                 .mode = COMMAND_EXEC,
1568                 .help = "set the MAC Address",
1569                 .usage = "[ff:ff:ff:ff:ff:ff]",
1570         },
1571         {
1572                 .name = "ip",
1573                 .handler = &jlink_handle_config_ip_address_command,
1574                 .mode = COMMAND_EXEC,
1575                 .help = "set the IP address, where A.B.C.D is the IP address, "
1576                         "E the bit of the subnet mask, F.G.H.I the subnet mask",
1577                 .usage = "[A.B.C.D[/E] [F.G.H.I]]",
1578         },
1579         {
1580                 .name = "reset",
1581                 .handler = &jlink_handle_config_reset_command,
1582                 .mode = COMMAND_EXEC,
1583                 .help = "undo configuration changes"
1584         },
1585         {
1586                 .name = "write",
1587                 .handler = &jlink_handle_config_write_command,
1588                 .mode = COMMAND_EXEC,
1589                 .help = "write configuration to the device"
1590         },
1591         COMMAND_REGISTRATION_DONE
1592 };
1593
1594 static const struct command_registration jlink_subcommand_handlers[] = {
1595         {
1596                 .name = "jtag",
1597                 .handler = &jlink_handle_jlink_jtag_command,
1598                 .mode = COMMAND_EXEC,
1599                 .help = "select the JTAG command version",
1600                 .usage = "[2|3]",
1601         },
1602         {
1603                 .name = "targetpower",
1604                 .handler = &jlink_handle_target_power_command,
1605                 .mode = COMMAND_EXEC,
1606                 .help = "set the target power supply",
1607                 .usage = "<on|off>"
1608         },
1609         {
1610                 .name = "freemem",
1611                 .handler = &jlink_handle_free_memory_command,
1612                 .mode = COMMAND_EXEC,
1613                 .help = "show free device memory"
1614         },
1615         {
1616                 .name = "hwstatus",
1617                 .handler = &jlink_handle_hwstatus_command,
1618                 .mode = COMMAND_EXEC,
1619                 .help = "show the hardware status"
1620         },
1621         {
1622                 .name = "usb",
1623                 .handler = &jlink_usb_command,
1624                 .mode = COMMAND_CONFIG,
1625                 .help = "set the USB address of the device that should be used",
1626                 .usage = "<0-3>"
1627         },
1628         {
1629                 .name = "serial",
1630                 .handler = &jlink_serial_command,
1631                 .mode = COMMAND_CONFIG,
1632                 .help = "set the serial number of the device that should be used",
1633                 .usage = "<serial number>"
1634         },
1635         {
1636                 .name = "config",
1637                 .handler = &jlink_handle_config_command,
1638                 .mode = COMMAND_EXEC,
1639                 .help = "access the device configuration. If no argument is given "
1640                         "this will show the device configuration",
1641                 .chain = jlink_config_subcommand_handlers,
1642         },
1643         COMMAND_REGISTRATION_DONE
1644 };
1645
1646 static const struct command_registration jlink_command_handlers[] = {
1647         {
1648                 .name = "jlink",
1649                 .mode = COMMAND_ANY,
1650                 .help = "perform jlink management",
1651                 .chain = jlink_subcommand_handlers,
1652         },
1653         COMMAND_REGISTRATION_DONE
1654 };
1655
1656 static int jlink_swd_init(void)
1657 {
1658         iface = JAYLINK_TIF_SWD;
1659
1660         return ERROR_OK;
1661 }
1662
1663 static void jlink_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
1664 {
1665         assert(!(cmd & SWD_CMD_RnW));
1666         jlink_swd_queue_cmd(cmd, NULL, value, ap_delay_clk);
1667 }
1668
1669 static void jlink_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
1670 {
1671         assert(cmd & SWD_CMD_RnW);
1672         jlink_swd_queue_cmd(cmd, value, 0, ap_delay_clk);
1673 }
1674
1675 static int_least32_t jlink_swd_frequency(int_least32_t hz)
1676 {
1677         if (hz > 0)
1678                 jlink_speed(hz / 1000);
1679
1680         return hz;
1681 }
1682
1683 /***************************************************************************/
1684 /* J-Link tap functions */
1685
1686 static unsigned tap_length;
1687 /* In SWD mode use tms buffer for direction control */
1688 static uint8_t tms_buffer[JLINK_TAP_BUFFER_SIZE];
1689 static uint8_t tdi_buffer[JLINK_TAP_BUFFER_SIZE];
1690 static uint8_t tdo_buffer[JLINK_TAP_BUFFER_SIZE];
1691
1692 struct pending_scan_result {
1693         /** First bit position in tdo_buffer to read. */
1694         unsigned first;
1695         /** Number of bits to read. */
1696         unsigned length;
1697         /** Location to store the result */
1698         void *buffer;
1699         /** Offset in the destination buffer */
1700         unsigned buffer_offset;
1701 };
1702
1703 #define MAX_PENDING_SCAN_RESULTS 256
1704
1705 static int pending_scan_results_length;
1706 static struct pending_scan_result pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
1707
1708 static void jlink_tap_init(void)
1709 {
1710         tap_length = 0;
1711         pending_scan_results_length = 0;
1712         memset(tms_buffer, 0, sizeof(tdi_buffer));
1713 }
1714
1715 static void jlink_clock_data(const uint8_t *out, unsigned out_offset,
1716                              const uint8_t *tms_out, unsigned tms_offset,
1717                              uint8_t *in, unsigned in_offset,
1718                              unsigned length)
1719 {
1720         do {
1721                 unsigned available_length = JLINK_TAP_BUFFER_SIZE - tap_length / 8;
1722
1723                 if (!available_length ||
1724                     (in && pending_scan_results_length == MAX_PENDING_SCAN_RESULTS)) {
1725                         if (jlink_flush() != ERROR_OK)
1726                                 return;
1727                         available_length = JLINK_TAP_BUFFER_SIZE;
1728                 }
1729
1730                 struct pending_scan_result *pending_scan_result =
1731                         &pending_scan_results_buffer[pending_scan_results_length];
1732
1733                 unsigned scan_length = length > available_length ?
1734                         available_length : length;
1735
1736                 if (out)
1737                         buf_set_buf(out, out_offset, tdi_buffer, tap_length, scan_length);
1738                 if (tms_out)
1739                         buf_set_buf(tms_out, tms_offset, tms_buffer, tap_length, scan_length);
1740
1741                 if (in) {
1742                         pending_scan_result->first = tap_length;
1743                         pending_scan_result->length = scan_length;
1744                         pending_scan_result->buffer = in;
1745                         pending_scan_result->buffer_offset = in_offset;
1746                         pending_scan_results_length++;
1747                 }
1748
1749                 tap_length += scan_length;
1750                 out_offset += scan_length;
1751                 tms_offset += scan_length;
1752                 in_offset += scan_length;
1753                 length -= scan_length;
1754         } while (length > 0);
1755 }
1756
1757 static int jlink_flush(void)
1758 {
1759         int i;
1760         int ret;
1761
1762         if (!tap_length)
1763                 return ERROR_OK;
1764
1765         jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
1766                 tap_length, jlink_last_state);
1767
1768         ret = jaylink_jtag_io(devh, tms_buffer, tdi_buffer, tdo_buffer,
1769                 tap_length, jtag_command_version);
1770
1771         if (ret != JAYLINK_OK) {
1772                 LOG_ERROR("jaylink_jtag_io() failed: %s.", jaylink_strerror_name(ret));
1773                 jlink_tap_init();
1774                 return ERROR_JTAG_QUEUE_FAILED;
1775         }
1776
1777         for (i = 0; i < pending_scan_results_length; i++) {
1778                 struct pending_scan_result *p = &pending_scan_results_buffer[i];
1779
1780                 buf_set_buf(tdo_buffer, p->first, p->buffer,
1781                             p->buffer_offset, p->length);
1782
1783                 DEBUG_JTAG_IO("Pending scan result, length = %d.", p->length);
1784         }
1785
1786         jlink_tap_init();
1787
1788         return ERROR_OK;
1789 }
1790
1791 static void fill_buffer(uint8_t *buf, uint32_t val, uint32_t len)
1792 {
1793         unsigned int tap_pos = tap_length;
1794
1795         while (len > 32) {
1796                 buf_set_u32(buf, tap_pos, 32, val);
1797                 len -= 32;
1798                 tap_pos += 32;
1799         }
1800
1801         if (len)
1802                 buf_set_u32(buf, tap_pos, len, val);
1803 }
1804
1805 static void jlink_queue_data_out(const uint8_t *data, uint32_t len)
1806 {
1807         const uint32_t dir_out = 0xffffffff;
1808
1809         if (data)
1810                 bit_copy(tdi_buffer, tap_length, data, 0, len);
1811         else
1812                 fill_buffer(tdi_buffer, 0, len);
1813
1814         fill_buffer(tms_buffer, dir_out, len);
1815         tap_length += len;
1816 }
1817
1818 static void jlink_queue_data_in(uint32_t len)
1819 {
1820         const uint32_t dir_in = 0;
1821
1822         fill_buffer(tms_buffer, dir_in, len);
1823         tap_length += len;
1824 }
1825
1826 static int jlink_swd_switch_seq(enum swd_special_seq seq)
1827 {
1828         const uint8_t *s;
1829         unsigned int s_len;
1830
1831         switch (seq) {
1832                 case LINE_RESET:
1833                         LOG_DEBUG("SWD line reset");
1834                         s = swd_seq_line_reset;
1835                         s_len = swd_seq_line_reset_len;
1836                         break;
1837                 case JTAG_TO_SWD:
1838                         LOG_DEBUG("JTAG-to-SWD");
1839                         s = swd_seq_jtag_to_swd;
1840                         s_len = swd_seq_jtag_to_swd_len;
1841                         break;
1842                 case SWD_TO_JTAG:
1843                         LOG_DEBUG("SWD-to-JTAG");
1844                         s = swd_seq_swd_to_jtag;
1845                         s_len = swd_seq_swd_to_jtag_len;
1846                         break;
1847                 default:
1848                         LOG_ERROR("Sequence %d not supported.", seq);
1849                         return ERROR_FAIL;
1850         }
1851
1852         jlink_queue_data_out(s, s_len);
1853
1854         return ERROR_OK;
1855 }
1856
1857 static int jlink_swd_run_queue(void)
1858 {
1859         int i;
1860         int ret;
1861
1862         LOG_DEBUG("Executing %d queued transactions.", pending_scan_results_length);
1863
1864         if (queued_retval != ERROR_OK) {
1865                 LOG_DEBUG("Skipping due to previous errors: %d.", queued_retval);
1866                 goto skip;
1867         }
1868
1869         /*
1870          * A transaction must be followed by another transaction or at least 8 idle
1871          * cycles to ensure that data is clocked through the AP.
1872          */
1873         jlink_queue_data_out(NULL, 8);
1874
1875         ret = jaylink_swd_io(devh, tms_buffer, tdi_buffer, tdo_buffer, tap_length);
1876
1877         if (ret != JAYLINK_OK) {
1878                 LOG_ERROR("jaylink_swd_io() failed: %s.", jaylink_strerror_name(ret));
1879                 goto skip;
1880         }
1881
1882         for (i = 0; i < pending_scan_results_length; i++) {
1883                 int ack = buf_get_u32(tdo_buffer, pending_scan_results_buffer[i].first, 3);
1884
1885                 if (ack != SWD_ACK_OK) {
1886                         LOG_DEBUG("SWD ack not OK: %d %s", ack,
1887                                   ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
1888                         queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
1889                         goto skip;
1890                 } else if (pending_scan_results_buffer[i].length) {
1891                         uint32_t data = buf_get_u32(tdo_buffer, 3 + pending_scan_results_buffer[i].first, 32);
1892                         int parity = buf_get_u32(tdo_buffer, 3 + 32 + pending_scan_results_buffer[i].first, 1);
1893
1894                         if (parity != parity_u32(data)) {
1895                                 LOG_ERROR("SWD: Read data parity mismatch.");
1896                                 queued_retval = ERROR_FAIL;
1897                                 goto skip;
1898                         }
1899
1900                         if (pending_scan_results_buffer[i].buffer)
1901                                 *(uint32_t *)pending_scan_results_buffer[i].buffer = data;
1902                 }
1903         }
1904
1905 skip:
1906         jlink_tap_init();
1907         ret = queued_retval;
1908         queued_retval = ERROR_OK;
1909
1910         return ret;
1911 }
1912
1913 static void jlink_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk)
1914 {
1915         uint8_t data_parity_trn[DIV_ROUND_UP(32 + 1, 8)];
1916         if (tap_length + 46 + 8 + ap_delay_clk >= sizeof(tdi_buffer) * 8 ||
1917             pending_scan_results_length == MAX_PENDING_SCAN_RESULTS) {
1918                 /* Not enough room in the queue. Run the queue. */
1919                 queued_retval = jlink_swd_run_queue();
1920         }
1921
1922         if (queued_retval != ERROR_OK)
1923                 return;
1924
1925         cmd |= SWD_CMD_START | SWD_CMD_PARK;
1926
1927         jlink_queue_data_out(&cmd, 8);
1928
1929         pending_scan_results_buffer[pending_scan_results_length].first = tap_length;
1930
1931         if (cmd & SWD_CMD_RnW) {
1932                 /* Queue a read transaction. */
1933                 pending_scan_results_buffer[pending_scan_results_length].length = 32;
1934                 pending_scan_results_buffer[pending_scan_results_length].buffer = dst;
1935
1936                 jlink_queue_data_in(1 + 3 + 32 + 1 + 1);
1937         } else {
1938                 /* Queue a write transaction. */
1939                 pending_scan_results_buffer[pending_scan_results_length].length = 0;
1940                 jlink_queue_data_in(1 + 3 + 1);
1941
1942                 buf_set_u32(data_parity_trn, 0, 32, data);
1943                 buf_set_u32(data_parity_trn, 32, 1, parity_u32(data));
1944
1945                 jlink_queue_data_out(data_parity_trn, 32 + 1);
1946         }
1947
1948         pending_scan_results_length++;
1949
1950         /* Insert idle cycles after AP accesses to avoid WAIT. */
1951         if (cmd & SWD_CMD_APnDP)
1952                 jlink_queue_data_out(NULL, ap_delay_clk);
1953 }
1954
1955 static const struct swd_driver jlink_swd = {
1956         .init = &jlink_swd_init,
1957         .frequency = &jlink_swd_frequency,
1958         .switch_seq = &jlink_swd_switch_seq,
1959         .read_reg = &jlink_swd_read_reg,
1960         .write_reg = &jlink_swd_write_reg,
1961         .run = &jlink_swd_run_queue,
1962 };
1963
1964 static const char * const jlink_transports[] = { "jtag", "swd", NULL };
1965
1966 struct jtag_interface jlink_interface = {
1967         .name = "jlink",
1968         .commands = jlink_command_handlers,
1969         .transports = jlink_transports,
1970         .swd = &jlink_swd,
1971         .execute_queue = &jlink_execute_queue,
1972         .speed = &jlink_speed,
1973         .speed_div = &jlink_speed_div,
1974         .khz = &jlink_khz,
1975         .init = &jlink_init,
1976         .quit = &jlink_quit,
1977         .config_trace = &config_trace,
1978         .poll_trace = &poll_trace,
1979 };