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