]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/jlink.c
drivers: jlink: rework to allow scans of arbitrary length, bump libjaylink
[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 uint8_t usb_address;
55 static bool use_usb_address;
56 static uint8_t 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);
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
517         ret = jaylink_init(&jayctx);
518
519         if (ret != JAYLINK_OK) {
520                 LOG_ERROR("jaylink_init() failed: %s.",
521                         jaylink_strerror_name(ret));
522                 return ERROR_JTAG_INIT_FAILED;
523         }
524
525         ret = jaylink_get_device_list(jayctx, &devs);
526
527         if (ret < 0) {
528                 LOG_ERROR("jaylink_get_device_list() failed: %s.",
529                         jaylink_strerror_name(ret));
530                 jaylink_exit(jayctx);
531                 return ERROR_JTAG_INIT_FAILED;
532         }
533
534         found_device = false;
535
536         if (!use_serial_number && !use_usb_address)
537                 LOG_INFO("No device selected, using first device.");
538
539         for (i = 0; devs[i]; i++) {
540                 jaylink_device_get_serial_number(devs[i], &tmp);
541                 ret = jaylink_device_get_usb_address(devs[i]);
542
543                 if (use_usb_address && usb_address != ret)
544                         continue;
545
546                 if (use_serial_number && tmp != serial_number)
547                         continue;
548
549                 ret = jaylink_open(devs[i], &devh);
550
551                 if (ret != JAYLINK_OK) {
552                         LOG_ERROR("Failed to open device: %s.", jaylink_strerror_name(ret));
553                         continue;
554                 }
555
556                 found_device = true;
557                 break;
558         }
559
560         jaylink_free_device_list(devs, 1);
561
562         if (!found_device) {
563                 LOG_ERROR("No J-Link device found.");
564                 jaylink_exit(jayctx);
565                 return ERROR_JTAG_INIT_FAILED;
566         }
567
568         /*
569          * Be careful with changing the following initialization sequence because
570          * some devices are known to be sensitive regarding the order.
571          */
572
573         ret = jaylink_get_firmware_version(devh, &firmware_version);
574
575         if (ret > 0) {
576                 LOG_INFO("%s", firmware_version);
577                 free(firmware_version);
578         } else if (!ret) {
579                 LOG_WARNING("Device responds empty firmware version string.");
580         } else {
581                 LOG_ERROR("jaylink_get_firmware_version() failed: %s.",
582                         jaylink_strerror_name(ret));
583                 jaylink_close(devh);
584                 jaylink_exit(jayctx);
585                 return ERROR_JTAG_INIT_FAILED;
586         }
587
588         memset(caps, 0, JAYLINK_DEV_EXT_CAPS_SIZE);
589         ret = jaylink_get_caps(devh, caps);
590
591         if (ret != JAYLINK_OK) {
592                 LOG_ERROR("jaylink_get_caps() failed: %s.", jaylink_strerror_name(ret));
593                 jaylink_close(devh);
594                 jaylink_exit(jayctx);
595                 return ERROR_JTAG_INIT_FAILED;
596         }
597
598         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_EXT_CAPS)) {
599                 ret = jaylink_get_extended_caps(devh, caps);
600
601                 if (ret != JAYLINK_OK) {
602                         LOG_ERROR("jaylink_get_extended_caps() failed:  %s.",
603                                 jaylink_strerror_name(ret));
604                         jaylink_close(devh);
605                         jaylink_exit(jayctx);
606                         return ERROR_JTAG_INIT_FAILED;
607                 }
608         }
609
610         jtag_command_version = JAYLINK_JTAG_V2;
611
612         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_HW_VERSION)) {
613                 ret = jaylink_get_hardware_version(devh, &hwver);
614
615                 if (ret != JAYLINK_OK) {
616                         LOG_ERROR("Failed to retrieve hardware version: %s.",
617                                 jaylink_strerror_name(ret));
618                         jaylink_close(devh);
619                         jaylink_exit(jayctx);
620                         return ERROR_JTAG_INIT_FAILED;
621                 }
622
623                 LOG_INFO("Hardware version: %u.%02u", hwver.major, hwver.minor);
624
625                 if (hwver.major >= 5)
626                         jtag_command_version = JAYLINK_JTAG_V3;
627         }
628
629         if (iface == JAYLINK_TIF_SWD) {
630                 /*
631                  * Adjust the SWD transaction buffer size in case there is already
632                  * allocated memory on the device. This happens for example if the
633                  * memory for SWO capturing is still allocated because the software
634                  * which used the device before has not been shut down properly.
635                  */
636                 if (!adjust_swd_buffer_size()) {
637                         jaylink_close(devh);
638                         jaylink_exit(jayctx);
639                         return ERROR_JTAG_INIT_FAILED;
640                 }
641         }
642
643         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
644                 if (!read_device_config(&config)) {
645                         LOG_ERROR("Failed to read device configuration data.");
646                         jaylink_close(devh);
647                         jaylink_exit(jayctx);
648                         return ERROR_JTAG_INIT_FAILED;
649                 }
650
651                 memcpy(&tmp_config, &config, sizeof(struct device_config));
652         }
653
654         ret = jaylink_get_hardware_status(devh, &hwstatus);
655
656         if (ret != JAYLINK_OK) {
657                 LOG_ERROR("jaylink_get_hardware_status() failed: %s.",
658                         jaylink_strerror_name(ret));
659                 jaylink_close(devh);
660                 jaylink_exit(jayctx);
661                 return ERROR_JTAG_INIT_FAILED;
662         }
663
664         LOG_INFO("VTarget = %u.%03u V", hwstatus.target_voltage / 1000,
665                 hwstatus.target_voltage % 1000);
666
667         conn.handle = 0;
668         conn.pid = 0;
669         conn.hid = 0;
670         conn.iid = 0;
671         conn.cid = 0;
672
673         ret = jlink_register();
674
675         if (ret != ERROR_OK) {
676                 jaylink_close(devh);
677                 jaylink_exit(jayctx);
678                 return ERROR_JTAG_INIT_FAILED;
679         }
680
681         ret = select_interface();
682
683         if (ret != ERROR_OK) {
684                 jaylink_close(devh);
685                 jaylink_exit(jayctx);
686                 return ret;
687         }
688
689         jlink_reset(0, 0);
690         jtag_sleep(3000);
691         jlink_tap_init();
692
693         jlink_speed(jtag_get_speed_khz());
694
695         if (iface == JAYLINK_TIF_JTAG) {
696                 /*
697                  * J-Link devices with firmware version v5 and v6 seems to have an issue
698                  * if the first tap move is not divisible by 8, so we send a TLR on
699                  * first power up.
700                  */
701                 uint8_t tms = 0xff;
702                 jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 8);
703
704                 jlink_flush();
705         }
706
707         return ERROR_OK;
708 }
709
710 static int jlink_quit(void)
711 {
712         int ret;
713
714         if (trace_enabled) {
715                 ret = jaylink_swo_stop(devh);
716
717                 if (ret != JAYLINK_OK)
718                         LOG_ERROR("jaylink_swo_stop() failed: %s.",
719                                 jaylink_strerror_name(ret));
720         }
721
722         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_REGISTER)) {
723                 ret = jaylink_unregister(devh, &conn, connlist, NULL, NULL);
724
725                 if (ret < 0)
726                         LOG_ERROR("jaylink_unregister() failed: %s.",
727                                 jaylink_strerror_name(ret));
728         }
729
730         jaylink_close(devh);
731         jaylink_exit(jayctx);
732
733         return ERROR_OK;
734 }
735
736 /***************************************************************************/
737 /* Queue command implementations */
738
739 static void jlink_end_state(tap_state_t state)
740 {
741         if (tap_is_state_stable(state))
742                 tap_set_end_state(state);
743         else {
744                 LOG_ERROR("BUG: %i is not a valid end state", state);
745                 exit(-1);
746         }
747 }
748
749 /* Goes to the end state. */
750 static void jlink_state_move(void)
751 {
752         uint8_t tms_scan;
753         uint8_t tms_scan_bits;
754
755         tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
756         tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
757
758         jlink_clock_data(NULL, 0, &tms_scan, 0, NULL, 0, tms_scan_bits);
759
760         tap_set_state(tap_get_end_state());
761 }
762
763 static void jlink_path_move(int num_states, tap_state_t *path)
764 {
765         int i;
766         uint8_t tms = 0xff;
767
768         for (i = 0; i < num_states; i++) {
769                 if (path[i] == tap_state_transition(tap_get_state(), false))
770                         jlink_clock_data(NULL, 0, NULL, 0, NULL, 0, 1);
771                 else if (path[i] == tap_state_transition(tap_get_state(), true))
772                         jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 1);
773                 else {
774                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
775                                 tap_state_name(tap_get_state()), tap_state_name(path[i]));
776                         exit(-1);
777                 }
778
779                 tap_set_state(path[i]);
780         }
781
782         tap_set_end_state(tap_get_state());
783 }
784
785 static void jlink_stableclocks(int num_cycles)
786 {
787         int i;
788
789         uint8_t tms = tap_get_state() == TAP_RESET;
790         /* Execute num_cycles. */
791         for (i = 0; i < num_cycles; i++)
792                 jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 1);
793 }
794
795 static void jlink_runtest(int num_cycles)
796 {
797         tap_state_t saved_end_state = tap_get_end_state();
798
799         /* Only do a state_move when we're not already in IDLE. */
800         if (tap_get_state() != TAP_IDLE) {
801                 jlink_end_state(TAP_IDLE);
802                 jlink_state_move();
803                 /* num_cycles--; */
804         }
805
806         jlink_stableclocks(num_cycles);
807
808         /* Finish in end_state. */
809         jlink_end_state(saved_end_state);
810
811         if (tap_get_state() != tap_get_end_state())
812                 jlink_state_move();
813 }
814
815 static void jlink_reset(int trst, int srst)
816 {
817         LOG_DEBUG("TRST: %i, SRST: %i.", trst, srst);
818
819         /* Signals are active low. */
820         if (srst == 0)
821                 jaylink_set_reset(devh);
822
823         if (srst == 1)
824                 jaylink_clear_reset(devh);
825
826         if (trst == 1)
827                 jaylink_jtag_clear_trst(devh);
828
829         if (trst == 0)
830                 jaylink_jtag_set_trst(devh);
831 }
832
833 COMMAND_HANDLER(jlink_usb_command)
834 {
835         if (CMD_ARGC != 1) {
836                 command_print(CMD_CTX, "Need exactly one argument for jlink usb.");
837                 return ERROR_COMMAND_SYNTAX_ERROR;
838         }
839
840         if (sscanf(CMD_ARGV[0], "%" SCNd8, &usb_address) != 1) {
841                 command_print(CMD_CTX, "Invalid USB address: %s.", CMD_ARGV[0]);
842                 return ERROR_FAIL;
843         }
844
845         if (usb_address > JAYLINK_USB_ADDRESS_3) {
846                 command_print(CMD_CTX, "Invalid USB address: %s.", CMD_ARGV[0]);
847                 return ERROR_FAIL;
848         }
849
850         use_serial_number = false;
851         use_usb_address = true;
852
853         return ERROR_OK;
854 }
855
856 COMMAND_HANDLER(jlink_serial_command)
857 {
858         if (CMD_ARGC != 1) {
859                 command_print(CMD_CTX, "Need exactly one argument for jlink serial.");
860                 return ERROR_COMMAND_SYNTAX_ERROR;
861         }
862
863         if (sscanf(CMD_ARGV[0], "%" SCNd32, &serial_number) != 1) {
864                 command_print(CMD_CTX, "Invalid serial number: %s.", CMD_ARGV[0]);
865                 return ERROR_FAIL;
866         }
867
868         use_serial_number = true;
869         use_usb_address = false;
870
871         return ERROR_OK;
872 }
873
874 COMMAND_HANDLER(jlink_handle_hwstatus_command)
875 {
876         int ret;
877         struct jaylink_hardware_status status;
878
879         ret = jaylink_get_hardware_status(devh, &status);
880
881         if (ret != JAYLINK_OK) {
882                 command_print(CMD_CTX, "jaylink_get_hardware_status() failed: %s.",
883                         jaylink_strerror_name(ret));
884                 return ERROR_FAIL;
885         }
886
887         command_print(CMD_CTX, "VTarget = %u.%03u V",
888                 status.target_voltage / 1000, status.target_voltage % 1000);
889
890         command_print(CMD_CTX, "TCK = %u TDI = %u TDO = %u TMS = %u SRST = %u "
891                 "TRST = %u", status.tck, status.tdi, status.tdo, status.tms,
892                 status.tres, status.trst);
893
894         if (status.target_voltage < 1500)
895                 command_print(CMD_CTX, "Target voltage too low. Check target power.");
896
897         return ERROR_OK;
898 }
899
900 COMMAND_HANDLER(jlink_handle_free_memory_command)
901 {
902         int ret;
903         uint32_t tmp;
904
905         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY)) {
906                 command_print(CMD_CTX, "Retrieval of free memory is not supported by "
907                         "the device.");
908                 return ERROR_OK;
909         }
910
911         ret = jaylink_get_free_memory(devh, &tmp);
912
913         if (ret != JAYLINK_OK) {
914                 command_print(CMD_CTX, "jaylink_get_free_memory() failed: %s.",
915                         jaylink_strerror_name(ret));
916                 return ERROR_FAIL;
917         }
918
919         command_print(CMD_CTX, "Device has %u bytes of free memory.", tmp);
920
921         return ERROR_OK;
922 }
923
924 COMMAND_HANDLER(jlink_handle_jlink_jtag_command)
925 {
926         int tmp;
927         int version;
928
929         if (!CMD_ARGC) {
930                 switch (jtag_command_version) {
931                         case JAYLINK_JTAG_V2:
932                                 version = 2;
933                                 break;
934                         case JAYLINK_JTAG_V3:
935                                 version = 3;
936                                 break;
937                         default:
938                                 return ERROR_FAIL;
939                 }
940
941                 command_print(CMD_CTX, "JTAG command version: %i", version);
942         } else if (CMD_ARGC == 1) {
943                 if (sscanf(CMD_ARGV[0], "%i", &tmp) != 1) {
944                         command_print(CMD_CTX, "Invalid argument: %s.", CMD_ARGV[0]);
945                         return ERROR_COMMAND_SYNTAX_ERROR;
946                 }
947
948                 switch (tmp) {
949                         case 2:
950                                 jtag_command_version = JAYLINK_JTAG_V2;
951                                 break;
952                         case 3:
953                                 jtag_command_version = JAYLINK_JTAG_V3;
954                                 break;
955                         default:
956                                 command_print(CMD_CTX, "Invalid argument: %s.", CMD_ARGV[0]);
957                                 return ERROR_COMMAND_SYNTAX_ERROR;
958                 }
959         } else {
960                 command_print(CMD_CTX, "Need exactly one argument for jlink jtag.");
961                 return ERROR_COMMAND_SYNTAX_ERROR;
962         }
963
964         return ERROR_OK;
965 }
966
967 COMMAND_HANDLER(jlink_handle_target_power_command)
968 {
969         int ret;
970         int enable;
971
972         if (CMD_ARGC != 1) {
973                 command_print(CMD_CTX, "Need exactly one argument for jlink "
974                         "targetpower.");
975                 return ERROR_COMMAND_SYNTAX_ERROR;
976         }
977
978         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER)) {
979                 command_print(CMD_CTX, "Target power supply is not supported by the "
980                         "device.");
981                 return ERROR_OK;
982         }
983
984         if (!strcmp(CMD_ARGV[0], "on")) {
985                 enable = true;
986         } else if (!strcmp(CMD_ARGV[0], "off")) {
987                 enable = false;
988         } else {
989                 command_print(CMD_CTX, "Invalid argument: %s.", CMD_ARGV[0]);
990                 return ERROR_FAIL;
991         }
992
993         ret = jaylink_set_target_power(devh, enable);
994
995         if (ret != JAYLINK_OK) {
996                 command_print(CMD_CTX, "jaylink_set_target_power() failed: %s.",
997                         jaylink_strerror_name(ret));
998                 return ERROR_FAIL;
999         }
1000
1001         return ERROR_OK;
1002 }
1003
1004 static void show_config_usb_address(struct command_context *ctx)
1005 {
1006         if (config.usb_address != tmp_config.usb_address)
1007                 command_print(ctx, "USB address: %u [%u]", config.usb_address,
1008                         tmp_config.usb_address);
1009         else
1010                 command_print(ctx, "USB address: %u", config.usb_address);
1011 }
1012
1013 static void show_config_ip_address(struct command_context *ctx)
1014 {
1015         if (!memcmp(config.ip_address, tmp_config.ip_address, 4))
1016                 command_print(ctx, "IP address: %d.%d.%d.%d",
1017                         config.ip_address[3], config.ip_address[2],
1018                         config.ip_address[1], config.ip_address[0]);
1019         else
1020                 command_print(ctx, "IP address: %d.%d.%d.%d [%d.%d.%d.%d]",
1021                         config.ip_address[3], config.ip_address[2],
1022                         config.ip_address[1], config.ip_address[0],
1023                         tmp_config.ip_address[3], tmp_config.ip_address[2],
1024                         tmp_config.ip_address[1], tmp_config.ip_address[0]);
1025
1026         if (!memcmp(config.subnet_mask, tmp_config.subnet_mask, 4))
1027                 command_print(ctx, "Subnet mask: %d.%d.%d.%d",
1028                         config.subnet_mask[3], config.subnet_mask[2],
1029                         config.subnet_mask[1], config.subnet_mask[0]);
1030         else
1031                 command_print(ctx, "Subnet mask: %d.%d.%d.%d [%d.%d.%d.%d]",
1032                         config.subnet_mask[3], config.subnet_mask[2],
1033                         config.subnet_mask[1], config.subnet_mask[0],
1034                         tmp_config.subnet_mask[3], tmp_config.subnet_mask[2],
1035                         tmp_config.subnet_mask[1], tmp_config.subnet_mask[0]);
1036 }
1037
1038 static void show_config_mac_address(struct command_context *ctx)
1039 {
1040         if (!memcmp(config.mac_address, tmp_config.mac_address, 6))
1041                 command_print(ctx, "MAC address: %.02x:%.02x:%.02x:%.02x:%.02x:%.02x",
1042                         config.mac_address[5], config.mac_address[4],
1043                         config.mac_address[3], config.mac_address[2],
1044                         config.mac_address[1], config.mac_address[0]);
1045         else
1046                 command_print(ctx, "MAC address: %.02x:%.02x:%.02x:%.02x:%.02x:%.02x "
1047                         "[%.02x:%.02x:%.02x:%.02x:%.02x:%.02x]",
1048                         config.mac_address[5], config.mac_address[4],
1049                         config.mac_address[3], config.mac_address[2],
1050                         config.mac_address[1], config.mac_address[0],
1051                         tmp_config.mac_address[5], tmp_config.mac_address[4],
1052                         tmp_config.mac_address[3], tmp_config.mac_address[2],
1053                         tmp_config.mac_address[1], tmp_config.mac_address[0]);
1054 }
1055
1056 static void show_config_target_power(struct command_context *ctx)
1057 {
1058         const char *target_power;
1059         const char *current_target_power;
1060
1061         if (!config.target_power)
1062                 target_power = "off";
1063         else
1064                 target_power = "on";
1065
1066         if (!tmp_config.target_power)
1067                 current_target_power = "off";
1068         else
1069                 current_target_power = "on";
1070
1071         if (config.target_power != tmp_config.target_power)
1072                 command_print(ctx, "Target power supply: %s [%s]", target_power,
1073                         current_target_power);
1074         else
1075                 command_print(ctx, "Target power supply: %s", target_power);
1076 }
1077
1078 static void show_config(struct command_context *ctx)
1079 {
1080         command_print(ctx, "J-Link device configuration:");
1081
1082         show_config_usb_address(ctx);
1083
1084         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER))
1085                 show_config_target_power(ctx);
1086
1087         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1088                 show_config_ip_address(ctx);
1089                 show_config_mac_address(ctx);
1090         }
1091 }
1092
1093 static int poll_trace(uint8_t *buf, size_t *size)
1094 {
1095         int ret;
1096         uint32_t length;
1097
1098         length = *size;
1099
1100         ret = jaylink_swo_read(devh, buf, &length);
1101
1102         if (ret != JAYLINK_OK) {
1103                 LOG_ERROR("jaylink_swo_read() failed: %s.", jaylink_strerror_name(ret));
1104                 return ERROR_FAIL;
1105         }
1106
1107         *size = length;
1108
1109         return ERROR_OK;
1110 }
1111
1112 static uint32_t calculate_trace_buffer_size(void)
1113 {
1114         int ret;
1115         uint32_t tmp;
1116
1117         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY))
1118                 return 0;
1119
1120         ret = jaylink_get_free_memory(devh, &tmp);
1121
1122         if (ret != JAYLINK_OK) {
1123                 LOG_ERROR("jaylink_get_free_memory() failed: %s.",
1124                         jaylink_strerror_name(ret));
1125                 return ERROR_FAIL;
1126         }
1127
1128         if (tmp > 0x3fff || tmp <= 0x600)
1129                 tmp = tmp >> 1;
1130         else
1131                 tmp = tmp - 0x400;
1132
1133         return tmp & 0xffffff00;
1134 }
1135
1136 static bool check_trace_freq(uint32_t freq, uint32_t divider, uint32_t trace_freq)
1137 {
1138         double min;
1139         double deviation;
1140
1141         min = fabs(1.0 - (freq / ((double)trace_freq * divider)));
1142
1143         while (freq / divider > 0) {
1144                 deviation = fabs(1.0 - (freq / ((double)trace_freq * divider)));
1145
1146                 if (deviation < 0.03) {
1147                         LOG_DEBUG("Found suitable frequency divider %u with deviation of "
1148                                 "%.02f %%.", divider, deviation);
1149                         return true;
1150                 }
1151
1152                 if (deviation < min)
1153                         min = deviation;
1154
1155                 divider++;
1156         }
1157
1158         LOG_ERROR("Selected trace frequency is not supported by the device. "
1159                 "Please choose a different trace frequency.");
1160         LOG_ERROR("Maximum permitted deviation is 3.00 %%, but only %.02f %% "
1161                 "could be achieved.", min * 100);
1162
1163         return false;
1164 }
1165
1166 static int config_trace(bool enabled, enum tpio_pin_protocol pin_protocol,
1167                 uint32_t port_size, unsigned int *trace_freq)
1168 {
1169         int ret;
1170         uint32_t buffer_size;
1171         uint32_t freq;
1172         uint32_t divider;
1173
1174         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SWO)) {
1175                 LOG_ERROR("Trace capturing is not supported by the device.");
1176                 return ERROR_FAIL;
1177         }
1178
1179         if (pin_protocol != ASYNC_UART) {
1180                 LOG_ERROR("Selected pin protocol is not supported.");
1181                 return ERROR_FAIL;
1182         }
1183
1184         trace_enabled = enabled;
1185
1186         ret = jaylink_swo_stop(devh);
1187
1188         if (ret != JAYLINK_OK) {
1189                 LOG_ERROR("jaylink_swo_stop() failed: %s.", jaylink_strerror_name(ret));
1190                 return ERROR_FAIL;
1191         }
1192
1193         if (!enabled) {
1194                 /*
1195                  * Adjust the SWD transaction buffer size as stopping SWO capturing
1196                  * deallocates device internal memory.
1197                  */
1198                 if (!adjust_swd_buffer_size())
1199                         return ERROR_FAIL;
1200
1201                 return ERROR_OK;
1202         }
1203
1204         buffer_size = calculate_trace_buffer_size();
1205
1206         if (!buffer_size) {
1207                 LOG_ERROR("Not enough free device memory to start trace capturing.");
1208                 return ERROR_FAIL;
1209         }
1210
1211         ret = jaylink_swo_get_speeds(devh, JAYLINK_SWO_MODE_UART, &freq, &divider);
1212
1213         if (ret != JAYLINK_OK) {
1214                 LOG_ERROR("jaylink_swo_get_speeds() failed: %s.",
1215                         jaylink_strerror_name(ret));
1216                 return ERROR_FAIL;
1217         }
1218
1219         if (!*trace_freq)
1220                 *trace_freq = freq / divider;
1221
1222         if (!check_trace_freq(freq, divider, *trace_freq))
1223                 return ERROR_FAIL;
1224
1225         LOG_DEBUG("Using %u bytes device memory for trace capturing.", buffer_size);
1226
1227         ret = jaylink_swo_start(devh, JAYLINK_SWO_MODE_UART, *trace_freq,
1228                 buffer_size);
1229
1230         if (ret != JAYLINK_OK) {
1231                 LOG_ERROR("jaylink_start_swo() failed: %s.",
1232                         jaylink_strerror_name(ret));
1233                 return ERROR_FAIL;
1234         }
1235
1236         /*
1237          * Adjust the SWD transaction buffer size as starting SWO capturing
1238          * allocates device internal memory.
1239          */
1240         if (!adjust_swd_buffer_size())
1241                 return ERROR_FAIL;
1242
1243         return ERROR_OK;
1244 }
1245
1246 COMMAND_HANDLER(jlink_handle_config_usb_address_command)
1247 {
1248         uint8_t tmp;
1249
1250         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1251                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1252                         "device.");
1253                 return ERROR_OK;
1254         }
1255
1256         if (!CMD_ARGC) {
1257                 show_config_usb_address(CMD_CTX);
1258         } else if (CMD_ARGC == 1) {
1259                 if (sscanf(CMD_ARGV[0], "%" SCNd8, &tmp) != 1) {
1260                         command_print(CMD_CTX, "Invalid USB address: %s.", CMD_ARGV[0]);
1261                         return ERROR_FAIL;
1262                 }
1263
1264                 if (tmp > JAYLINK_USB_ADDRESS_3) {
1265                         command_print(CMD_CTX, "Invalid USB address: %u.", tmp);
1266                         return ERROR_FAIL;
1267                 }
1268
1269                 tmp_config.usb_address = tmp;
1270         } else {
1271                 command_print(CMD_CTX, "Need exactly one argument for jlink config "
1272                         "usb.");
1273                 return ERROR_COMMAND_SYNTAX_ERROR;
1274         }
1275
1276         return ERROR_OK;
1277 }
1278
1279 COMMAND_HANDLER(jlink_handle_config_target_power_command)
1280 {
1281         int enable;
1282
1283         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1284                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1285                         "device.");
1286                 return ERROR_OK;
1287         }
1288
1289         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER)) {
1290                 command_print(CMD_CTX, "Target power supply is not supported by the "
1291                         "device.");
1292                 return ERROR_OK;
1293         }
1294
1295         if (!CMD_ARGC) {
1296                 show_config_target_power(CMD_CTX);
1297         } else if (CMD_ARGC == 1) {
1298                 if (!strcmp(CMD_ARGV[0], "on")) {
1299                         enable = true;
1300                 } else if (!strcmp(CMD_ARGV[0], "off")) {
1301                         enable = false;
1302                 } else {
1303                         command_print(CMD_CTX, "Invalid argument: %s.", CMD_ARGV[0]);
1304                         return ERROR_FAIL;
1305                 }
1306
1307                 tmp_config.target_power = enable;
1308         } else {
1309                 command_print(CMD_CTX, "Need exactly one argument for jlink config "
1310                         "targetpower.");
1311                 return ERROR_COMMAND_SYNTAX_ERROR;
1312         }
1313
1314         return ERROR_OK;
1315 }
1316
1317 COMMAND_HANDLER(jlink_handle_config_mac_address_command)
1318 {
1319         uint8_t addr[6];
1320         int i;
1321         char *e;
1322         const char *str;
1323
1324         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1325                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1326                         "device.");
1327                 return ERROR_OK;
1328         }
1329
1330         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1331                 command_print(CMD_CTX, "Ethernet connectivity is not supported by the "
1332                         "device.");
1333                 return ERROR_OK;
1334         }
1335
1336         if (!CMD_ARGC) {
1337                 show_config_mac_address(CMD_CTX);
1338         } else if (CMD_ARGC == 1) {
1339                 str = CMD_ARGV[0];
1340
1341                 if ((strlen(str) != 17) || (str[2] != ':' || str[5] != ':' || \
1342                                 str[8] != ':' || str[11] != ':' || str[14] != ':')) {
1343                         command_print(CMD_CTX, "Invalid MAC address format.");
1344                         return ERROR_COMMAND_SYNTAX_ERROR;
1345                 }
1346
1347                 for (i = 5; i >= 0; i--) {
1348                         addr[i] = strtoul(str, &e, 16);
1349                         str = e + 1;
1350                 }
1351
1352                 if (!(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5])) {
1353                         command_print(CMD_CTX, "Invalid MAC address: zero address.");
1354                         return ERROR_COMMAND_SYNTAX_ERROR;
1355                 }
1356
1357                 if (!(0x01 & addr[0])) {
1358                         command_print(CMD_CTX, "Invalid MAC address: multicast address.");
1359                         return ERROR_COMMAND_SYNTAX_ERROR;
1360                 }
1361
1362                 memcpy(tmp_config.mac_address, addr, sizeof(addr));
1363         } else {
1364                 command_print(CMD_CTX, "Need exactly one argument for jlink config "
1365                         " mac.");
1366                 return ERROR_COMMAND_SYNTAX_ERROR;
1367         }
1368
1369         return ERROR_OK;
1370 }
1371
1372 static bool string_to_ip(const char *s, uint8_t *ip, int *pos)
1373 {
1374         uint8_t lip[4];
1375         char *e;
1376         const char *s_save = s;
1377         int i;
1378
1379         if (!s)
1380                 return false;
1381
1382         for (i = 0; i < 4; i++) {
1383                 lip[i] = strtoul(s, &e, 10);
1384
1385                 if (*e != '.' && i != 3)
1386                         return false;
1387
1388                 s = e + 1;
1389         }
1390
1391         *pos = e - s_save;
1392         memcpy(ip, lip, sizeof(lip));
1393
1394         return true;
1395 }
1396
1397 static void cpy_ip(uint8_t *dst, uint8_t *src)
1398 {
1399         int i, j;
1400
1401         for (i = 0, j = 3; i < 4; i++, j--)
1402                 dst[i] = src[j];
1403 }
1404
1405 COMMAND_HANDLER(jlink_handle_config_ip_address_command)
1406 {
1407         uint8_t ip_address[4];
1408         uint32_t subnet_mask = 0;
1409         int i, len;
1410         uint8_t subnet_bits = 24;
1411
1412         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1413                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1414                         "device.");
1415                 return ERROR_OK;
1416         }
1417
1418         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1419                 command_print(CMD_CTX, "Ethernet connectivity is not supported by the "
1420                         "device.");
1421                 return ERROR_OK;
1422         }
1423
1424         if (!CMD_ARGC) {
1425                 show_config_ip_address(CMD_CTX);
1426         } else {
1427                 if (!string_to_ip(CMD_ARGV[0], ip_address, &i))
1428                         return ERROR_COMMAND_SYNTAX_ERROR;
1429
1430                 len = strlen(CMD_ARGV[0]);
1431
1432                 /* Check for format A.B.C.D/E. */
1433                 if (i < len) {
1434                         if (CMD_ARGV[0][i] != '/')
1435                                 return ERROR_COMMAND_SYNTAX_ERROR;
1436
1437                         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[0] + i + 1, subnet_bits);
1438                 } else if (CMD_ARGC > 1) {
1439                         if (!string_to_ip(CMD_ARGV[1], (uint8_t *)&subnet_mask, &i))
1440                                 return ERROR_COMMAND_SYNTAX_ERROR;
1441                 }
1442
1443                 if (!subnet_mask)
1444                         subnet_mask = (uint32_t)(subnet_bits < 32 ?
1445                                 ((1ULL << subnet_bits) - 1) : 0xffffffff);
1446
1447                 cpy_ip(tmp_config.ip_address, ip_address);
1448                 cpy_ip(tmp_config.subnet_mask, (uint8_t *)&subnet_mask);
1449         }
1450
1451         return ERROR_OK;
1452 }
1453
1454 COMMAND_HANDLER(jlink_handle_config_reset_command)
1455 {
1456         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG))
1457                 return ERROR_OK;
1458
1459         memcpy(&tmp_config, &config, sizeof(struct device_config));
1460
1461         return ERROR_OK;
1462 }
1463
1464
1465 COMMAND_HANDLER(jlink_handle_config_write_command)
1466 {
1467         int ret;
1468
1469         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1470                 command_print(CMD_CTX, "Reading configuration is not supported by the "
1471                         "device.");
1472                 return ERROR_OK;
1473         }
1474
1475         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_WRITE_CONFIG)) {
1476                 command_print(CMD_CTX, "Writing configuration is not supported by the "
1477                         "device.");
1478                 return ERROR_OK;
1479         }
1480
1481         if (!memcmp(&config, &tmp_config, sizeof(struct device_config))) {
1482                 command_print(CMD_CTX, "Operation not performed due to no changes in "
1483                         "the configuration.");
1484                 return ERROR_OK;
1485         }
1486
1487         ret = jaylink_write_raw_config(devh, (const uint8_t *)&tmp_config);
1488
1489         if (ret != JAYLINK_OK) {
1490                 LOG_ERROR("jaylink_write_raw_config() failed: %s.",
1491                         jaylink_strerror_name(ret));
1492                 return ERROR_FAIL;
1493         }
1494
1495         if (!read_device_config(&config)) {
1496                 LOG_ERROR("Failed to read device configuration for verification.");
1497                 return ERROR_FAIL;
1498         }
1499
1500         if (memcmp(&config, &tmp_config, sizeof(struct device_config))) {
1501                 LOG_ERROR("Verification of device configuration failed. Please check "
1502                         "your device.");
1503                 return ERROR_FAIL;
1504         }
1505
1506         memcpy(&tmp_config, &config, sizeof(struct device_config));
1507         command_print(CMD_CTX, "The new device configuration applies after power "
1508                 "cycling the J-Link device.");
1509
1510         return ERROR_OK;
1511 }
1512
1513 COMMAND_HANDLER(jlink_handle_config_command)
1514 {
1515         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1516                 command_print(CMD_CTX, "Device doesn't support reading configuration.");
1517                 return ERROR_OK;
1518         }
1519
1520         if (CMD_ARGC == 0)
1521                 show_config(CMD_CTX);
1522
1523         return ERROR_OK;
1524 }
1525
1526 static const struct command_registration jlink_config_subcommand_handlers[] = {
1527         {
1528                 .name = "usb",
1529                 .handler = &jlink_handle_config_usb_address_command,
1530                 .mode = COMMAND_EXEC,
1531                 .help = "set the USB address",
1532                 .usage = "[0-3]",
1533         },
1534         {
1535                 .name = "targetpower",
1536                 .handler = &jlink_handle_config_target_power_command,
1537                 .mode = COMMAND_EXEC,
1538                 .help = "set the target power supply",
1539                 .usage = "[on|off]"
1540         },
1541         {
1542                 .name = "mac",
1543                 .handler = &jlink_handle_config_mac_address_command,
1544                 .mode = COMMAND_EXEC,
1545                 .help = "set the MAC Address",
1546                 .usage = "[ff:ff:ff:ff:ff:ff]",
1547         },
1548         {
1549                 .name = "ip",
1550                 .handler = &jlink_handle_config_ip_address_command,
1551                 .mode = COMMAND_EXEC,
1552                 .help = "set the IP address, where A.B.C.D is the IP address, "
1553                         "E the bit of the subnet mask, F.G.H.I the subnet mask",
1554                 .usage = "[A.B.C.D[/E] [F.G.H.I]]",
1555         },
1556         {
1557                 .name = "reset",
1558                 .handler = &jlink_handle_config_reset_command,
1559                 .mode = COMMAND_EXEC,
1560                 .help = "undo configuration changes"
1561         },
1562         {
1563                 .name = "write",
1564                 .handler = &jlink_handle_config_write_command,
1565                 .mode = COMMAND_EXEC,
1566                 .help = "write configuration to the device"
1567         },
1568         COMMAND_REGISTRATION_DONE
1569 };
1570
1571 static const struct command_registration jlink_subcommand_handlers[] = {
1572         {
1573                 .name = "jtag",
1574                 .handler = &jlink_handle_jlink_jtag_command,
1575                 .mode = COMMAND_EXEC,
1576                 .help = "select the JTAG command version",
1577                 .usage = "[2|3]",
1578         },
1579         {
1580                 .name = "targetpower",
1581                 .handler = &jlink_handle_target_power_command,
1582                 .mode = COMMAND_EXEC,
1583                 .help = "set the target power supply",
1584                 .usage = "<on|off>"
1585         },
1586         {
1587                 .name = "freemem",
1588                 .handler = &jlink_handle_free_memory_command,
1589                 .mode = COMMAND_EXEC,
1590                 .help = "show free device memory"
1591         },
1592         {
1593                 .name = "hwstatus",
1594                 .handler = &jlink_handle_hwstatus_command,
1595                 .mode = COMMAND_EXEC,
1596                 .help = "show the hardware status"
1597         },
1598         {
1599                 .name = "usb",
1600                 .handler = &jlink_usb_command,
1601                 .mode = COMMAND_CONFIG,
1602                 .help = "set the USB address of the device that should be used",
1603                 .usage = "<0-3>"
1604         },
1605         {
1606                 .name = "serial",
1607                 .handler = &jlink_serial_command,
1608                 .mode = COMMAND_CONFIG,
1609                 .help = "set the serial number of the device that should be used",
1610                 .usage = "<serial number>"
1611         },
1612         {
1613                 .name = "config",
1614                 .handler = &jlink_handle_config_command,
1615                 .mode = COMMAND_EXEC,
1616                 .help = "access the device configuration. If no argument is given "
1617                         "this will show the device configuration",
1618                 .chain = jlink_config_subcommand_handlers,
1619         },
1620         COMMAND_REGISTRATION_DONE
1621 };
1622
1623 static const struct command_registration jlink_command_handlers[] = {
1624         {
1625                 .name = "jlink",
1626                 .mode = COMMAND_ANY,
1627                 .help = "perform jlink management",
1628                 .chain = jlink_subcommand_handlers,
1629         },
1630         COMMAND_REGISTRATION_DONE
1631 };
1632
1633 static int jlink_swd_init(void)
1634 {
1635         iface = JAYLINK_TIF_SWD;
1636
1637         return ERROR_OK;
1638 }
1639
1640 static void jlink_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
1641 {
1642         assert(!(cmd & SWD_CMD_RnW));
1643         jlink_swd_queue_cmd(cmd, NULL, value, ap_delay_clk);
1644 }
1645
1646 static void jlink_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
1647 {
1648         assert(cmd & SWD_CMD_RnW);
1649         jlink_swd_queue_cmd(cmd, value, 0, ap_delay_clk);
1650 }
1651
1652 static int_least32_t jlink_swd_frequency(int_least32_t hz)
1653 {
1654         if (hz > 0)
1655                 jlink_speed(hz / 1000);
1656
1657         return hz;
1658 }
1659
1660 /***************************************************************************/
1661 /* J-Link tap functions */
1662
1663 static unsigned tap_length;
1664 /* In SWD mode use tms buffer for direction control */
1665 static uint8_t tms_buffer[JLINK_TAP_BUFFER_SIZE];
1666 static uint8_t tdi_buffer[JLINK_TAP_BUFFER_SIZE];
1667 static uint8_t tdo_buffer[JLINK_TAP_BUFFER_SIZE];
1668
1669 struct pending_scan_result {
1670         /** First bit position in tdo_buffer to read. */
1671         unsigned first;
1672         /** Number of bits to read. */
1673         unsigned length;
1674         /** Location to store the result */
1675         void *buffer;
1676         /** Offset in the destination buffer */
1677         unsigned buffer_offset;
1678 };
1679
1680 #define MAX_PENDING_SCAN_RESULTS 256
1681
1682 static int pending_scan_results_length;
1683 static struct pending_scan_result pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
1684
1685 static void jlink_tap_init(void)
1686 {
1687         tap_length = 0;
1688         pending_scan_results_length = 0;
1689         memset(tms_buffer, 0, sizeof(tdi_buffer));
1690 }
1691
1692 static void jlink_clock_data(const uint8_t *out, unsigned out_offset,
1693                              const uint8_t *tms_out, unsigned tms_offset,
1694                              uint8_t *in, unsigned in_offset,
1695                              unsigned length)
1696 {
1697         do {
1698                 unsigned available_length = JLINK_TAP_BUFFER_SIZE - tap_length / 8;
1699
1700                 if (!available_length ||
1701                     (in && pending_scan_results_length == MAX_PENDING_SCAN_RESULTS)) {
1702                         if (jlink_flush() != ERROR_OK)
1703                                 return;
1704                         available_length = JLINK_TAP_BUFFER_SIZE;
1705                 }
1706
1707                 struct pending_scan_result *pending_scan_result =
1708                         &pending_scan_results_buffer[pending_scan_results_length];
1709
1710                 unsigned scan_length = length > available_length ?
1711                         available_length : length;
1712
1713                 if (out)
1714                         buf_set_buf(out, out_offset, tdi_buffer, tap_length, scan_length);
1715                 if (tms_out)
1716                         buf_set_buf(tms_out, tms_offset, tms_buffer, tap_length, scan_length);
1717
1718                 if (in) {
1719                         pending_scan_result->first = tap_length;
1720                         pending_scan_result->length = scan_length;
1721                         pending_scan_result->buffer = in;
1722                         pending_scan_result->buffer_offset = in_offset;
1723                         pending_scan_results_length++;
1724                 }
1725
1726                 tap_length += scan_length;
1727                 out_offset += scan_length;
1728                 tms_offset += scan_length;
1729                 in_offset += scan_length;
1730                 length -= scan_length;
1731         } while (length > 0);
1732 }
1733
1734 static int jlink_flush(void)
1735 {
1736         int i;
1737         int ret;
1738
1739         if (!tap_length)
1740                 return ERROR_OK;
1741
1742         jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
1743                 tap_length, jlink_last_state);
1744
1745         ret = jaylink_jtag_io(devh, tms_buffer, tdi_buffer, tdo_buffer,
1746                 tap_length, jtag_command_version);
1747
1748         if (ret != JAYLINK_OK) {
1749                 LOG_ERROR("jaylink_jtag_io() failed: %s.", jaylink_strerror_name(ret));
1750                 jlink_tap_init();
1751                 return ERROR_JTAG_QUEUE_FAILED;
1752         }
1753
1754         for (i = 0; i < pending_scan_results_length; i++) {
1755                 struct pending_scan_result *p = &pending_scan_results_buffer[i];
1756
1757                 buf_set_buf(tdo_buffer, p->first, p->buffer,
1758                             p->buffer_offset, p->length);
1759
1760                 DEBUG_JTAG_IO("Pending scan result, length = %d.", p->length);
1761         }
1762
1763         jlink_tap_init();
1764
1765         return ERROR_OK;
1766 }
1767
1768 static void fill_buffer(uint8_t *buf, uint32_t val, uint32_t len)
1769 {
1770         unsigned int tap_pos = tap_length;
1771
1772         while (len > 32) {
1773                 buf_set_u32(buf, tap_pos, 32, val);
1774                 len -= 32;
1775                 tap_pos += 32;
1776         }
1777
1778         if (len)
1779                 buf_set_u32(buf, tap_pos, len, val);
1780 }
1781
1782 static void jlink_queue_data_out(const uint8_t *data, uint32_t len)
1783 {
1784         const uint32_t dir_out = 0xffffffff;
1785
1786         if (data)
1787                 bit_copy(tdi_buffer, tap_length, data, 0, len);
1788         else
1789                 fill_buffer(tdi_buffer, 0, len);
1790
1791         fill_buffer(tms_buffer, dir_out, len);
1792         tap_length += len;
1793 }
1794
1795 static void jlink_queue_data_in(uint32_t len)
1796 {
1797         const uint32_t dir_in = 0;
1798
1799         fill_buffer(tms_buffer, dir_in, len);
1800         tap_length += len;
1801 }
1802
1803 static int jlink_swd_switch_seq(enum swd_special_seq seq)
1804 {
1805         const uint8_t *s;
1806         unsigned int s_len;
1807
1808         switch (seq) {
1809                 case LINE_RESET:
1810                         LOG_DEBUG("SWD line reset");
1811                         s = swd_seq_line_reset;
1812                         s_len = swd_seq_line_reset_len;
1813                         break;
1814                 case JTAG_TO_SWD:
1815                         LOG_DEBUG("JTAG-to-SWD");
1816                         s = swd_seq_jtag_to_swd;
1817                         s_len = swd_seq_jtag_to_swd_len;
1818                         break;
1819                 case SWD_TO_JTAG:
1820                         LOG_DEBUG("SWD-to-JTAG");
1821                         s = swd_seq_swd_to_jtag;
1822                         s_len = swd_seq_swd_to_jtag_len;
1823                         break;
1824                 default:
1825                         LOG_ERROR("Sequence %d not supported.", seq);
1826                         return ERROR_FAIL;
1827         }
1828
1829         jlink_queue_data_out(s, s_len);
1830
1831         return ERROR_OK;
1832 }
1833
1834 static int jlink_swd_run_queue(void)
1835 {
1836         int i;
1837         int ret;
1838
1839         LOG_DEBUG("Executing %d queued transactions.", pending_scan_results_length);
1840
1841         if (queued_retval != ERROR_OK) {
1842                 LOG_DEBUG("Skipping due to previous errors: %d.", queued_retval);
1843                 goto skip;
1844         }
1845
1846         /*
1847          * A transaction must be followed by another transaction or at least 8 idle
1848          * cycles to ensure that data is clocked through the AP.
1849          */
1850         jlink_queue_data_out(NULL, 8);
1851
1852         ret = jaylink_swd_io(devh, tms_buffer, tdi_buffer, tdo_buffer, tap_length);
1853
1854         if (ret != JAYLINK_OK) {
1855                 LOG_ERROR("jaylink_swd_io() failed: %s.", jaylink_strerror_name(ret));
1856                 goto skip;
1857         }
1858
1859         for (i = 0; i < pending_scan_results_length; i++) {
1860                 int ack = buf_get_u32(tdo_buffer, pending_scan_results_buffer[i].first, 3);
1861
1862                 if (ack != SWD_ACK_OK) {
1863                         LOG_DEBUG("SWD ack not OK: %d %s", ack,
1864                                   ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
1865                         queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
1866                         goto skip;
1867                 } else if (pending_scan_results_buffer[i].length) {
1868                         uint32_t data = buf_get_u32(tdo_buffer, 3 + pending_scan_results_buffer[i].first, 32);
1869                         int parity = buf_get_u32(tdo_buffer, 3 + 32 + pending_scan_results_buffer[i].first, 1);
1870
1871                         if (parity != parity_u32(data)) {
1872                                 LOG_ERROR("SWD: Read data parity mismatch.");
1873                                 queued_retval = ERROR_FAIL;
1874                                 goto skip;
1875                         }
1876
1877                         if (pending_scan_results_buffer[i].buffer)
1878                                 *(uint32_t *)pending_scan_results_buffer[i].buffer = data;
1879                 }
1880         }
1881
1882 skip:
1883         jlink_tap_init();
1884         ret = queued_retval;
1885         queued_retval = ERROR_OK;
1886
1887         return ret;
1888 }
1889
1890 static void jlink_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk)
1891 {
1892         uint8_t data_parity_trn[DIV_ROUND_UP(32 + 1, 8)];
1893         if (tap_length + 46 + 8 + ap_delay_clk >= sizeof(tdi_buffer) * 8 ||
1894             pending_scan_results_length == MAX_PENDING_SCAN_RESULTS) {
1895                 /* Not enough room in the queue. Run the queue. */
1896                 queued_retval = jlink_swd_run_queue();
1897         }
1898
1899         if (queued_retval != ERROR_OK)
1900                 return;
1901
1902         cmd |= SWD_CMD_START | SWD_CMD_PARK;
1903
1904         jlink_queue_data_out(&cmd, 8);
1905
1906         pending_scan_results_buffer[pending_scan_results_length].first = tap_length;
1907
1908         if (cmd & SWD_CMD_RnW) {
1909                 /* Queue a read transaction. */
1910                 pending_scan_results_buffer[pending_scan_results_length].length = 32;
1911                 pending_scan_results_buffer[pending_scan_results_length].buffer = dst;
1912
1913                 jlink_queue_data_in(1 + 3 + 32 + 1 + 1);
1914         } else {
1915                 /* Queue a write transaction. */
1916                 pending_scan_results_buffer[pending_scan_results_length].length = 0;
1917                 jlink_queue_data_in(1 + 3 + 1);
1918
1919                 buf_set_u32(data_parity_trn, 0, 32, data);
1920                 buf_set_u32(data_parity_trn, 32, 1, parity_u32(data));
1921
1922                 jlink_queue_data_out(data_parity_trn, 32 + 1);
1923         }
1924
1925         pending_scan_results_length++;
1926
1927         /* Insert idle cycles after AP accesses to avoid WAIT. */
1928         if (cmd & SWD_CMD_APnDP)
1929                 jlink_queue_data_out(NULL, ap_delay_clk);
1930 }
1931
1932 static const struct swd_driver jlink_swd = {
1933         .init = &jlink_swd_init,
1934         .frequency = &jlink_swd_frequency,
1935         .switch_seq = &jlink_swd_switch_seq,
1936         .read_reg = &jlink_swd_read_reg,
1937         .write_reg = &jlink_swd_write_reg,
1938         .run = &jlink_swd_run_queue,
1939 };
1940
1941 static const char * const jlink_transports[] = { "jtag", "swd", NULL };
1942
1943 struct jtag_interface jlink_interface = {
1944         .name = "jlink",
1945         .commands = jlink_command_handlers,
1946         .transports = jlink_transports,
1947         .swd = &jlink_swd,
1948         .execute_queue = &jlink_execute_queue,
1949         .speed = &jlink_speed,
1950         .speed_div = &jlink_speed_div,
1951         .khz = &jlink_khz,
1952         .init = &jlink_init,
1953         .quit = &jlink_quit,
1954         .config_trace = &config_trace,
1955         .poll_trace = &poll_trace,
1956 };