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