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