+/*
+ * select transport interface
+ *
+ * @param iface [0..31] currently: 0=JTAG, 1=SWD
+ * @returns ERROR_OK or ERROR_ code
+ *
+ * @pre jlink_handle must be opened
+ * @pre function may be called only for devices, that have
+ * EMU_CAP_SELECT_IF capability enabled
+ */
+static int jlink_select_interface(int iface)
+{
+ /* According to Segger's document RM08001-R7 Date: October 8, 2010,
+ * http://www.segger.com/admin/uploads/productDocs/RM08001_JLinkUSBProtocol.pdf
+ * section 5.5.3 EMU_CMD_SELECT_IF
+ * > SubCmd 1..31 to select interface (0..31)
+ *
+ * The table below states:
+ * 0 TIF_JTAG
+ * 1 TIF_SWD
+ *
+ * This obviosly means that to select TIF_JTAG one should write SubCmd = 1.
+ *
+ * In fact, JTAG interface operates when SubCmd=0
+ *
+ * It looks like a typo in documentation, because interfaces 0..31 could not
+ * be selected by 1..31 range command.
+ */
+ assert(iface >= 0 && iface < 32);
+ int result;
+
+ /* get available interfaces */
+ usb_out_buffer[0] = EMU_CMD_SELECT_IF;
+ usb_out_buffer[1] = 0xff;
+
+ result = jlink_usb_io(jlink_handle, 2, 4);
+ if (result != ERROR_OK) {
+ LOG_ERROR("J-Link query interface failed (%d)", result);
+ return ERROR_JTAG_DEVICE_ERROR;
+ }
+
+ uint32_t iface_mask = buf_get_u32(usb_in_buffer, 0, 32);
+
+ if (!(iface_mask & (1<<iface))) {
+ LOG_ERROR("J-Link requesting to select unsupported interface (%x)", iface_mask);
+ return ERROR_JTAG_DEVICE_ERROR;
+ }
+
+ /* Select interface */
+ usb_out_buffer[0] = EMU_CMD_SELECT_IF;
+ usb_out_buffer[1] = iface;
+
+ result = jlink_usb_io(jlink_handle, 2, 4);
+ if (result != ERROR_OK) {
+ LOG_ERROR("J-Link interface select failed (%d)", result);
+ return ERROR_JTAG_DEVICE_ERROR;
+ }
+
+ return ERROR_OK;
+}
+