]> sigrok.org Git - libsigrok.git/blob - src/hardware/dreamsourcelab-dslogic/protocol.c
sr_dev_open(): Set status to SR_ST_ACTIVE upon success.
[libsigrok.git] / src / hardware / dreamsourcelab-dslogic / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <math.h>
23 #include <glib.h>
24 #include <glib/gstdio.h>
25 #include "protocol.h"
26
27 #define DS_CMD_GET_FW_VERSION           0xb0
28 #define DS_CMD_GET_REVID_VERSION        0xb1
29 #define DS_CMD_START                    0xb2
30 #define DS_CMD_CONFIG                   0xb3
31 #define DS_CMD_SETTING                  0xb4
32 #define DS_CMD_CONTROL                  0xb5
33 #define DS_CMD_STATUS                   0xb6
34 #define DS_CMD_STATUS_INFO              0xb7
35 #define DS_CMD_WR_REG                   0xb8
36 #define DS_CMD_WR_NVM                   0xb9
37 #define DS_CMD_RD_NVM                   0xba
38 #define DS_CMD_RD_NVM_PRE               0xbb
39 #define DS_CMD_GET_HW_INFO              0xbc
40
41 #define DS_START_FLAGS_STOP             (1 << 7)
42 #define DS_START_FLAGS_CLK_48MHZ        (1 << 6)
43 #define DS_START_FLAGS_SAMPLE_WIDE      (1 << 5)
44 #define DS_START_FLAGS_MODE_LA          (1 << 4)
45
46 #define DS_ADDR_COMB                    0x68
47 #define DS_ADDR_EEWP                    0x70
48 #define DS_ADDR_VTH                     0x78
49
50 #define DS_MAX_LOGIC_DEPTH              SR_MHZ(16)
51 #define DS_MAX_LOGIC_SAMPLERATE         SR_MHZ(100)
52 #define DS_MAX_TRIG_PERCENT             90
53
54 #define DS_MODE_TRIG_EN                 (1 << 0)
55 #define DS_MODE_CLK_TYPE                (1 << 1)
56 #define DS_MODE_CLK_EDGE                (1 << 2)
57 #define DS_MODE_RLE_MODE                (1 << 3)
58 #define DS_MODE_DSO_MODE                (1 << 4)
59 #define DS_MODE_HALF_MODE               (1 << 5)
60 #define DS_MODE_QUAR_MODE               (1 << 6)
61 #define DS_MODE_ANALOG_MODE             (1 << 7)
62 #define DS_MODE_FILTER                  (1 << 8)
63 #define DS_MODE_INSTANT                 (1 << 9)
64 #define DS_MODE_STRIG_MODE              (1 << 11)
65 #define DS_MODE_STREAM_MODE             (1 << 12)
66 #define DS_MODE_LPB_TEST                (1 << 13)
67 #define DS_MODE_EXT_TEST                (1 << 14)
68 #define DS_MODE_INT_TEST                (1 << 15)
69
70 #define DSLOGIC_ATOMIC_SAMPLES          (sizeof(uint64_t) * 8)
71 #define DSLOGIC_ATOMIC_BYTES            sizeof(uint64_t)
72
73 /*
74  * The FPGA is configured with TLV tuples. Length is specified as the
75  * number of 16-bit words.
76  */
77 #define _DS_CFG(variable, wordcnt) ((variable << 8) | wordcnt)
78 #define DS_CFG_START                    0xf5a5f5a5
79 #define DS_CFG_MODE                     _DS_CFG(0, 1)
80 #define DS_CFG_DIVIDER                  _DS_CFG(1, 2)
81 #define DS_CFG_COUNT                    _DS_CFG(3, 2)
82 #define DS_CFG_TRIG_POS                 _DS_CFG(5, 2)
83 #define DS_CFG_TRIG_GLB                 _DS_CFG(7, 1)
84 #define DS_CFG_CH_EN                    _DS_CFG(8, 1)
85 #define DS_CFG_TRIG                     _DS_CFG(64, 160)
86 #define DS_CFG_END                      0xfa5afa5a
87
88 #pragma pack(push, 1)
89
90 struct version_info {
91         uint8_t major;
92         uint8_t minor;
93 };
94
95 struct cmd_start_acquisition {
96         uint8_t flags;
97         uint8_t sample_delay_h;
98         uint8_t sample_delay_l;
99 };
100
101 struct dslogic_fpga_config {
102         uint32_t sync;
103
104         uint16_t mode_header;
105         uint16_t mode;
106         uint16_t divider_header;
107         uint32_t divider;
108         uint16_t count_header;
109         uint32_t count;
110         uint16_t trig_pos_header;
111         uint32_t trig_pos;
112         uint16_t trig_glb_header;
113         uint16_t trig_glb;
114         uint16_t ch_en_header;
115         uint16_t ch_en;
116
117         uint16_t trig_header;
118         uint16_t trig_mask0[NUM_TRIGGER_STAGES];
119         uint16_t trig_mask1[NUM_TRIGGER_STAGES];
120         uint16_t trig_value0[NUM_TRIGGER_STAGES];
121         uint16_t trig_value1[NUM_TRIGGER_STAGES];
122         uint16_t trig_edge0[NUM_TRIGGER_STAGES];
123         uint16_t trig_edge1[NUM_TRIGGER_STAGES];
124         uint16_t trig_logic0[NUM_TRIGGER_STAGES];
125         uint16_t trig_logic1[NUM_TRIGGER_STAGES];
126         uint32_t trig_count[NUM_TRIGGER_STAGES];
127
128         uint32_t end_sync;
129 };
130
131 #pragma pack(pop)
132
133 /*
134  * This should be larger than the FPGA bitstream image so that it'll get
135  * uploaded in one big operation. There seem to be issues when uploading
136  * it in chunks.
137  */
138 #define FW_BUFSIZE (1024 * 1024)
139
140 #define FPGA_UPLOAD_DELAY (10 * 1000)
141
142 #define USB_TIMEOUT (3 * 1000)
143
144 static int command_get_fw_version(libusb_device_handle *devhdl,
145                                   struct version_info *vi)
146 {
147         int ret;
148
149         ret = libusb_control_transfer(devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
150                 LIBUSB_ENDPOINT_IN, DS_CMD_GET_FW_VERSION, 0x0000, 0x0000,
151                 (unsigned char *)vi, sizeof(struct version_info), USB_TIMEOUT);
152
153         if (ret < 0) {
154                 sr_err("Unable to get version info: %s.",
155                        libusb_error_name(ret));
156                 return SR_ERR;
157         }
158
159         return SR_OK;
160 }
161
162 static int command_get_revid_version(struct sr_dev_inst *sdi, uint8_t *revid)
163 {
164         struct sr_usb_dev_inst *usb = sdi->conn;
165         libusb_device_handle *devhdl = usb->devhdl;
166         int ret;
167
168         ret = libusb_control_transfer(devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
169                 LIBUSB_ENDPOINT_IN, DS_CMD_GET_REVID_VERSION, 0x0000, 0x0000,
170                 revid, 1, USB_TIMEOUT);
171
172         if (ret < 0) {
173                 sr_err("Unable to get REVID: %s.", libusb_error_name(ret));
174                 return SR_ERR;
175         }
176
177         return SR_OK;
178 }
179
180 static int command_start_acquisition(const struct sr_dev_inst *sdi)
181 {
182         struct sr_usb_dev_inst *usb;
183         struct dslogic_mode mode;
184         int ret;
185
186         mode.flags = DS_START_FLAGS_MODE_LA | DS_START_FLAGS_SAMPLE_WIDE;
187         mode.sample_delay_h = mode.sample_delay_l = 0;
188
189         usb = sdi->conn;
190         ret = libusb_control_transfer(usb->devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
191                         LIBUSB_ENDPOINT_OUT, DS_CMD_START, 0x0000, 0x0000,
192                         (unsigned char *)&mode, sizeof(mode), USB_TIMEOUT);
193         if (ret < 0) {
194                 sr_err("Failed to send start command: %s.", libusb_error_name(ret));
195                 return SR_ERR;
196         }
197
198         return SR_OK;
199 }
200
201 static int command_stop_acquisition(const struct sr_dev_inst *sdi)
202 {
203         struct sr_usb_dev_inst *usb;
204         struct dslogic_mode mode;
205         int ret;
206
207         mode.flags = DS_START_FLAGS_STOP;
208         mode.sample_delay_h = mode.sample_delay_l = 0;
209
210         usb = sdi->conn;
211         ret = libusb_control_transfer(usb->devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
212                         LIBUSB_ENDPOINT_OUT, DS_CMD_START, 0x0000, 0x0000,
213                         (unsigned char *)&mode, sizeof(struct dslogic_mode), USB_TIMEOUT);
214         if (ret < 0) {
215                 sr_err("Failed to send stop command: %s.", libusb_error_name(ret));
216                 return SR_ERR;
217         }
218
219         return SR_OK;
220 }
221
222 SR_PRIV int dslogic_fpga_firmware_upload(const struct sr_dev_inst *sdi)
223 {
224         const char *name = NULL;
225         uint64_t sum;
226         struct sr_resource bitstream;
227         struct drv_context *drvc;
228         struct dev_context *devc;
229         struct sr_usb_dev_inst *usb;
230         unsigned char *buf;
231         ssize_t chunksize;
232         int transferred;
233         int result, ret;
234         const uint8_t cmd[3] = {0, 0, 0};
235
236         drvc = sdi->driver->context;
237         devc = sdi->priv;
238         usb = sdi->conn;
239
240         if (!strcmp(devc->profile->model, "DSLogic")) {
241                 if (devc->cur_threshold < 1.40)
242                         name = DSLOGIC_FPGA_FIRMWARE_3V3;
243                 else
244                         name = DSLOGIC_FPGA_FIRMWARE_5V;
245         } else if (!strcmp(devc->profile->model, "DSLogic Pro")){
246                 name = DSLOGIC_PRO_FPGA_FIRMWARE;
247         } else if (!strcmp(devc->profile->model, "DSLogic Plus")){
248                 name = DSLOGIC_PLUS_FPGA_FIRMWARE;
249         } else if (!strcmp(devc->profile->model, "DSLogic Basic")){
250                 name = DSLOGIC_BASIC_FPGA_FIRMWARE;
251         } else if (!strcmp(devc->profile->model, "DSCope")) {
252                 name = DSCOPE_FPGA_FIRMWARE;
253         } else {
254                 sr_err("Failed to select FPGA firmware.");
255                 return SR_ERR;
256         }
257
258         sr_dbg("Uploading FPGA firmware '%s'.", name);
259
260         result = sr_resource_open(drvc->sr_ctx, &bitstream,
261                         SR_RESOURCE_FIRMWARE, name);
262         if (result != SR_OK)
263                 return result;
264
265         /* Tell the device firmware is coming. */
266         if ((ret = libusb_control_transfer(usb->devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
267                         LIBUSB_ENDPOINT_OUT, DS_CMD_CONFIG, 0x0000, 0x0000,
268                         (unsigned char *)&cmd, sizeof(cmd), USB_TIMEOUT)) < 0) {
269                 sr_err("Failed to upload FPGA firmware: %s.", libusb_error_name(ret));
270                 sr_resource_close(drvc->sr_ctx, &bitstream);
271                 return SR_ERR;
272         }
273
274         /* Give the FX2 time to get ready for FPGA firmware upload. */
275         g_usleep(FPGA_UPLOAD_DELAY);
276
277         buf = g_malloc(FW_BUFSIZE);
278         sum = 0;
279         result = SR_OK;
280         while (1) {
281                 chunksize = sr_resource_read(drvc->sr_ctx, &bitstream,
282                                 buf, FW_BUFSIZE);
283                 if (chunksize < 0)
284                         result = SR_ERR;
285                 if (chunksize <= 0)
286                         break;
287
288                 if ((ret = libusb_bulk_transfer(usb->devhdl, 2 | LIBUSB_ENDPOINT_OUT,
289                                 buf, chunksize, &transferred, USB_TIMEOUT)) < 0) {
290                         sr_err("Unable to configure FPGA firmware: %s.",
291                                         libusb_error_name(ret));
292                         result = SR_ERR;
293                         break;
294                 }
295                 sum += transferred;
296                 sr_spew("Uploaded %" PRIu64 "/%" PRIu64 " bytes.",
297                         sum, bitstream.size);
298
299                 if (transferred != chunksize) {
300                         sr_err("Short transfer while uploading FPGA firmware.");
301                         result = SR_ERR;
302                         break;
303                 }
304         }
305         g_free(buf);
306         sr_resource_close(drvc->sr_ctx, &bitstream);
307
308         if (result == SR_OK)
309                 sr_dbg("FPGA firmware upload done.");
310
311         return result;
312 }
313
314 static unsigned int enabled_channel_count(const struct sr_dev_inst *sdi)
315 {
316         unsigned int count = 0;
317         for (const GSList *l = sdi->channels; l; l = l->next) {
318                 const struct sr_channel *const probe = (struct sr_channel *)l->data;
319                 if (probe->enabled)
320                         count++;
321         }
322         return count;
323 }
324
325 static uint16_t enabled_channel_mask(const struct sr_dev_inst *sdi)
326 {
327         unsigned int mask = 0;
328         for (const GSList *l = sdi->channels; l; l = l->next) {
329                 const struct sr_channel *const probe = (struct sr_channel *)l->data;
330                 if (probe->enabled)
331                         mask |= 1 << probe->index;
332         }
333         return mask;
334 }
335
336 /*
337  * Get the session trigger and configure the FPGA structure
338  * accordingly.
339  */
340 static void set_trigger(const struct sr_dev_inst *sdi,
341         struct dslogic_fpga_config *cfg)
342 {
343         struct sr_trigger *trigger;
344         struct sr_trigger_stage *stage;
345         struct sr_trigger_match *match;
346         struct dev_context *devc;
347         const GSList *l, *m;
348         const unsigned int num_enabled_channels = enabled_channel_count(sdi);
349         int num_trigger_stages = 0;
350
351         int channelbit, i = 0;
352         uint32_t trigger_point;
353
354         devc = sdi->priv;
355
356         cfg->ch_en = enabled_channel_mask(sdi);
357
358         cfg->trig_mask0[0] = 0xffff;
359         cfg->trig_mask1[0] = 0xffff;
360
361         cfg->trig_value0[0] = 0;
362         cfg->trig_value1[0] = 0;
363
364         cfg->trig_edge0[0] = 0;
365         cfg->trig_edge1[0] = 0;
366
367         cfg->trig_logic0[0] = 2;
368         cfg->trig_logic1[0] = 2;
369
370         cfg->trig_count[0] = 0;
371
372         cfg->trig_glb = num_enabled_channels << 4;
373
374         for (i = 1; i < NUM_TRIGGER_STAGES; i++) {
375                 cfg->trig_mask0[i] = 0xffff;
376                 cfg->trig_mask1[i] = 0xffff;
377                 cfg->trig_value0[i] = 0;
378                 cfg->trig_value1[i] = 0;
379                 cfg->trig_edge0[i] = 0;
380                 cfg->trig_edge1[i] = 0;
381                 cfg->trig_logic0[i] = 2;
382                 cfg->trig_logic1[i] = 2;
383                 cfg->trig_count[i] = 0;
384         }
385
386         trigger_point = (devc->capture_ratio * devc->limit_samples) / 100;
387         if (trigger_point < DSLOGIC_ATOMIC_SAMPLES)
388                 trigger_point = DSLOGIC_ATOMIC_SAMPLES;
389         const uint32_t mem_depth = devc->profile->mem_depth;
390         const uint32_t max_trigger_point = devc->continuous_mode ? ((mem_depth * 10) / 100) :
391                 ((mem_depth * DS_MAX_TRIG_PERCENT) / 100);
392         if (trigger_point > max_trigger_point)
393                 trigger_point = max_trigger_point;
394         cfg->trig_pos = trigger_point & ~(DSLOGIC_ATOMIC_SAMPLES - 1);
395
396         if (!(trigger = sr_session_trigger_get(sdi->session))) {
397                 sr_dbg("No session trigger found");
398                 return;
399         }
400
401         for (l = trigger->stages; l; l = l->next) {
402                 stage = l->data;
403                 num_trigger_stages++;
404                 for (m = stage->matches; m; m = m->next) {
405                         match = m->data;
406                         if (!match->channel->enabled)
407                                 /* Ignore disabled channels with a trigger. */
408                                 continue;
409                         channelbit = 1 << (match->channel->index);
410                         /* Simple trigger support (event). */
411                         if (match->match == SR_TRIGGER_ONE) {
412                                 cfg->trig_mask0[0] &= ~channelbit;
413                                 cfg->trig_mask1[0] &= ~channelbit;
414                                 cfg->trig_value0[0] |= channelbit;
415                                 cfg->trig_value1[0] |= channelbit;
416                         } else if (match->match == SR_TRIGGER_ZERO) {
417                                 cfg->trig_mask0[0] &= ~channelbit;
418                                 cfg->trig_mask1[0] &= ~channelbit;
419                         } else if (match->match == SR_TRIGGER_FALLING) {
420                                 cfg->trig_mask0[0] &= ~channelbit;
421                                 cfg->trig_mask1[0] &= ~channelbit;
422                                 cfg->trig_edge0[0] |= channelbit;
423                                 cfg->trig_edge1[0] |= channelbit;
424                         } else if (match->match == SR_TRIGGER_RISING) {
425                                 cfg->trig_mask0[0] &= ~channelbit;
426                                 cfg->trig_mask1[0] &= ~channelbit;
427                                 cfg->trig_value0[0] |= channelbit;
428                                 cfg->trig_value1[0] |= channelbit;
429                                 cfg->trig_edge0[0] |= channelbit;
430                                 cfg->trig_edge1[0] |= channelbit;
431                         } else if (match->match == SR_TRIGGER_EDGE) {
432                                 cfg->trig_edge0[0] |= channelbit;
433                                 cfg->trig_edge1[0] |= channelbit;
434                         }
435                 }
436         }
437
438         cfg->trig_glb |= num_trigger_stages;
439 }
440
441 static int fpga_configure(const struct sr_dev_inst *sdi)
442 {
443         struct dev_context *devc;
444         struct sr_usb_dev_inst *usb;
445         uint8_t c[3];
446         struct dslogic_fpga_config cfg;
447         uint16_t v16;
448         uint32_t v32;
449         int transferred, len, ret;
450
451         sr_dbg("Configuring FPGA.");
452
453         usb = sdi->conn;
454         devc = sdi->priv;
455
456         WL32(&cfg.sync, DS_CFG_START);
457         WL16(&cfg.mode_header, DS_CFG_MODE);
458         WL16(&cfg.divider_header, DS_CFG_DIVIDER);
459         WL16(&cfg.count_header, DS_CFG_COUNT);
460         WL16(&cfg.trig_pos_header, DS_CFG_TRIG_POS);
461         WL16(&cfg.trig_glb_header, DS_CFG_TRIG_GLB);
462         WL16(&cfg.ch_en_header, DS_CFG_CH_EN);
463         WL16(&cfg.trig_header, DS_CFG_TRIG);
464         WL32(&cfg.end_sync, DS_CFG_END);
465
466         /* Pass in the length of a fixed-size struct. Really. */
467         len = sizeof(struct dslogic_fpga_config) / 2;
468         c[0] = len & 0xff;
469         c[1] = (len >> 8) & 0xff;
470         c[2] = (len >> 16) & 0xff;
471
472         ret = libusb_control_transfer(usb->devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
473                         LIBUSB_ENDPOINT_OUT, DS_CMD_SETTING, 0x0000, 0x0000,
474                         c, sizeof(c), USB_TIMEOUT);
475         if (ret < 0) {
476                 sr_err("Failed to send FPGA configure command: %s.",
477                         libusb_error_name(ret));
478                 return SR_ERR;
479         }
480
481         v16 = 0x0000;
482
483         if (devc->mode == DS_OP_INTERNAL_TEST)
484                 v16 = DS_MODE_INT_TEST;
485         else if (devc->mode == DS_OP_EXTERNAL_TEST)
486                 v16 = DS_MODE_EXT_TEST;
487         else if (devc->mode == DS_OP_LOOPBACK_TEST)
488                 v16 = DS_MODE_LPB_TEST;
489
490         if (devc->cur_samplerate == DS_MAX_LOGIC_SAMPLERATE * 2)
491                 v16 |= DS_MODE_HALF_MODE;
492         else if (devc->cur_samplerate == DS_MAX_LOGIC_SAMPLERATE * 4)
493                 v16 |= DS_MODE_QUAR_MODE;
494
495         if (devc->continuous_mode)
496                 v16 |= DS_MODE_STREAM_MODE;
497         if (devc->external_clock) {
498                 v16 |= DS_MODE_CLK_TYPE;
499                 if (devc->clock_edge == DS_EDGE_FALLING)
500                         v16 |= DS_MODE_CLK_EDGE;
501         }
502         if (devc->limit_samples > DS_MAX_LOGIC_DEPTH *
503                 ceil(devc->cur_samplerate * 1.0 / DS_MAX_LOGIC_SAMPLERATE)
504                 && !devc->continuous_mode) {
505                 /* Enable RLE for long captures.
506                  * Without this, captured data present errors.
507                  */
508                 v16 |= DS_MODE_RLE_MODE;
509         }
510
511         WL16(&cfg.mode, v16);
512         v32 = ceil(DS_MAX_LOGIC_SAMPLERATE * 1.0 / devc->cur_samplerate);
513         WL32(&cfg.divider, v32);
514
515         /* Number of 16-sample units. */
516         WL32(&cfg.count, devc->limit_samples / 16);
517
518         set_trigger(sdi, &cfg);
519
520         len = sizeof(struct dslogic_fpga_config);
521         ret = libusb_bulk_transfer(usb->devhdl, 2 | LIBUSB_ENDPOINT_OUT,
522                         (unsigned char *)&cfg, len, &transferred, USB_TIMEOUT);
523         if (ret < 0 || transferred != len) {
524                 sr_err("Failed to send FPGA configuration: %s.", libusb_error_name(ret));
525                 return SR_ERR;
526         }
527
528         return SR_OK;
529 }
530
531 SR_PRIV int dslogic_set_voltage_threshold(const struct sr_dev_inst *sdi, double threshold)
532 {
533         int ret;
534         struct dev_context *const devc = sdi->priv;
535         const struct sr_usb_dev_inst *const usb = sdi->conn;
536         const uint8_t value = (threshold / 5.0) * 255;
537         const uint16_t cmd = value | (DS_ADDR_VTH << 8);
538
539         /* Send the control command. */
540         ret = libusb_control_transfer(usb->devhdl,
541                         LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT,
542                         DS_CMD_WR_REG, 0x0000, 0x0000,
543                         (unsigned char *)&cmd, sizeof(cmd), 3000);
544         if (ret < 0) {
545                 sr_err("Unable to set voltage-threshold register: %s.",
546                 libusb_error_name(ret));
547                 return SR_ERR;
548         }
549
550         devc->cur_threshold = threshold;
551
552         return SR_OK;
553 }
554
555 SR_PRIV int dslogic_dev_open(struct sr_dev_inst *sdi, struct sr_dev_driver *di)
556 {
557         libusb_device **devlist;
558         struct sr_usb_dev_inst *usb;
559         struct libusb_device_descriptor des;
560         struct dev_context *devc;
561         struct drv_context *drvc;
562         struct version_info vi;
563         int ret = SR_ERR, i, device_count;
564         uint8_t revid;
565         char connection_id[64];
566
567         drvc = di->context;
568         devc = sdi->priv;
569         usb = sdi->conn;
570
571         device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
572         if (device_count < 0) {
573                 sr_err("Failed to get device list: %s.",
574                        libusb_error_name(device_count));
575                 return SR_ERR;
576         }
577
578         for (i = 0; i < device_count; i++) {
579                 libusb_get_device_descriptor(devlist[i], &des);
580
581                 if (des.idVendor != devc->profile->vid
582                     || des.idProduct != devc->profile->pid)
583                         continue;
584
585                 if ((sdi->status == SR_ST_INITIALIZING) ||
586                                 (sdi->status == SR_ST_INACTIVE)) {
587                         /* Check device by its physical USB bus/port address. */
588                         usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
589                         if (strcmp(sdi->connection_id, connection_id))
590                                 /* This is not the one. */
591                                 continue;
592                 }
593
594                 if (!(ret = libusb_open(devlist[i], &usb->devhdl))) {
595                         if (usb->address == 0xff)
596                                 /*
597                                  * First time we touch this device after FW
598                                  * upload, so we don't know the address yet.
599                                  */
600                                 usb->address = libusb_get_device_address(devlist[i]);
601                 } else {
602                         sr_err("Failed to open device: %s.",
603                                libusb_error_name(ret));
604                         ret = SR_ERR;
605                         break;
606                 }
607
608                 if (libusb_has_capability(LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER)) {
609                         if (libusb_kernel_driver_active(usb->devhdl, USB_INTERFACE) == 1) {
610                                 if ((ret = libusb_detach_kernel_driver(usb->devhdl, USB_INTERFACE)) < 0) {
611                                         sr_err("Failed to detach kernel driver: %s.",
612                                                 libusb_error_name(ret));
613                                         ret = SR_ERR;
614                                         break;
615                                 }
616                         }
617                 }
618
619                 ret = command_get_fw_version(usb->devhdl, &vi);
620                 if (ret != SR_OK) {
621                         sr_err("Failed to get firmware version.");
622                         break;
623                 }
624
625                 ret = command_get_revid_version(sdi, &revid);
626                 if (ret != SR_OK) {
627                         sr_err("Failed to get REVID.");
628                         break;
629                 }
630
631                 /*
632                  * Changes in major version mean incompatible/API changes, so
633                  * bail out if we encounter an incompatible version.
634                  * Different minor versions are OK, they should be compatible.
635                  */
636                 if (vi.major != DSLOGIC_REQUIRED_VERSION_MAJOR) {
637                         sr_err("Expected firmware version %d.x, "
638                                "got %d.%d.", DSLOGIC_REQUIRED_VERSION_MAJOR,
639                                vi.major, vi.minor);
640                         ret = SR_ERR;
641                         break;
642                 }
643
644                 sr_info("Opened device on %d.%d (logical) / %s (physical), "
645                         "interface %d, firmware %d.%d.",
646                         usb->bus, usb->address, connection_id,
647                         USB_INTERFACE, vi.major, vi.minor);
648
649                 sr_info("Detected REVID=%d, it's a Cypress CY7C68013%s.",
650                         revid, (revid != 1) ? " (FX2)" : "A (FX2LP)");
651
652                 ret = SR_OK;
653
654                 break;
655         }
656
657         libusb_free_device_list(devlist, 1);
658
659         return ret;
660 }
661
662 SR_PRIV struct dev_context *dslogic_dev_new(void)
663 {
664         struct dev_context *devc;
665
666         devc = g_malloc0(sizeof(struct dev_context));
667         devc->profile = NULL;
668         devc->fw_updated = 0;
669         devc->cur_samplerate = 0;
670         devc->limit_samples = 0;
671         devc->capture_ratio = 0;
672         devc->continuous_mode = FALSE;
673         devc->clock_edge = DS_EDGE_RISING;
674
675         return devc;
676 }
677
678 static void abort_acquisition(struct dev_context *devc)
679 {
680         int i;
681
682         devc->acq_aborted = TRUE;
683
684         for (i = devc->num_transfers - 1; i >= 0; i--) {
685                 if (devc->transfers[i])
686                         libusb_cancel_transfer(devc->transfers[i]);
687         }
688 }
689
690 static void finish_acquisition(struct sr_dev_inst *sdi)
691 {
692         struct dev_context *devc;
693
694         devc = sdi->priv;
695
696         std_session_send_df_end(sdi);
697
698         usb_source_remove(sdi->session, devc->ctx);
699
700         devc->num_transfers = 0;
701         g_free(devc->transfers);
702         g_free(devc->deinterleave_buffer);
703 }
704
705 static void free_transfer(struct libusb_transfer *transfer)
706 {
707         struct sr_dev_inst *sdi;
708         struct dev_context *devc;
709         unsigned int i;
710
711         sdi = transfer->user_data;
712         devc = sdi->priv;
713
714         g_free(transfer->buffer);
715         transfer->buffer = NULL;
716         libusb_free_transfer(transfer);
717
718         for (i = 0; i < devc->num_transfers; i++) {
719                 if (devc->transfers[i] == transfer) {
720                         devc->transfers[i] = NULL;
721                         break;
722                 }
723         }
724
725         devc->submitted_transfers--;
726         if (devc->submitted_transfers == 0)
727                 finish_acquisition(sdi);
728 }
729
730 static void resubmit_transfer(struct libusb_transfer *transfer)
731 {
732         int ret;
733
734         if ((ret = libusb_submit_transfer(transfer)) == LIBUSB_SUCCESS)
735                 return;
736
737         sr_err("%s: %s", __func__, libusb_error_name(ret));
738         free_transfer(transfer);
739
740 }
741
742 static void deinterleave_buffer(const uint8_t *src, size_t length,
743         uint16_t *dst_ptr, size_t channel_count, uint16_t channel_mask)
744 {
745         uint16_t sample;
746
747         for (const uint64_t *src_ptr = (uint64_t*)src;
748                 src_ptr < (uint64_t*)(src + length);
749                 src_ptr += channel_count) {
750                 for (int bit = 0; bit != 64; bit++) {
751                         const uint64_t *word_ptr = src_ptr;
752                         sample = 0;
753                         for (size_t channel = 0; channel != channel_count;
754                                 channel++) {
755                                 if ((channel_mask & (1 << channel)) &&
756                                         (*word_ptr++ & (1ULL << bit)))
757                                         sample |= 1 << channel;
758                         }
759                         *dst_ptr++ = sample;
760                 }
761         }
762 }
763
764 static void send_data(struct sr_dev_inst *sdi,
765         uint16_t *data, size_t sample_count)
766 {
767         const struct sr_datafeed_logic logic = {
768                 .length = sample_count * sizeof(uint16_t),
769                 .unitsize = sizeof(uint16_t),
770                 .data = data
771         };
772
773         const struct sr_datafeed_packet packet = {
774                 .type = SR_DF_LOGIC,
775                 .payload = &logic
776         };
777
778         sr_session_send(sdi, &packet);
779 }
780
781 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
782 {
783         struct sr_dev_inst *const sdi = transfer->user_data;
784         struct dev_context *const devc = sdi->priv;
785         const size_t channel_count = enabled_channel_count(sdi);
786         const uint16_t channel_mask = enabled_channel_mask(sdi);
787         const unsigned int cur_sample_count = DSLOGIC_ATOMIC_SAMPLES *
788                 transfer->actual_length /
789                 (DSLOGIC_ATOMIC_BYTES * channel_count);
790
791         gboolean packet_has_error = FALSE;
792         struct sr_datafeed_packet packet;
793         unsigned int num_samples;
794         int trigger_offset;
795
796         /*
797          * If acquisition has already ended, just free any queued up
798          * transfer that come in.
799          */
800         if (devc->acq_aborted) {
801                 free_transfer(transfer);
802                 return;
803         }
804
805         sr_dbg("receive_transfer(): status %s received %d bytes.",
806                 libusb_error_name(transfer->status), transfer->actual_length);
807
808         /* Save incoming transfer before reusing the transfer struct. */
809
810         switch (transfer->status) {
811         case LIBUSB_TRANSFER_NO_DEVICE:
812                 abort_acquisition(devc);
813                 free_transfer(transfer);
814                 return;
815         case LIBUSB_TRANSFER_COMPLETED:
816         case LIBUSB_TRANSFER_TIMED_OUT: /* We may have received some data though. */
817                 break;
818         default:
819                 packet_has_error = TRUE;
820                 break;
821         }
822
823         if (transfer->actual_length == 0 || packet_has_error) {
824                 devc->empty_transfer_count++;
825                 if (devc->empty_transfer_count > MAX_EMPTY_TRANSFERS) {
826                         /*
827                          * The FX2 gave up. End the acquisition, the frontend
828                          * will work out that the samplecount is short.
829                          */
830                         abort_acquisition(devc);
831                         free_transfer(transfer);
832                 } else {
833                         resubmit_transfer(transfer);
834                 }
835                 return;
836         } else {
837                 devc->empty_transfer_count = 0;
838         }
839
840         if (!devc->limit_samples || devc->sent_samples < devc->limit_samples) {
841                 if (devc->limit_samples && devc->sent_samples + cur_sample_count > devc->limit_samples)
842                         num_samples = devc->limit_samples - devc->sent_samples;
843                 else
844                         num_samples = cur_sample_count;
845
846                 /**
847                  * The DSLogic emits sample data as sequences of 64-bit sample words
848                  * in a round-robin i.e. 64-bits from channel 0, 64-bits from channel 1
849                  * etc. for each of the enabled channels, then looping back to the
850                  * channel.
851                  *
852                  * Because sigrok's internal representation is bit-interleaved channels
853                  * we must recast the data.
854                  *
855                  * Hopefully in future it will be possible to pass the data on as-is.
856                  */
857                 if (transfer->actual_length % (DSLOGIC_ATOMIC_BYTES * channel_count) != 0)
858                         sr_err("Invalid transfer length!");
859                 deinterleave_buffer(transfer->buffer, transfer->actual_length,
860                         devc->deinterleave_buffer, channel_count, channel_mask);
861
862                 /* Send the incoming transfer to the session bus. */
863                 if (devc->trigger_pos > devc->sent_samples
864                         && devc->trigger_pos <= devc->sent_samples + num_samples) {
865                         /* DSLogic trigger in this block. Send trigger position. */
866                         trigger_offset = devc->trigger_pos - devc->sent_samples;
867                         /* Pre-trigger samples. */
868                         send_data(sdi, devc->deinterleave_buffer, trigger_offset);
869                         devc->sent_samples += trigger_offset;
870                         /* Trigger position. */
871                         devc->trigger_pos = 0;
872                         packet.type = SR_DF_TRIGGER;
873                         packet.payload = NULL;
874                         sr_session_send(sdi, &packet);
875                         /* Post trigger samples. */
876                         num_samples -= trigger_offset;
877                         send_data(sdi, devc->deinterleave_buffer
878                                 + trigger_offset, num_samples);
879                         devc->sent_samples += num_samples;
880                 } else {
881                         send_data(sdi, devc->deinterleave_buffer, num_samples);
882                         devc->sent_samples += num_samples;
883                 }
884         }
885
886         if (devc->limit_samples && devc->sent_samples >= devc->limit_samples) {
887                 abort_acquisition(devc);
888                 free_transfer(transfer);
889         } else
890                 resubmit_transfer(transfer);
891 }
892
893 static int receive_data(int fd, int revents, void *cb_data)
894 {
895         struct timeval tv;
896         struct drv_context *drvc;
897
898         (void)fd;
899         (void)revents;
900
901         drvc = (struct drv_context *)cb_data;
902
903         tv.tv_sec = tv.tv_usec = 0;
904         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
905
906         return TRUE;
907 }
908
909 static size_t to_bytes_per_ms(const struct sr_dev_inst *sdi)
910 {
911         const struct dev_context *const devc = sdi->priv;
912         const size_t ch_count = enabled_channel_count(sdi);
913
914         if (devc->continuous_mode)
915                 return (devc->cur_samplerate * ch_count) / (1000 * 8);
916
917
918         /* If we're in buffered mode, the transfer rate is not so important,
919          * but we expect to get at least 10% of the high-speed USB bandwidth.
920          */
921         return 35000000 / (1000 * 10);
922 }
923
924 static size_t get_buffer_size(const struct sr_dev_inst *sdi)
925 {
926         /*
927          * The buffer should be large enough to hold 10ms of data and
928          * a multiple of the size of a data atom.
929          */
930         const size_t block_size = enabled_channel_count(sdi) * 512;
931         const size_t s = 10 * to_bytes_per_ms(sdi);
932         return ((s + block_size - 1) / block_size) * block_size;
933 }
934
935 static unsigned int get_number_of_transfers(const struct sr_dev_inst *sdi)
936 {
937         /* Total buffer size should be able to hold about 100ms of data. */
938         const unsigned int s = get_buffer_size(sdi);
939         const unsigned int n = (100 * to_bytes_per_ms(sdi) + s - 1) / s;
940         return (n > NUM_SIMUL_TRANSFERS) ? NUM_SIMUL_TRANSFERS : n;
941 }
942
943 static unsigned int get_timeout(const struct sr_dev_inst *sdi)
944 {
945         const size_t total_size = get_buffer_size(sdi) *
946                 get_number_of_transfers(sdi);
947         const unsigned int timeout = total_size / to_bytes_per_ms(sdi);
948         return timeout + timeout / 4; /* Leave a headroom of 25% percent. */
949 }
950
951 static int start_transfers(const struct sr_dev_inst *sdi)
952 {
953         const size_t channel_count = enabled_channel_count(sdi);
954         const size_t size = get_buffer_size(sdi);
955         const unsigned int num_transfers = get_number_of_transfers(sdi);
956         const unsigned int timeout = get_timeout(sdi);
957
958         struct dev_context *devc;
959         struct sr_usb_dev_inst *usb;
960         struct libusb_transfer *transfer;
961         unsigned int i;
962         int ret;
963         unsigned char *buf;
964
965         devc = sdi->priv;
966         usb = sdi->conn;
967
968         devc->sent_samples = 0;
969         devc->acq_aborted = FALSE;
970         devc->empty_transfer_count = 0;
971         devc->submitted_transfers = 0;
972
973         g_free(devc->transfers);
974         devc->transfers = g_try_malloc0(sizeof(*devc->transfers) * num_transfers);
975         if (!devc->transfers) {
976                 sr_err("USB transfers malloc failed.");
977                 return SR_ERR_MALLOC;
978         }
979
980         devc->deinterleave_buffer = g_try_malloc(DSLOGIC_ATOMIC_SAMPLES *
981                 (size / (channel_count * DSLOGIC_ATOMIC_BYTES)) * sizeof(uint16_t));
982         if (!devc->deinterleave_buffer) {
983                 sr_err("Deinterleave buffer malloc failed.");
984                 g_free(devc->deinterleave_buffer);
985                 return SR_ERR_MALLOC;
986         }
987
988         devc->num_transfers = num_transfers;
989         for (i = 0; i < num_transfers; i++) {
990                 if (!(buf = g_try_malloc(size))) {
991                         sr_err("USB transfer buffer malloc failed.");
992                         return SR_ERR_MALLOC;
993                 }
994                 transfer = libusb_alloc_transfer(0);
995                 libusb_fill_bulk_transfer(transfer, usb->devhdl,
996                                 6 | LIBUSB_ENDPOINT_IN, buf, size,
997                                 receive_transfer, (void *)sdi, timeout);
998                 sr_info("submitting transfer: %d", i);
999                 if ((ret = libusb_submit_transfer(transfer)) != 0) {
1000                         sr_err("Failed to submit transfer: %s.",
1001                                libusb_error_name(ret));
1002                         libusb_free_transfer(transfer);
1003                         g_free(buf);
1004                         abort_acquisition(devc);
1005                         return SR_ERR;
1006                 }
1007                 devc->transfers[i] = transfer;
1008                 devc->submitted_transfers++;
1009         }
1010
1011         std_session_send_df_header(sdi);
1012
1013         return SR_OK;
1014 }
1015
1016 static void LIBUSB_CALL trigger_receive(struct libusb_transfer *transfer)
1017 {
1018         const struct sr_dev_inst *sdi;
1019         struct dslogic_trigger_pos *tpos;
1020         struct dev_context *devc;
1021
1022         sdi = transfer->user_data;
1023         devc = sdi->priv;
1024         if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
1025                 sr_dbg("Trigger transfer canceled.");
1026                 /* Terminate session. */
1027                 std_session_send_df_end(sdi);
1028                 usb_source_remove(sdi->session, devc->ctx);
1029                 devc->num_transfers = 0;
1030                 g_free(devc->transfers);
1031         } else if (transfer->status == LIBUSB_TRANSFER_COMPLETED
1032                         && transfer->actual_length == sizeof(struct dslogic_trigger_pos)) {
1033                 tpos = (struct dslogic_trigger_pos *)transfer->buffer;
1034                 sr_info("tpos real_pos %d ram_saddr %d cnt %d", tpos->real_pos,
1035                         tpos->ram_saddr, tpos->remain_cnt);
1036                 devc->trigger_pos = tpos->real_pos;
1037                 g_free(tpos);
1038                 start_transfers(sdi);
1039         }
1040         libusb_free_transfer(transfer);
1041 }
1042
1043 SR_PRIV int dslogic_acquisition_start(const struct sr_dev_inst *sdi)
1044 {
1045         const unsigned int timeout = get_timeout(sdi);
1046
1047         struct sr_dev_driver *di;
1048         struct drv_context *drvc;
1049         struct dev_context *devc;
1050         struct sr_usb_dev_inst *usb;
1051         struct dslogic_trigger_pos *tpos;
1052         struct libusb_transfer *transfer;
1053         int ret;
1054
1055         di = sdi->driver;
1056         drvc = di->context;
1057         devc = sdi->priv;
1058         usb = sdi->conn;
1059
1060         devc->ctx = drvc->sr_ctx;
1061         devc->sent_samples = 0;
1062         devc->empty_transfer_count = 0;
1063         devc->acq_aborted = FALSE;
1064
1065         usb_source_add(sdi->session, devc->ctx, timeout, receive_data, drvc);
1066
1067         if ((ret = command_stop_acquisition(sdi)) != SR_OK)
1068                 return ret;
1069
1070         if ((ret = fpga_configure(sdi)) != SR_OK)
1071                 return ret;
1072
1073         if ((ret = command_start_acquisition(sdi)) != SR_OK)
1074                 return ret;
1075
1076         sr_dbg("Getting trigger.");
1077         tpos = g_malloc(sizeof(struct dslogic_trigger_pos));
1078         transfer = libusb_alloc_transfer(0);
1079         libusb_fill_bulk_transfer(transfer, usb->devhdl, 6 | LIBUSB_ENDPOINT_IN,
1080                         (unsigned char *)tpos, sizeof(struct dslogic_trigger_pos),
1081                         trigger_receive, (void *)sdi, 0);
1082         if ((ret = libusb_submit_transfer(transfer)) < 0) {
1083                 sr_err("Failed to request trigger: %s.", libusb_error_name(ret));
1084                 libusb_free_transfer(transfer);
1085                 g_free(tpos);
1086                 return SR_ERR;
1087         }
1088
1089         devc->transfers = g_try_malloc0(sizeof(*devc->transfers));
1090         if (!devc->transfers) {
1091                 sr_err("USB trigger_pos transfer malloc failed.");
1092                 return SR_ERR_MALLOC;
1093         }
1094         devc->num_transfers = 1;
1095         devc->submitted_transfers++;
1096         devc->transfers[0] = transfer;
1097
1098         return ret;
1099 }
1100
1101 SR_PRIV int dslogic_acquisition_stop(struct sr_dev_inst *sdi)
1102 {
1103         command_stop_acquisition(sdi);
1104         abort_acquisition(sdi->priv);
1105         return SR_OK;
1106 }