]> sigrok.org Git - libsigrok.git/blob - hardware/fx2lafw/fx2lafw.c
fx2lafw: Ensure default sample rate is set
[libsigrok.git] / hardware / fx2lafw / fx2lafw.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <inttypes.h>
23 #include <glib.h>
24 #include <libusb.h>
25 #include "config.h"
26 #include "sigrok.h"
27 #include "sigrok-internal.h"
28 #include "fx2lafw.h"
29 #include "command.h"
30
31 static struct fx2lafw_profile supported_fx2[] = {
32         /* USBee AX */
33         { 0x08a9, 0x0014, "CWAV", "USBee AX", NULL, 8 },
34         { 0, 0, 0, 0, 0, 0 }
35 };
36
37 static int fx2lafw_capabilities[] = {
38         SR_HWCAP_LOGIC_ANALYZER,
39         SR_HWCAP_SAMPLERATE,
40
41         /* These are really implemented in the driver, not the hardware. */
42         SR_HWCAP_LIMIT_SAMPLES,
43         SR_HWCAP_CONTINUOUS,
44         0,
45 };
46
47 static const char *fx2lafw_probe_names[] = {
48         "D0",
49         "D1",
50         "D2",
51         "D3",
52         "D4",
53         "D5",
54         "D6",
55         "D7",
56         NULL,
57 };
58
59 static uint64_t fx2lafw_supported_samplerates[] = {
60         SR_MHZ(1),
61         SR_MHZ(2),
62         SR_MHZ(3),
63         SR_MHZ(4),
64         SR_MHZ(6),
65         SR_MHZ(8),
66         SR_MHZ(12),
67         SR_MHZ(16),
68         SR_MHZ(24),
69 };
70
71 static struct sr_samplerates fx2lafw_samplerates = {
72         SR_MHZ(1),
73         SR_MHZ(24),
74         SR_HZ(0),
75         fx2lafw_supported_samplerates,
76 };
77
78 static GSList *dev_insts = NULL;
79 static libusb_context *usb_context = NULL;
80
81 static int hw_dev_config_set(int dev_index, int hwcap, void *value);
82 static int hw_dev_acquisition_stop(int dev_index, void *session_dev_id);
83
84 /**
85  * Check the USB configuration to determine if this is an fx2lafw device.
86  *
87  * @return TRUE if the device's configuration profile match fx2lafw
88  *         configuration, FALSE otherwise.
89  */
90 static gboolean check_conf_profile(libusb_device *dev)
91 {
92         struct libusb_device_descriptor des;
93         struct libusb_config_descriptor *conf_dsc = NULL;
94         const struct libusb_interface_descriptor *intf_dsc;
95         gboolean ret = FALSE;
96
97         while (!ret) {
98                 /* Assume it's not a Saleae Logic unless proven wrong. */
99                 ret = 0;
100
101                 if (libusb_get_device_descriptor(dev, &des) != 0)
102                         break;
103
104                 if (des.bNumConfigurations != 1)
105                         /* Need exactly 1 configuration. */
106                         break;
107
108                 if (libusb_get_config_descriptor(dev, 0, &conf_dsc) != 0)
109                         break;
110
111                 if (conf_dsc->bNumInterfaces != 1)
112                         /* Need exactly 1 interface. */
113                         break;
114
115                 if (conf_dsc->interface[0].num_altsetting != 1)
116                         /* Need just one alternate setting. */
117                         break;
118
119                 intf_dsc = &(conf_dsc->interface[0].altsetting[0]);
120                 if (intf_dsc->bNumEndpoints != 3)
121                         /* Need exactly 3 end points. */
122                         break;
123
124                 if ((intf_dsc->endpoint[0].bEndpointAddress & 0x8f) !=
125                     (1 | LIBUSB_ENDPOINT_OUT))
126                         /* The first endpoint should be 1 (outbound). */
127                         break;
128
129                 if ((intf_dsc->endpoint[1].bEndpointAddress & 0x8f) !=
130                     (2 | LIBUSB_ENDPOINT_IN))
131                         /* The second endpoint should be 2 (inbound). */
132                         break;
133
134                 /* TODO: Check the debug channel... */
135
136                 /* If we made it here, it must be an fx2lafw. */
137                 ret = TRUE;
138         }
139
140         if (conf_dsc)
141                 libusb_free_config_descriptor(conf_dsc);
142
143         return ret;
144 }
145
146 static int fx2lafw_open_dev(int dev_index)
147 {
148         libusb_device **devlist;
149         struct libusb_device_descriptor des;
150         struct sr_dev_inst *sdi;
151         struct context *ctx;
152         int err, skip, i;
153
154         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
155                 return SR_ERR;
156         ctx = sdi->priv;
157
158         if (sdi->status == SR_ST_ACTIVE)
159                 /* already in use */
160                 return SR_ERR;
161
162         skip = 0;
163         libusb_get_device_list(usb_context, &devlist);
164         for (i = 0; devlist[i]; i++) {
165                 if ((err = libusb_get_device_descriptor(devlist[i], &des))) {
166                         sr_err("fx2lafw: failed to get device descriptor: %d", err);
167                         continue;
168                 }
169
170                 if (des.idVendor != ctx->profile->vid
171                     || des.idProduct != ctx->profile->pid)
172                         continue;
173
174                 if (sdi->status == SR_ST_INITIALIZING) {
175                         if (skip != dev_index) {
176                                 /* Skip devices of this type that aren't the one we want. */
177                                 skip += 1;
178                                 continue;
179                         }
180                 } else if (sdi->status == SR_ST_INACTIVE) {
181                         /*
182                          * This device is fully enumerated, so we need to find
183                          * this device by vendor, product, bus and address.
184                          */
185                         if (libusb_get_bus_number(devlist[i]) != ctx->usb->bus
186                                 || libusb_get_device_address(devlist[i]) != ctx->usb->address)
187                                 /* this is not the one */
188                                 continue;
189                 }
190
191                 if (!(err = libusb_open(devlist[i], &ctx->usb->devhdl))) {
192                         if (ctx->usb->address == 0xff)
193                                 /*
194                                  * first time we touch this device after firmware upload,
195                                  * so we don't know the address yet.
196                                  */
197                                 ctx->usb->address = libusb_get_device_address(devlist[i]);
198
199                         sdi->status = SR_ST_ACTIVE;
200                         sr_info("fx2lafw: opened device %d on %d.%d interface %d",
201                                 sdi->index, ctx->usb->bus,
202                                 ctx->usb->address, USB_INTERFACE);
203                 } else {
204                         sr_err("fx2lafw: failed to open device: %d", err);
205                 }
206
207                 /* if we made it here, we handled the device one way or another */
208                 break;
209         }
210         libusb_free_device_list(devlist, 1);
211
212         if (sdi->status != SR_ST_ACTIVE)
213                 return SR_ERR;
214
215         return SR_OK;
216 }
217
218 static void close_dev(struct sr_dev_inst *sdi)
219 {
220         struct context *ctx;
221
222         ctx = sdi->priv;
223
224         if (ctx->usb->devhdl == NULL)
225                 return;
226
227         sr_info("fx2lafw: closing device %d on %d.%d interface %d", sdi->index,
228                 ctx->usb->bus, ctx->usb->address, USB_INTERFACE);
229         libusb_release_interface(ctx->usb->devhdl, USB_INTERFACE);
230         libusb_close(ctx->usb->devhdl);
231         ctx->usb->devhdl = NULL;
232         sdi->status = SR_ST_INACTIVE;
233 }
234
235 static struct context *fx2lafw_device_new(void)
236 {
237         struct context *ctx;
238
239         if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
240                 sr_err("fx2lafw: %s: ctx malloc failed", __func__);
241                 return NULL;
242         }
243
244         return ctx;
245 }
246
247 /*
248  * API callbacks
249  */
250
251 static int hw_init(const char *deviceinfo)
252 {
253         struct sr_dev_inst *sdi;
254         struct libusb_device_descriptor des;
255         struct fx2lafw_profile *fx2lafw_prof;
256         struct context *ctx;
257         libusb_device **devlist;
258         int err;
259         int devcnt = 0;
260         int i, j;
261
262         /* Avoid compiler warnings. */
263         (void)deviceinfo;
264
265         if (libusb_init(&usb_context) != 0) {
266                 sr_warn("Failed to initialize USB.");
267                 return 0;
268         }
269
270         /* Find all fx2lafw compatible devices and upload firware to all of them. */
271         libusb_get_device_list(usb_context, &devlist);
272         for (i = 0; devlist[i]; i++) {
273
274                 if ((err = libusb_get_device_descriptor(
275                         devlist[i], &des)) != 0) {
276                         sr_warn("failed to get device descriptor: %d", err);
277                         continue;
278                 }
279
280                 fx2lafw_prof = NULL;
281                 for (j = 0; supported_fx2[j].vid; j++) {
282                         if (des.idVendor == supported_fx2[j].vid &&
283                                 des.idProduct == supported_fx2[j].pid) {
284                                 fx2lafw_prof = &supported_fx2[j];
285                         }
286                 }
287
288                 /* Skip if the device was not found */
289                 if(!fx2lafw_prof)
290                         continue;
291
292                 sdi = sr_dev_inst_new(devcnt, SR_ST_INITIALIZING,
293                         fx2lafw_prof->vendor, fx2lafw_prof->model,
294                         fx2lafw_prof->model_version);
295                 if(!sdi)
296                         return 0;
297
298                 ctx = fx2lafw_device_new();
299                 ctx->profile = fx2lafw_prof;
300                 sdi->priv = ctx;
301                 dev_insts = g_slist_append(dev_insts, sdi);
302
303                 if (check_conf_profile(devlist[i])) {
304                         /* Already has the firmware, so fix the new address. */
305                         sr_dbg("fx2lafw: Found a fx2lafw device.");
306                         sdi->status = SR_ST_INACTIVE;
307                         ctx->usb = sr_usb_dev_inst_new
308                             (libusb_get_bus_number(devlist[i]),
309                              libusb_get_device_address(devlist[i]), NULL);
310                 } else {
311                         if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION, FIRMWARE) == SR_OK)
312                                 /* Remember when the firmware on this device was updated */
313                                 g_get_current_time(&ctx->fw_updated);
314                         else
315                                 sr_err("fx2lafw: firmware upload failed for "
316                                        "device %d", devcnt);
317                         ctx->usb = sr_usb_dev_inst_new
318                                 (libusb_get_bus_number(devlist[i]), 0xff, NULL);
319                 }
320
321                 devcnt++;
322         }
323         libusb_free_device_list(devlist, 1);
324
325         return devcnt;
326 }
327
328 static int hw_dev_open(int dev_index)
329 {
330         GTimeVal cur_time;
331         struct sr_dev_inst *sdi;
332         struct context *ctx;
333         int timediff, err;
334
335         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
336                 return SR_ERR;
337         ctx = sdi->priv;
338
339         /*
340          * if the firmware was recently uploaded, wait up to MAX_RENUM_DELAY ms
341          * for the FX2 to renumerate
342          */
343         err = 0;
344         if (GTV_TO_MSEC(ctx->fw_updated) > 0) {
345                 sr_info("fx2lafw: waiting for device to reset");
346                 /* takes at least 300ms for the FX2 to be gone from the USB bus */
347                 g_usleep(300 * 1000);
348                 timediff = 0;
349                 while (timediff < MAX_RENUM_DELAY) {
350                         if ((err = fx2lafw_open_dev(dev_index)) == SR_OK)
351                                 break;
352                         g_usleep(100 * 1000);
353                         g_get_current_time(&cur_time);
354                         timediff = GTV_TO_MSEC(cur_time) - GTV_TO_MSEC(ctx->fw_updated);
355                 }
356                 sr_info("fx2lafw: device came back after %d ms", timediff);
357         } else {
358                 err = fx2lafw_open_dev(dev_index);
359         }
360
361         if (err != SR_OK) {
362                 sr_err("fx2lafw: unable to open device");
363                 return SR_ERR;
364         }
365         ctx = sdi->priv;
366
367         err = libusb_claim_interface(ctx->usb->devhdl, USB_INTERFACE);
368         if (err != 0) {
369                 sr_err("fx2lafw: Unable to claim interface: %d", err);
370                 return SR_ERR;
371         }
372
373         if (ctx->cur_samplerate == 0) {
374                 /* Samplerate hasn't been set; default to the slowest one. */
375                 if (hw_dev_config_set(dev_index, SR_HWCAP_SAMPLERATE,
376                     &fx2lafw_supported_samplerates[0]) == SR_ERR)
377                         return SR_ERR;
378         }
379
380         return SR_OK;
381 }
382
383 static int hw_dev_close(int dev_index)
384 {
385         struct sr_dev_inst *sdi;
386
387         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index))) {
388                 sr_err("fx2lafw: %s: sdi was NULL", __func__);
389                 return SR_ERR_BUG;
390         }
391
392         /* TODO */
393         close_dev(sdi);
394
395         return SR_OK;
396 }
397
398 static int hw_cleanup(void)
399 {
400         GSList *l;
401         struct sr_dev_inst *sdi;
402         struct context *ctx;
403         int ret = SR_OK;
404
405         for(l = dev_insts; l; l = l->next) {
406                 if (!(sdi = l->data)) {
407                         /* Log error, but continue cleaning up the rest. */
408                         sr_err("fx2lafw: %s: sdi was NULL, continuing", __func__);
409                         ret = SR_ERR_BUG;
410                         continue;
411                 }
412                 if (!(ctx = sdi->priv)) {
413                         /* Log error, but continue cleaning up the rest. */
414                         sr_err("fx2lafw: %s: sdi->priv was NULL, continuing",
415                                __func__);
416                         ret = SR_ERR_BUG;
417                         continue;
418                 }
419                 close_dev(sdi);
420                 sdi = l->data;
421                 sr_dev_inst_free(sdi);
422         }
423
424         g_slist_free(dev_insts);
425         dev_insts = NULL;
426
427         if(usb_context)
428                 libusb_exit(usb_context);
429         usb_context = NULL;
430
431         return ret;
432 }
433
434 static void *hw_dev_info_get(int dev_index, int dev_info_id)
435 {
436         struct sr_dev_inst *sdi;
437         struct context *ctx;
438
439         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
440                 return NULL;
441         ctx = sdi->priv;
442
443         switch (dev_info_id) {
444         case SR_DI_INST:
445                 return sdi;
446         case SR_DI_NUM_PROBES:
447                 return GINT_TO_POINTER(ctx->profile->num_probes);
448         case SR_DI_PROBE_NAMES:
449                 return fx2lafw_probe_names;
450         case SR_DI_SAMPLERATES:
451                 return &fx2lafw_samplerates;
452         case SR_DI_TRIGGER_TYPES:
453                 return TRIGGER_TYPES;
454         case SR_DI_CUR_SAMPLERATE:
455                 return &ctx->cur_samplerate;
456         }
457
458         return NULL;
459 }
460
461 static int hw_dev_status_get(int dev_index)
462 {
463         const struct sr_dev_inst *const sdi =
464                 sr_dev_inst_get(dev_insts, dev_index);
465
466         if (!sdi)
467                 return SR_ST_NOT_FOUND;
468
469         return sdi->status;
470 }
471
472 static int *hw_hwcap_get_all(void)
473 {
474         return fx2lafw_capabilities;
475 }
476
477 static int hw_dev_config_set(int dev_index, int hwcap, void *value)
478 {
479         struct sr_dev_inst *sdi;
480         struct context *ctx;
481         int ret;
482
483         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
484                 return SR_ERR;
485         ctx = sdi->priv;
486
487         if (hwcap == SR_HWCAP_SAMPLERATE) {
488                 ctx->cur_samplerate = *(uint64_t *)value;
489                 ret = SR_OK;
490         } else if (hwcap == SR_HWCAP_PROBECONFIG) {
491                 ret = SR_OK;
492         } else if (hwcap == SR_HWCAP_LIMIT_SAMPLES) {
493                 ctx->limit_samples = *(uint64_t *)value;
494                 ret = SR_OK;
495         } else {
496                 ret = SR_ERR;
497         }
498
499         return ret;
500 }
501
502 static int receive_data(int fd, int revents, void *cb_data)
503 {
504         struct timeval tv;
505
506         /* Avoid compiler warnings. */
507         (void)fd;
508         (void)revents;
509         (void)cb_data;
510
511         tv.tv_sec = tv.tv_usec = 0;
512         libusb_handle_events_timeout(usb_context, &tv);
513
514         return TRUE;
515 }
516
517 static void abort_acquisition(struct context *ctx)
518 {
519         struct sr_datafeed_packet packet;
520
521         packet.type = SR_DF_END;
522         sr_session_send(ctx->session_dev_id, &packet);
523
524         ctx->num_samples = -1;
525
526         /* TODO: Need to cancel and free any queued up transfers. */
527 }
528
529 static void receive_transfer(struct libusb_transfer *transfer)
530 {
531         /* TODO: These statics have to move to the ctx struct. */
532         static int empty_transfer_count = 0;
533         struct sr_datafeed_packet packet;
534         struct sr_datafeed_logic logic;
535         struct context *ctx = transfer->user_data;
536         int cur_buflen;
537         unsigned char *cur_buf, *new_buf;
538
539         /*
540          * If acquisition has already ended, just free any queued up
541          * transfer that come in.
542          */
543         if (ctx->num_samples == -1) {
544                 if (transfer)
545                         libusb_free_transfer(transfer);
546                 return;
547         }
548
549         sr_info("fx2lafw: receive_transfer(): status %d received %d bytes",
550                 transfer->status, transfer->actual_length);
551
552         /* Save incoming transfer before reusing the transfer struct. */
553         cur_buf = transfer->buffer;
554         cur_buflen = transfer->actual_length;
555         ctx = transfer->user_data;
556
557         /* Fire off a new request. */
558         if (!(new_buf = g_try_malloc(4096))) {
559                 sr_err("fx2lafw: %s: new_buf malloc failed", __func__);
560                 return; /* TODO: SR_ERR_MALLOC */
561         }
562
563         transfer->buffer = new_buf;
564         transfer->length = 4096;
565         if (libusb_submit_transfer(transfer) != 0) {
566                 /* TODO: Stop session? */
567                 /* TODO: Better error message. */
568                 sr_err("fx2lafw: %s: libusb_submit_transfer error", __func__);
569         }
570
571         if (cur_buflen == 0) {
572                 empty_transfer_count++;
573                 if (empty_transfer_count > MAX_EMPTY_TRANSFERS) {
574                         /*
575                          * The FX2 gave up. End the acquisition, the frontend
576                          * will work out that the samplecount is short.
577                          */
578                         abort_acquisition(ctx);
579                 }
580                 return;
581         } else {
582                 empty_transfer_count = 0;
583         }
584
585         /* Send the incoming transfer to the session bus. */
586         packet.type = SR_DF_LOGIC;
587         packet.payload = &logic;
588         logic.length = cur_buflen;
589         logic.unitsize = 1;
590         logic.data = cur_buf;
591         sr_session_send(ctx->session_dev_id, &packet);
592         g_free(cur_buf);
593
594         ctx->num_samples += cur_buflen;
595         if (ctx->limit_samples &&
596                 (unsigned int) ctx->num_samples > ctx->limit_samples) {
597                 abort_acquisition(ctx);
598         }
599 }
600
601 static int hw_dev_acquisition_start(int dev_index, void *cb_data)
602 {
603         struct sr_dev_inst *sdi;
604         struct sr_datafeed_packet *packet;
605         struct sr_datafeed_header *header;
606         struct context *ctx;
607         struct libusb_transfer *transfer;
608         const struct libusb_pollfd **lupfd;
609         int err, size, i;
610         unsigned char *buf;
611
612         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
613                 return SR_ERR;
614         ctx = sdi->priv;
615         ctx->session_dev_id = cb_data;
616         ctx->num_samples = 0;
617
618         if (!(packet = g_try_malloc(sizeof(struct sr_datafeed_packet)))) {
619                 sr_err("fx2lafw: %s: packet malloc failed", __func__);
620                 return SR_ERR_MALLOC;
621         }
622
623         if (!(header = g_try_malloc(sizeof(struct sr_datafeed_header)))) {
624                 sr_err("fx2lafw: %s: header malloc failed", __func__);
625                 return SR_ERR_MALLOC;
626         }
627
628         if ((err = command_start_acquisition (ctx->usb->devhdl)) != SR_OK) {
629                 return err;
630         }
631
632         /* Start with 2K transfer, subsequently increased to 4K. */
633         size = 2048;
634         for (i = 0; i < NUM_SIMUL_TRANSFERS; i++) {
635                 if (!(buf = g_try_malloc(size))) {
636                         sr_err("fx2lafw: %s: buf malloc failed", __func__);
637                         return SR_ERR_MALLOC;
638                 }
639                 transfer = libusb_alloc_transfer(0);
640                 libusb_fill_bulk_transfer(transfer, ctx->usb->devhdl,
641                                 2 | LIBUSB_ENDPOINT_IN, buf, size,
642                                 receive_transfer, ctx, 40);
643                 if (libusb_submit_transfer(transfer) != 0) {
644                         /* TODO: Free them all. */
645                         libusb_free_transfer(transfer);
646                         g_free(buf);
647                         return SR_ERR;
648                 }
649                 size = 4096;
650         }
651
652         lupfd = libusb_get_pollfds(usb_context);
653         for (i = 0; lupfd[i]; i++)
654                 sr_source_add(lupfd[i]->fd, lupfd[i]->events,
655                               40, receive_data, NULL);
656         free(lupfd); /* NOT g_free()! */
657
658         packet->type = SR_DF_HEADER;
659         packet->payload = header;
660         header->feed_version = 1;
661         gettimeofday(&header->starttime, NULL);
662         header->samplerate = ctx->cur_samplerate;
663         header->num_logic_probes = ctx->profile->num_probes;
664         sr_session_send(cb_data, packet);
665         g_free(header);
666         g_free(packet);
667
668         return SR_OK;
669 }
670
671 /* TODO: This stops acquisition on ALL devices, ignoring dev_index. */
672 static int hw_dev_acquisition_stop(int dev_index, void *cb_data)
673 {
674         struct sr_dev_inst *sdi;
675
676         /* unused parameter */
677         (void)cb_data;
678
679         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
680                 return SR_ERR;
681  
682         abort_acquisition(sdi->priv);
683
684         return SR_OK;
685 }
686
687 SR_PRIV struct sr_dev_driver fx2lafw_driver_info = {
688         .name = "fx2lafw",
689         .longname = "fx2lafw",
690         .api_version = 1,
691         .init = hw_init,
692         .cleanup = hw_cleanup,
693         .dev_open = hw_dev_open,
694         .dev_close = hw_dev_close,
695         .dev_info_get = hw_dev_info_get,
696         .dev_status_get = hw_dev_status_get,
697         .hwcap_get_all = hw_hwcap_get_all,
698         .dev_config_set = hw_dev_config_set,
699         .dev_acquisition_start = hw_dev_acquisition_start,
700         .dev_acquisition_stop = hw_dev_acquisition_stop,
701 };