]> sigrok.org Git - libsigrok.git/blob - src/hardware/fx2lafw/protocol.c
Working trigger on rising and falling edges.
[libsigrok.git] / src / hardware / fx2lafw / 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 <glib.h>
23 #include <glib/gstdio.h>
24 #include "protocol.h"
25 #include "dslogic.h"
26
27 #pragma pack(push, 1)
28
29 struct version_info {
30         uint8_t major;
31         uint8_t minor;
32 };
33
34 struct cmd_start_acquisition {
35         uint8_t flags;
36         uint8_t sample_delay_h;
37         uint8_t sample_delay_l;
38 };
39
40 #pragma pack(pop)
41
42 #define USB_TIMEOUT 100
43
44 static int command_get_fw_version(libusb_device_handle *devhdl,
45                                   struct version_info *vi)
46 {
47         int ret;
48
49         ret = libusb_control_transfer(devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
50                 LIBUSB_ENDPOINT_IN, CMD_GET_FW_VERSION, 0x0000, 0x0000,
51                 (unsigned char *)vi, sizeof(struct version_info), USB_TIMEOUT);
52
53         if (ret < 0) {
54                 sr_err("Unable to get version info: %s.",
55                        libusb_error_name(ret));
56                 return SR_ERR;
57         }
58
59         return SR_OK;
60 }
61
62 static int command_get_revid_version(struct sr_dev_inst *sdi, uint8_t *revid)
63 {
64         struct dev_context *devc = sdi->priv;
65         struct sr_usb_dev_inst *usb = sdi->conn;
66         libusb_device_handle *devhdl = usb->devhdl;
67         int cmd, ret;
68
69         cmd = devc->dslogic ? DS_CMD_GET_REVID_VERSION : CMD_GET_REVID_VERSION;
70         ret = libusb_control_transfer(devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
71                 LIBUSB_ENDPOINT_IN, cmd, 0x0000, 0x0000, revid, 1, USB_TIMEOUT);
72
73         if (ret < 0) {
74                 sr_err("Unable to get REVID: %s.", libusb_error_name(ret));
75                 return SR_ERR;
76         }
77
78         return SR_OK;
79 }
80
81 SR_PRIV int fx2lafw_command_start_acquisition(const struct sr_dev_inst *sdi)
82 {
83         struct dev_context *devc;
84         struct sr_usb_dev_inst *usb;
85         uint64_t samplerate;
86         struct cmd_start_acquisition cmd;
87         int delay, ret;
88
89         devc = sdi->priv;
90         usb = sdi->conn;
91         samplerate = devc->cur_samplerate;
92
93         /* Compute the sample rate. */
94         if (devc->sample_wide && samplerate > MAX_16BIT_SAMPLE_RATE) {
95                 sr_err("Unable to sample at %" PRIu64 "Hz "
96                        "when collecting 16-bit samples.", samplerate);
97                 return SR_ERR;
98         }
99
100         delay = 0;
101         cmd.flags = cmd.sample_delay_h = cmd.sample_delay_l = 0;
102         if ((SR_MHZ(48) % samplerate) == 0) {
103                 cmd.flags = CMD_START_FLAGS_CLK_48MHZ;
104                 delay = SR_MHZ(48) / samplerate - 1;
105                 if (delay > MAX_SAMPLE_DELAY)
106                         delay = 0;
107         }
108
109         if (delay == 0 && (SR_MHZ(30) % samplerate) == 0) {
110                 cmd.flags = CMD_START_FLAGS_CLK_30MHZ;
111                 delay = SR_MHZ(30) / samplerate - 1;
112         }
113
114         sr_dbg("GPIF delay = %d, clocksource = %sMHz.", delay,
115                 (cmd.flags & CMD_START_FLAGS_CLK_48MHZ) ? "48" : "30");
116
117         if (delay <= 0 || delay > MAX_SAMPLE_DELAY) {
118                 sr_err("Unable to sample at %" PRIu64 "Hz.", samplerate);
119                 return SR_ERR;
120         }
121
122         cmd.sample_delay_h = (delay >> 8) & 0xff;
123         cmd.sample_delay_l = delay & 0xff;
124
125         /* Select the sampling width. */
126         cmd.flags |= devc->sample_wide ? CMD_START_FLAGS_SAMPLE_16BIT :
127                 CMD_START_FLAGS_SAMPLE_8BIT;
128
129         /* Send the control message. */
130         ret = libusb_control_transfer(usb->devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
131                         LIBUSB_ENDPOINT_OUT, CMD_START, 0x0000, 0x0000,
132                         (unsigned char *)&cmd, sizeof(cmd), USB_TIMEOUT);
133         if (ret < 0) {
134                 sr_err("Unable to send start command: %s.",
135                        libusb_error_name(ret));
136                 return SR_ERR;
137         }
138
139         return SR_OK;
140 }
141
142 /**
143  * Check the USB configuration to determine if this is an fx2lafw device.
144  *
145  * @return TRUE if the device's configuration profile matches fx2lafw
146  *         configuration, FALSE otherwise.
147  */
148 SR_PRIV gboolean match_manuf_prod(libusb_device *dev, const char *manufacturer,
149                 const char *product)
150 {
151         struct libusb_device_descriptor des;
152         struct libusb_device_handle *hdl;
153         gboolean ret;
154         unsigned char strdesc[64];
155
156         hdl = NULL;
157         ret = FALSE;
158         while (!ret) {
159                 /* Assume the FW has not been loaded, unless proven wrong. */
160                 libusb_get_device_descriptor(dev, &des);
161
162                 if (libusb_open(dev, &hdl) != 0)
163                         break;
164
165                 if (libusb_get_string_descriptor_ascii(hdl,
166                                 des.iManufacturer, strdesc, sizeof(strdesc)) < 0)
167                         break;
168                 if (strcmp((const char *)strdesc, manufacturer))
169                         break;
170
171                 if (libusb_get_string_descriptor_ascii(hdl,
172                                 des.iProduct, strdesc, sizeof(strdesc)) < 0)
173                         break;
174                 if (strcmp((const char *)strdesc, product))
175                         break;
176
177                 ret = TRUE;
178         }
179         if (hdl)
180                 libusb_close(hdl);
181
182         return ret;
183 }
184
185 SR_PRIV int fx2lafw_dev_open(struct sr_dev_inst *sdi, struct sr_dev_driver *di)
186 {
187         libusb_device **devlist;
188         struct sr_usb_dev_inst *usb;
189         struct libusb_device_descriptor des;
190         struct dev_context *devc;
191         struct drv_context *drvc;
192         struct version_info vi;
193         int ret, i, device_count;
194         uint8_t revid;
195         char connection_id[64];
196
197         drvc = di->context;
198         devc = sdi->priv;
199         usb = sdi->conn;
200
201         if (sdi->status == SR_ST_ACTIVE)
202                 /* Device is already in use. */
203                 return SR_ERR;
204
205         device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
206         if (device_count < 0) {
207                 sr_err("Failed to get device list: %s.",
208                        libusb_error_name(device_count));
209                 return SR_ERR;
210         }
211
212         for (i = 0; i < device_count; i++) {
213                 libusb_get_device_descriptor(devlist[i], &des);
214
215                 if (des.idVendor != devc->profile->vid
216                     || des.idProduct != devc->profile->pid)
217                         continue;
218
219                 if ((sdi->status == SR_ST_INITIALIZING) ||
220                                 (sdi->status == SR_ST_INACTIVE)) {
221                         /*
222                          * Check device by its physical USB bus/port address.
223                          */
224                         usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
225                         if (strcmp(sdi->connection_id, connection_id))
226                                 /* This is not the one. */
227                                 continue;
228                 }
229
230                 if (!(ret = libusb_open(devlist[i], &usb->devhdl))) {
231                         if (usb->address == 0xff)
232                                 /*
233                                  * First time we touch this device after FW
234                                  * upload, so we don't know the address yet.
235                                  */
236                                 usb->address = libusb_get_device_address(devlist[i]);
237                 } else {
238                         sr_err("Failed to open device: %s.",
239                                libusb_error_name(ret));
240                         break;
241                 }
242
243                 if (libusb_has_capability(LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER)) {
244                         if (libusb_kernel_driver_active(usb->devhdl, USB_INTERFACE) == 1) {
245                                 if ((ret = libusb_detach_kernel_driver(usb->devhdl, USB_INTERFACE)) < 0) {
246                                         sr_err("Failed to detach kernel driver: %s.",
247                                                 libusb_error_name(ret));
248                                         return SR_ERR;
249                                 }
250                         }
251                 }
252
253                 ret = command_get_fw_version(usb->devhdl, &vi);
254                 if (ret != SR_OK) {
255                         sr_err("Failed to get firmware version.");
256                         break;
257                 }
258
259                 ret = command_get_revid_version(sdi, &revid);
260                 if (ret != SR_OK) {
261                         sr_err("Failed to get REVID.");
262                         break;
263                 }
264
265                 /*
266                  * Changes in major version mean incompatible/API changes, so
267                  * bail out if we encounter an incompatible version.
268                  * Different minor versions are OK, they should be compatible.
269                  */
270                 if (vi.major != FX2LAFW_REQUIRED_VERSION_MAJOR) {
271                         sr_err("Expected firmware version %d.x, "
272                                "got %d.%d.", FX2LAFW_REQUIRED_VERSION_MAJOR,
273                                vi.major, vi.minor);
274                         break;
275                 }
276
277                 sdi->status = SR_ST_ACTIVE;
278                 sr_info("Opened device on %d.%d (logical) / %s (physical), "
279                         "interface %d, firmware %d.%d.",
280                         usb->bus, usb->address, connection_id,
281                         USB_INTERFACE, vi.major, vi.minor);
282
283                 sr_info("Detected REVID=%d, it's a Cypress CY7C68013%s.",
284                         revid, (revid != 1) ? " (FX2)" : "A (FX2LP)");
285
286                 break;
287         }
288         libusb_free_device_list(devlist, 1);
289
290         if (sdi->status != SR_ST_ACTIVE)
291                 return SR_ERR;
292
293         return SR_OK;
294 }
295
296 SR_PRIV struct dev_context *fx2lafw_dev_new(void)
297 {
298         struct dev_context *devc;
299
300         devc = g_malloc0(sizeof(struct dev_context));
301         devc->profile = NULL;
302         devc->fw_updated = 0;
303         devc->cur_samplerate = 0;
304         devc->limit_samples = 0;
305         devc->capture_ratio = 0;
306         devc->sample_wide = FALSE;
307         devc->trigger_en = FALSE;
308         devc->stl = NULL;
309
310         return devc;
311 }
312
313 SR_PRIV void fx2lafw_abort_acquisition(struct dev_context *devc)
314 {
315         int i;
316
317         devc->acq_aborted = TRUE;
318
319         for (i = devc->num_transfers - 1; i >= 0; i--) {
320                 if (devc->transfers[i])
321                         libusb_cancel_transfer(devc->transfers[i]);
322         }
323 }
324
325 static void finish_acquisition(struct sr_dev_inst *sdi)
326 {
327         struct sr_datafeed_packet packet;
328         struct dev_context *devc;
329
330         devc = sdi->priv;
331
332         /* Terminate session. */
333         packet.type = SR_DF_END;
334         sr_session_send(sdi, &packet);
335
336         /* Remove fds from polling. */
337         usb_source_remove(sdi->session, devc->ctx);
338
339         devc->num_transfers = 0;
340         g_free(devc->transfers);
341
342         if (devc->stl) {
343                 soft_trigger_logic_free(devc->stl);
344                 devc->stl = NULL;
345         }
346 }
347
348 static void free_transfer(struct libusb_transfer *transfer)
349 {
350         struct sr_dev_inst *sdi;
351         struct dev_context *devc;
352         unsigned int i;
353
354         sdi = transfer->user_data;
355         devc = sdi->priv;
356
357         g_free(transfer->buffer);
358         transfer->buffer = NULL;
359         libusb_free_transfer(transfer);
360
361         for (i = 0; i < devc->num_transfers; i++) {
362                 if (devc->transfers[i] == transfer) {
363                         devc->transfers[i] = NULL;
364                         break;
365                 }
366         }
367
368         devc->submitted_transfers--;
369         if (devc->submitted_transfers == 0)
370                 finish_acquisition(sdi);
371 }
372
373 static void resubmit_transfer(struct libusb_transfer *transfer)
374 {
375         int ret;
376
377         if ((ret = libusb_submit_transfer(transfer)) == LIBUSB_SUCCESS)
378                 return;
379
380         sr_err("%s: %s", __func__, libusb_error_name(ret));
381         free_transfer(transfer);
382
383 }
384
385 SR_PRIV void LIBUSB_CALL fx2lafw_receive_transfer(struct libusb_transfer *transfer)
386 {
387         struct sr_dev_inst *sdi;
388         struct dev_context *devc;
389         gboolean packet_has_error = FALSE;
390         struct sr_datafeed_packet packet;
391         struct sr_datafeed_logic logic;
392         unsigned int num_samples;
393         int trigger_offset, cur_sample_count, unitsize;
394         int pre_trigger_samples;
395
396         sdi = transfer->user_data;
397         devc = sdi->priv;
398
399         /*
400          * If acquisition has already ended, just free any queued up
401          * transfer that come in.
402          */
403         if (devc->acq_aborted) {
404                 free_transfer(transfer);
405                 return;
406         }
407
408         sr_dbg("receive_transfer(): status %s received %d bytes.",
409                 libusb_error_name(transfer->status), transfer->actual_length);
410
411         /* Save incoming transfer before reusing the transfer struct. */
412         unitsize = devc->sample_wide ? 2 : 1;
413         cur_sample_count = transfer->actual_length / unitsize;
414
415         switch (transfer->status) {
416         case LIBUSB_TRANSFER_NO_DEVICE:
417                 fx2lafw_abort_acquisition(devc);
418                 free_transfer(transfer);
419                 return;
420         case LIBUSB_TRANSFER_COMPLETED:
421         case LIBUSB_TRANSFER_TIMED_OUT: /* We may have received some data though. */
422                 break;
423         default:
424                 packet_has_error = TRUE;
425                 break;
426         }
427
428         if (transfer->actual_length == 0 || packet_has_error) {
429                 devc->empty_transfer_count++;
430                 if (devc->empty_transfer_count > MAX_EMPTY_TRANSFERS) {
431                         /*
432                          * The FX2 gave up. End the acquisition, the frontend
433                          * will work out that the samplecount is short.
434                          */
435                         fx2lafw_abort_acquisition(devc);
436                         free_transfer(transfer);
437                 } else {
438                         resubmit_transfer(transfer);
439                 }
440                 return;
441         } else {
442                 devc->empty_transfer_count = 0;
443         }
444         if (devc->trigger_en)
445                 devc->trigger_fired = TRUE;
446         if (devc->trigger_fired) {
447                 if (!devc->limit_samples || devc->sent_samples < devc->limit_samples) {
448                         /* Send the incoming transfer to the session bus. */
449                         packet.type = SR_DF_LOGIC;
450                         packet.payload = &logic;
451                         if (devc->limit_samples && devc->sent_samples + cur_sample_count > devc->limit_samples)
452                                 num_samples = devc->limit_samples - devc->sent_samples;
453                         else
454                                 num_samples = cur_sample_count;
455                         logic.length = num_samples * unitsize;
456                         logic.unitsize = unitsize;
457                         logic.data = transfer->buffer;
458                         sr_session_send(devc->cb_data, &packet);
459                         devc->sent_samples += num_samples;
460                 }
461         } else {
462                 trigger_offset = soft_trigger_logic_check(devc->stl,
463                         transfer->buffer, transfer->actual_length, &pre_trigger_samples);
464                 if (trigger_offset > -1) {
465                         devc->sent_samples += pre_trigger_samples;
466                         packet.type = SR_DF_LOGIC;
467                         packet.payload = &logic;
468                         num_samples = cur_sample_count - trigger_offset;
469                         if (devc->limit_samples &&
470                                         num_samples > devc->limit_samples - devc->sent_samples)
471                                 num_samples = devc->limit_samples - devc->sent_samples;
472                         logic.length = num_samples * unitsize;
473                         logic.unitsize = unitsize;
474                         logic.data = transfer->buffer + trigger_offset * unitsize;
475                         sr_session_send(devc->cb_data, &packet);
476                         devc->sent_samples += num_samples;
477
478                         devc->trigger_fired = TRUE;
479                 }
480         }
481
482         if (devc->limit_samples && devc->sent_samples >= devc->limit_samples) {
483                 fx2lafw_abort_acquisition(devc);
484                 free_transfer(transfer);
485         } else
486                 resubmit_transfer(transfer);
487 }
488
489 static unsigned int to_bytes_per_ms(unsigned int samplerate)
490 {
491         return samplerate / 1000;
492 }
493
494 SR_PRIV size_t fx2lafw_get_buffer_size(struct dev_context *devc)
495 {
496         size_t s;
497
498         /*
499          * The buffer should be large enough to hold 10ms of data and
500          * a multiple of 512.
501          */
502         s = 10 * to_bytes_per_ms(devc->cur_samplerate);
503         return (s + 511) & ~511;
504 }
505
506 SR_PRIV unsigned int fx2lafw_get_number_of_transfers(struct dev_context *devc)
507 {
508         unsigned int n;
509
510         /* Total buffer size should be able to hold about 500ms of data. */
511         n = (500 * to_bytes_per_ms(devc->cur_samplerate) /
512                 fx2lafw_get_buffer_size(devc));
513
514         if (n > NUM_SIMUL_TRANSFERS)
515                 return NUM_SIMUL_TRANSFERS;
516
517         return n;
518 }
519
520 SR_PRIV unsigned int fx2lafw_get_timeout(struct dev_context *devc)
521 {
522         size_t total_size;
523         unsigned int timeout;
524
525         total_size = fx2lafw_get_buffer_size(devc) *
526                         fx2lafw_get_number_of_transfers(devc);
527         timeout = total_size / to_bytes_per_ms(devc->cur_samplerate);
528         return timeout + timeout / 4; /* Leave a headroom of 25% percent. */
529 }