]> sigrok.org Git - libsigrok.git/blob - src/hardware/fx2lafw/protocol.c
Factor out std_session_send_df_end() helper.
[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         /* Enable CTL2 clock. */
129         cmd.flags |= (devc->profile->dev_caps & DEV_CAPS_AX_ANALOG) ? CMD_START_FLAGS_CLK_CTL2 : 0;
130
131         /* Send the control message. */
132         ret = libusb_control_transfer(usb->devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
133                         LIBUSB_ENDPOINT_OUT, CMD_START, 0x0000, 0x0000,
134                         (unsigned char *)&cmd, sizeof(cmd), USB_TIMEOUT);
135         if (ret < 0) {
136                 sr_err("Unable to send start command: %s.",
137                        libusb_error_name(ret));
138                 return SR_ERR;
139         }
140
141         return SR_OK;
142 }
143
144 /**
145  * Check the USB configuration to determine if this is an fx2lafw device.
146  *
147  * @return TRUE if the device's configuration profile matches fx2lafw
148  *         configuration, FALSE otherwise.
149  */
150 SR_PRIV gboolean match_manuf_prod(libusb_device *dev, const char *manufacturer,
151                 const char *product)
152 {
153         struct libusb_device_descriptor des;
154         struct libusb_device_handle *hdl;
155         gboolean ret;
156         unsigned char strdesc[64];
157
158         hdl = NULL;
159         ret = FALSE;
160         while (!ret) {
161                 /* Assume the FW has not been loaded, unless proven wrong. */
162                 libusb_get_device_descriptor(dev, &des);
163
164                 if (libusb_open(dev, &hdl) != 0)
165                         break;
166
167                 if (libusb_get_string_descriptor_ascii(hdl,
168                                 des.iManufacturer, strdesc, sizeof(strdesc)) < 0)
169                         break;
170                 if (strcmp((const char *)strdesc, manufacturer))
171                         break;
172
173                 if (libusb_get_string_descriptor_ascii(hdl,
174                                 des.iProduct, strdesc, sizeof(strdesc)) < 0)
175                         break;
176                 if (strcmp((const char *)strdesc, product))
177                         break;
178
179                 ret = TRUE;
180         }
181         if (hdl)
182                 libusb_close(hdl);
183
184         return ret;
185 }
186
187 SR_PRIV int fx2lafw_dev_open(struct sr_dev_inst *sdi, struct sr_dev_driver *di)
188 {
189         libusb_device **devlist;
190         struct sr_usb_dev_inst *usb;
191         struct libusb_device_descriptor des;
192         struct dev_context *devc;
193         struct drv_context *drvc;
194         struct version_info vi;
195         int ret, i, device_count;
196         uint8_t revid;
197         char connection_id[64];
198
199         drvc = di->context;
200         devc = sdi->priv;
201         usb = sdi->conn;
202
203         if (sdi->status == SR_ST_ACTIVE)
204                 /* Device is already in use. */
205                 return SR_ERR;
206
207         device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
208         if (device_count < 0) {
209                 sr_err("Failed to get device list: %s.",
210                        libusb_error_name(device_count));
211                 return SR_ERR;
212         }
213
214         for (i = 0; i < device_count; i++) {
215                 libusb_get_device_descriptor(devlist[i], &des);
216
217                 if (des.idVendor != devc->profile->vid
218                     || des.idProduct != devc->profile->pid)
219                         continue;
220
221                 if ((sdi->status == SR_ST_INITIALIZING) ||
222                                 (sdi->status == SR_ST_INACTIVE)) {
223                         /*
224                          * Check device by its physical USB bus/port address.
225                          */
226                         usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
227                         if (strcmp(sdi->connection_id, connection_id))
228                                 /* This is not the one. */
229                                 continue;
230                 }
231
232                 if (!(ret = libusb_open(devlist[i], &usb->devhdl))) {
233                         if (usb->address == 0xff)
234                                 /*
235                                  * First time we touch this device after FW
236                                  * upload, so we don't know the address yet.
237                                  */
238                                 usb->address = libusb_get_device_address(devlist[i]);
239                 } else {
240                         sr_err("Failed to open device: %s.",
241                                libusb_error_name(ret));
242                         break;
243                 }
244
245                 if (libusb_has_capability(LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER)) {
246                         if (libusb_kernel_driver_active(usb->devhdl, USB_INTERFACE) == 1) {
247                                 if ((ret = libusb_detach_kernel_driver(usb->devhdl, USB_INTERFACE)) < 0) {
248                                         sr_err("Failed to detach kernel driver: %s.",
249                                                 libusb_error_name(ret));
250                                         return SR_ERR;
251                                 }
252                         }
253                 }
254
255                 ret = command_get_fw_version(usb->devhdl, &vi);
256                 if (ret != SR_OK) {
257                         sr_err("Failed to get firmware version.");
258                         break;
259                 }
260
261                 ret = command_get_revid_version(sdi, &revid);
262                 if (ret != SR_OK) {
263                         sr_err("Failed to get REVID.");
264                         break;
265                 }
266
267                 /*
268                  * Changes in major version mean incompatible/API changes, so
269                  * bail out if we encounter an incompatible version.
270                  * Different minor versions are OK, they should be compatible.
271                  */
272                 if (vi.major != FX2LAFW_REQUIRED_VERSION_MAJOR) {
273                         sr_err("Expected firmware version %d.x, "
274                                "got %d.%d.", FX2LAFW_REQUIRED_VERSION_MAJOR,
275                                vi.major, vi.minor);
276                         break;
277                 }
278
279                 sdi->status = SR_ST_ACTIVE;
280                 sr_info("Opened device on %d.%d (logical) / %s (physical), "
281                         "interface %d, firmware %d.%d.",
282                         usb->bus, usb->address, connection_id,
283                         USB_INTERFACE, vi.major, vi.minor);
284
285                 sr_info("Detected REVID=%d, it's a Cypress CY7C68013%s.",
286                         revid, (revid != 1) ? " (FX2)" : "A (FX2LP)");
287
288                 break;
289         }
290         libusb_free_device_list(devlist, 1);
291
292         if (sdi->status != SR_ST_ACTIVE)
293                 return SR_ERR;
294
295         return SR_OK;
296 }
297
298 SR_PRIV struct dev_context *fx2lafw_dev_new(void)
299 {
300         struct dev_context *devc;
301
302         devc = g_malloc0(sizeof(struct dev_context));
303         devc->profile = NULL;
304         devc->fw_updated = 0;
305         devc->cur_samplerate = 0;
306         devc->limit_samples = 0;
307         devc->capture_ratio = 0;
308         devc->sample_wide = FALSE;
309         devc->trigger_en = FALSE;
310         devc->stl = NULL;
311
312         return devc;
313 }
314
315 SR_PRIV void fx2lafw_abort_acquisition(struct dev_context *devc)
316 {
317         int i;
318
319         devc->acq_aborted = TRUE;
320
321         for (i = devc->num_transfers - 1; i >= 0; i--) {
322                 if (devc->transfers[i])
323                         libusb_cancel_transfer(devc->transfers[i]);
324         }
325 }
326
327 static void finish_acquisition(struct sr_dev_inst *sdi)
328 {
329         struct dev_context *devc;
330
331         devc = sdi->priv;
332
333         std_session_send_df_end(sdi, LOG_PREFIX);
334
335         /* Remove fds from polling. */
336         usb_source_remove(sdi->session, devc->ctx);
337
338         devc->num_transfers = 0;
339         g_free(devc->transfers);
340
341         /* Free the deinterlace buffers if we had them */
342         g_free(devc->logic_buffer);
343         g_free(devc->analog_buffer);
344
345         if (devc->stl) {
346                 soft_trigger_logic_free(devc->stl);
347                 devc->stl = NULL;
348         }
349 }
350
351 static void free_transfer(struct libusb_transfer *transfer)
352 {
353         struct sr_dev_inst *sdi;
354         struct dev_context *devc;
355         unsigned int i;
356
357         sdi = transfer->user_data;
358         devc = sdi->priv;
359
360         g_free(transfer->buffer);
361         transfer->buffer = NULL;
362         libusb_free_transfer(transfer);
363
364         for (i = 0; i < devc->num_transfers; i++) {
365                 if (devc->transfers[i] == transfer) {
366                         devc->transfers[i] = NULL;
367                         break;
368                 }
369         }
370
371         devc->submitted_transfers--;
372         if (devc->submitted_transfers == 0)
373                 finish_acquisition(sdi);
374 }
375
376 static void resubmit_transfer(struct libusb_transfer *transfer)
377 {
378         int ret;
379
380         if ((ret = libusb_submit_transfer(transfer)) == LIBUSB_SUCCESS)
381                 return;
382
383         sr_err("%s: %s", __func__, libusb_error_name(ret));
384         free_transfer(transfer);
385
386 }
387
388 SR_PRIV void mso_send_data_proc(struct dev_context *devc,
389         uint8_t *data, size_t length, size_t sample_width)
390 {
391         size_t i;
392         sample_width = sample_width;
393         length /= 2;
394
395         /* Send the logic */
396         for(i = 0; i < length; i++) {
397                 devc->logic_buffer[i]  = data[i * 2];
398                 /* Rescale to -10V - +10V from 0-255. */
399                 devc->analog_buffer[i] = data[i * 2 + 1] - 128.0f / 12.8f;
400         };
401
402         const struct sr_datafeed_logic logic = {
403                 .length = length,
404                 .unitsize = 1,
405                 .data = devc->logic_buffer
406         };
407
408         const struct sr_datafeed_packet logic_packet = {
409                 .type = SR_DF_LOGIC,
410                 .payload = &logic
411         };
412         sr_session_send(devc->cb_data, &logic_packet);
413
414         const struct sr_datafeed_analog_old analog = {
415                 .channels = devc->enabled_analog_channels,
416                 .num_samples = length,
417                 .mq = SR_MQ_VOLTAGE,
418                 .unit = SR_UNIT_VOLT,
419                 .mqflags = 0 /*SR_MQFLAG_DC*/,
420                 .data = devc->analog_buffer
421         };
422
423         const struct sr_datafeed_packet analog_packet = {
424                 .type = SR_DF_ANALOG_OLD,
425                 .payload = &analog
426         };
427         sr_session_send(devc->cb_data, &analog_packet);
428
429 }
430
431 SR_PRIV void la_send_data_proc(struct dev_context *devc,
432         uint8_t *data, size_t length, size_t sample_width)
433 {
434         const struct sr_datafeed_logic logic = {
435                 .length = length,
436                 .unitsize = sample_width,
437                 .data = data
438         };
439
440         const struct sr_datafeed_packet packet = {
441                 .type = SR_DF_LOGIC,
442                 .payload = &logic
443         };
444
445         sr_session_send(devc->cb_data, &packet);
446 }
447
448 SR_PRIV void LIBUSB_CALL fx2lafw_receive_transfer(struct libusb_transfer *transfer)
449 {
450         struct sr_dev_inst *sdi;
451         struct dev_context *devc;
452         gboolean packet_has_error = FALSE;
453         unsigned int num_samples;
454         int trigger_offset, cur_sample_count, unitsize;
455         int pre_trigger_samples;
456
457         sdi = transfer->user_data;
458         devc = sdi->priv;
459
460         /*
461          * If acquisition has already ended, just free any queued up
462          * transfer that come in.
463          */
464         if (devc->acq_aborted) {
465                 free_transfer(transfer);
466                 return;
467         }
468
469         sr_dbg("receive_transfer(): status %s received %d bytes.",
470                 libusb_error_name(transfer->status), transfer->actual_length);
471
472         /* Save incoming transfer before reusing the transfer struct. */
473         unitsize = devc->sample_wide ? 2 : 1;
474         cur_sample_count = transfer->actual_length / unitsize;
475
476         switch (transfer->status) {
477         case LIBUSB_TRANSFER_NO_DEVICE:
478                 fx2lafw_abort_acquisition(devc);
479                 free_transfer(transfer);
480                 return;
481         case LIBUSB_TRANSFER_COMPLETED:
482         case LIBUSB_TRANSFER_TIMED_OUT: /* We may have received some data though. */
483                 break;
484         default:
485                 packet_has_error = TRUE;
486                 break;
487         }
488
489         if (transfer->actual_length == 0 || packet_has_error) {
490                 devc->empty_transfer_count++;
491                 if (devc->empty_transfer_count > MAX_EMPTY_TRANSFERS) {
492                         /*
493                          * The FX2 gave up. End the acquisition, the frontend
494                          * will work out that the samplecount is short.
495                          */
496                         fx2lafw_abort_acquisition(devc);
497                         free_transfer(transfer);
498                 } else {
499                         resubmit_transfer(transfer);
500                 }
501                 return;
502         } else {
503                 devc->empty_transfer_count = 0;
504         }
505         if (devc->trigger_en)
506                 devc->trigger_fired = TRUE;
507         if (devc->trigger_fired) {
508                 if (!devc->limit_samples || devc->sent_samples < devc->limit_samples) {
509                         /* Send the incoming transfer to the session bus. */
510                         if (devc->limit_samples && devc->sent_samples + cur_sample_count > devc->limit_samples)
511                                 num_samples = devc->limit_samples - devc->sent_samples;
512                         else
513                                 num_samples = cur_sample_count;
514
515                         devc->send_data_proc(devc,
516                                                 (uint8_t*)transfer->buffer,
517                                                 num_samples * unitsize,
518                                                 unitsize);
519                         devc->sent_samples += num_samples;
520                 }
521         } else {
522                 trigger_offset = soft_trigger_logic_check(devc->stl,
523                         transfer->buffer, transfer->actual_length, &pre_trigger_samples);
524                 if (trigger_offset > -1) {
525                         devc->sent_samples += pre_trigger_samples;
526                         num_samples = cur_sample_count - trigger_offset;
527                         if (devc->limit_samples &&
528                                         num_samples > devc->limit_samples - devc->sent_samples)
529                                 num_samples = devc->limit_samples - devc->sent_samples;
530
531                         devc->send_data_proc(devc,
532                                                 (uint8_t*)transfer->buffer + trigger_offset * unitsize,
533                                                 num_samples * unitsize,
534                                                 unitsize);
535                         devc->sent_samples += num_samples;
536
537                         devc->trigger_fired = TRUE;
538                 }
539         }
540
541         if (devc->limit_samples && devc->sent_samples >= devc->limit_samples) {
542                 fx2lafw_abort_acquisition(devc);
543                 free_transfer(transfer);
544         } else
545                 resubmit_transfer(transfer);
546 }
547
548 static unsigned int to_bytes_per_ms(unsigned int samplerate)
549 {
550         return samplerate / 1000;
551 }
552
553 SR_PRIV size_t fx2lafw_get_buffer_size(struct dev_context *devc)
554 {
555         size_t s;
556
557         /*
558          * The buffer should be large enough to hold 10ms of data and
559          * a multiple of 512.
560          */
561         s = 10 * to_bytes_per_ms(devc->cur_samplerate);
562         return (s + 511) & ~511;
563 }
564
565 SR_PRIV unsigned int fx2lafw_get_number_of_transfers(struct dev_context *devc)
566 {
567         unsigned int n;
568
569         /* Total buffer size should be able to hold about 500ms of data. */
570         n = (500 * to_bytes_per_ms(devc->cur_samplerate) /
571                 fx2lafw_get_buffer_size(devc));
572
573         if (n > NUM_SIMUL_TRANSFERS)
574                 return NUM_SIMUL_TRANSFERS;
575
576         return n;
577 }
578
579 SR_PRIV unsigned int fx2lafw_get_timeout(struct dev_context *devc)
580 {
581         size_t total_size;
582         unsigned int timeout;
583
584         total_size = fx2lafw_get_buffer_size(devc) *
585                         fx2lafw_get_number_of_transfers(devc);
586         timeout = total_size / to_bytes_per_ms(devc->cur_samplerate);
587         return timeout + timeout / 4; /* Leave a headroom of 25% percent. */
588 }