]> sigrok.org Git - libsigrok.git/blob - src/hardware/sysclk-lwla/api.c
d0eb82caec8babc61bf6fd4569370e9408153f16
[libsigrok.git] / src / hardware / sysclk-lwla / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 Daniel Elstner <daniel.kitta@gmail.com>
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 <config.h>
21 #include <glib.h>
22 #include <libusb.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <libsigrok/libsigrok.h>
26 #include <libsigrok-internal.h>
27 #include "protocol.h"
28
29 static const uint32_t scanopts[] = {
30         SR_CONF_CONN,
31 };
32
33 static const uint32_t drvopts[] = {
34         SR_CONF_LOGIC_ANALYZER,
35 };
36
37 static const int32_t trigger_matches[] = {
38         SR_TRIGGER_ZERO,
39         SR_TRIGGER_ONE,
40         SR_TRIGGER_RISING,
41         SR_TRIGGER_FALLING,
42 };
43
44 static const char *const trigger_source_names[] = {
45         [TRIGGER_CHANNELS] = "CH",
46         [TRIGGER_EXT_TRG] = "TRG",
47 };
48
49 static const char *const signal_edge_names[] = {
50         [EDGE_POSITIVE] = "r",
51         [EDGE_NEGATIVE] = "f",
52 };
53
54 static struct sr_dev_inst *dev_inst_new(const struct model_info *model)
55 {
56         struct sr_dev_inst *sdi;
57         struct dev_context *devc;
58         int i;
59         char name[8];
60
61         devc = g_malloc0(sizeof(struct dev_context));
62         devc->model = model;
63         devc->active_fpga_config = FPGA_NOCONF;
64         devc->cfg_rle = TRUE;
65         devc->samplerate = model->samplerates[0];
66         devc->channel_mask = (UINT64_C(1) << model->num_channels) - 1;
67
68         sdi = g_malloc0(sizeof(struct sr_dev_inst));
69         sdi->status = SR_ST_INACTIVE;
70         sdi->vendor = g_strdup("SysClk");
71         sdi->model = g_strdup(model->name);
72         sdi->priv = devc;
73
74         for (i = 0; i < model->num_channels; i++) {
75                 g_snprintf(name, sizeof(name), "CH%d", i + 1);
76                 sr_channel_new(sdi, i, SR_CHANNEL_LOGIC, TRUE, name);
77         }
78
79         return sdi;
80 }
81
82 /* Create a new device instance for a libusb device if it is a SysClk LWLA
83  * device and also matches the connection specification.
84  */
85 static struct sr_dev_inst *dev_inst_new_matching(GSList *conn_matches,
86                                                  libusb_device *dev)
87 {
88         GSList *node;
89         struct sr_usb_dev_inst *usb;
90         const struct model_info *model;
91         struct sr_dev_inst *sdi;
92         struct libusb_device_descriptor des;
93         int bus, address, ret;
94         unsigned int vid, pid;
95
96         bus = libusb_get_bus_number(dev);
97         address = libusb_get_device_address(dev);
98
99         for (node = conn_matches; node != NULL; node = node->next) {
100                 usb = node->data;
101                 if (usb && usb->bus == bus && usb->address == address)
102                         break; /* found */
103         }
104         if (conn_matches && !node)
105                 return NULL; /* no match */
106
107         ret = libusb_get_device_descriptor(dev, &des);
108         if (ret != 0) {
109                 sr_err("Failed to get USB device descriptor: %s.",
110                         libusb_error_name(ret));
111                 return NULL;
112         }
113         vid = des.idVendor;
114         pid = des.idProduct;
115
116         /* Create sigrok device instance. */
117         if (vid == USB_VID_SYSCLK && pid == USB_PID_LWLA1016) {
118                 model = &lwla1016_info;
119         } else if (vid == USB_VID_SYSCLK && pid == USB_PID_LWLA1034) {
120                 model = &lwla1034_info;
121         } else {
122                 if (conn_matches)
123                         sr_warn("USB device %d.%d (%04x:%04x) is not a"
124                                 " SysClk LWLA.", bus, address, vid, pid);
125                 return NULL;
126         }
127         sdi = dev_inst_new(model);
128
129         sdi->inst_type = SR_INST_USB;
130         sdi->conn = sr_usb_dev_inst_new(bus, address, NULL);
131
132         return sdi;
133 }
134
135 static GSList *scan(struct sr_dev_driver *di, GSList *options)
136 {
137         GSList *conn_devices, *devices, *node;
138         struct drv_context *drvc;
139         struct sr_dev_inst *sdi;
140         struct sr_config *src;
141         const char *conn;
142         libusb_device **devlist;
143         ssize_t num_devs, i;
144
145         drvc = di->context;
146         conn = NULL;
147         conn_devices = NULL;
148         devices = NULL;
149
150         for (node = options; node != NULL; node = node->next) {
151                 src = node->data;
152                 if (src->key == SR_CONF_CONN) {
153                         conn = g_variant_get_string(src->data, NULL);
154                         break;
155                 }
156         }
157         if (conn) {
158                 /* Find devices matching the connection specification. */
159                 conn_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn);
160         }
161
162         /* List all libusb devices. */
163         num_devs = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
164         if (num_devs < 0) {
165                 sr_err("Failed to list USB devices: %s.",
166                         libusb_error_name(num_devs));
167                 g_slist_free_full(conn_devices,
168                         (GDestroyNotify)&sr_usb_dev_inst_free);
169                 return NULL;
170         }
171
172         /* Scan the USB device list for matching LWLA devices. */
173         for (i = 0; i < num_devs; i++) {
174                 sdi = dev_inst_new_matching(conn_devices, devlist[i]);
175                 if (!sdi)
176                         continue; /* no match */
177
178                 /* Register device instance with driver. */
179                 devices = g_slist_append(devices, sdi);
180         }
181
182         libusb_free_device_list(devlist, 1);
183         g_slist_free_full(conn_devices, (GDestroyNotify)&sr_usb_dev_inst_free);
184
185         return std_scan_complete(di, devices);
186 }
187
188 /* Drain any pending data from the USB transfer buffers on the device.
189  * This may be necessary e.g. after a crash or generally to clean up after
190  * an abnormal condition.
191  */
192 static int drain_usb(struct sr_usb_dev_inst *usb, unsigned int endpoint)
193 {
194         int drained, xfer_len, ret;
195         unsigned char buf[512];
196         const unsigned int drain_timeout_ms = 10;
197
198         drained = 0;
199         do {
200                 xfer_len = 0;
201                 ret = libusb_bulk_transfer(usb->devhdl, endpoint,
202                                            buf, sizeof(buf), &xfer_len,
203                                            drain_timeout_ms);
204                 drained += xfer_len;
205         } while (ret == LIBUSB_SUCCESS && xfer_len != 0);
206
207         if (ret != LIBUSB_SUCCESS && ret != LIBUSB_ERROR_TIMEOUT) {
208                 sr_err("Failed to drain USB endpoint %u: %s.",
209                        endpoint & (LIBUSB_ENDPOINT_IN - 1),
210                        libusb_error_name(ret));
211                 return SR_ERR;
212         }
213         if (drained > 0) {
214                 sr_warn("Drained %d bytes from USB endpoint %u.",
215                         drained, endpoint & (LIBUSB_ENDPOINT_IN - 1));
216         }
217
218         return SR_OK;
219 }
220
221 static int dev_open(struct sr_dev_inst *sdi)
222 {
223         struct drv_context *drvc;
224         struct dev_context *devc;
225         struct sr_usb_dev_inst *usb;
226         int i, ret;
227
228         drvc = sdi->driver->context;
229         devc = sdi->priv;
230         usb = sdi->conn;
231
232         /* Try the whole shebang three times, fingers crossed. */
233         for (i = 0; i < 3; i++) {
234                 ret = sr_usb_open(drvc->sr_ctx->libusb_ctx, usb);
235                 if (ret != SR_OK)
236                         return ret;
237
238                 ret = libusb_set_configuration(usb->devhdl, USB_CONFIG);
239                 if (ret != LIBUSB_SUCCESS) {
240                         sr_err("Failed to set USB configuration: %s.",
241                                 libusb_error_name(ret));
242                         sr_usb_close(usb);
243                         return SR_ERR;
244                 }
245
246                 ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
247                 if (ret != LIBUSB_SUCCESS) {
248                         sr_err("Failed to claim interface: %s.",
249                                 libusb_error_name(ret));
250                         sr_usb_close(usb);
251                         return SR_ERR;
252                 }
253
254                 ret = drain_usb(usb, EP_REPLY);
255                 if (ret != SR_OK) {
256                         sr_usb_close(usb);
257                         return ret;
258                 }
259                 /* This delay appears to be necessary for reliable operation. */
260                 g_usleep(30 * 1000);
261
262                 devc->active_fpga_config = FPGA_NOCONF;
263                 devc->short_transfer_quirk = FALSE;
264                 devc->state = STATE_IDLE;
265
266                 ret = (*devc->model->apply_fpga_config)(sdi);
267
268                 if (ret == SR_OK)
269                         ret = (*devc->model->device_init_check)(sdi);
270                 if (ret == SR_OK)
271                         break;
272
273                 /* Rinse and repeat. */
274                 sr_usb_close(usb);
275         }
276
277         if (ret == SR_OK && devc->short_transfer_quirk)
278                 sr_warn("Short transfer quirk detected! "
279                         "Memory reads will be slow.");
280         return ret;
281 }
282
283 static int dev_close(struct sr_dev_inst *sdi)
284 {
285         struct dev_context *devc;
286         struct sr_usb_dev_inst *usb;
287         int ret;
288
289         devc = sdi->priv;
290         usb = sdi->conn;
291
292         if (devc->acquisition) {
293                 sr_err("Cannot close device during acquisition!");
294                 /* Request stop, leak handle, and prepare for the worst. */
295                 devc->cancel_requested = TRUE;
296                 return SR_ERR_BUG;
297         }
298
299         /* Download of the shutdown bitstream, if any. */
300         ret = (*devc->model->apply_fpga_config)(sdi);
301         if (ret != SR_OK)
302                 sr_warn("Unable to shut down device.");
303
304         libusb_release_interface(usb->devhdl, USB_INTERFACE);
305
306         sr_usb_close(usb);
307
308         return SR_OK;
309 }
310
311 /* Check whether the device options contain a specific key.
312  * Also match against get/set/list bits if specified.
313  */
314 static int has_devopt(const struct model_info *model, uint32_t key)
315 {
316         unsigned int i;
317
318         for (i = 0; i < model->num_devopts; i++) {
319                 if ((model->devopts[i] & (SR_CONF_MASK | key)) == key)
320                         return TRUE;
321         }
322
323         return FALSE;
324 }
325
326 static int config_get(uint32_t key, GVariant **data,
327         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
328 {
329         struct dev_context *devc;
330         unsigned int idx;
331
332         (void)cg;
333
334         if (!sdi)
335                 return SR_ERR_ARG;
336
337         devc = sdi->priv;
338
339         if (!has_devopt(devc->model, key | SR_CONF_GET))
340                 return SR_ERR_NA;
341
342         switch (key) {
343         case SR_CONF_SAMPLERATE:
344                 *data = g_variant_new_uint64(devc->samplerate);
345                 break;
346         case SR_CONF_LIMIT_MSEC:
347                 *data = g_variant_new_uint64(devc->limit_msec);
348                 break;
349         case SR_CONF_LIMIT_SAMPLES:
350                 *data = g_variant_new_uint64(devc->limit_samples);
351                 break;
352         case SR_CONF_RLE:
353                 *data = g_variant_new_boolean(devc->cfg_rle);
354                 break;
355         case SR_CONF_EXTERNAL_CLOCK:
356                 *data = g_variant_new_boolean(devc->cfg_clock_source
357                                                 == CLOCK_EXT_CLK);
358                 break;
359         case SR_CONF_CLOCK_EDGE:
360                 idx = devc->cfg_clock_edge;
361                 if (idx >= ARRAY_SIZE(signal_edge_names))
362                         return SR_ERR_BUG;
363                 *data = g_variant_new_string(signal_edge_names[idx]);
364                 break;
365         case SR_CONF_TRIGGER_SOURCE:
366                 idx = devc->cfg_trigger_source;
367                 if (idx >= ARRAY_SIZE(trigger_source_names))
368                         return SR_ERR_BUG;
369                 *data = g_variant_new_string(trigger_source_names[idx]);
370                 break;
371         case SR_CONF_TRIGGER_SLOPE:
372                 idx = devc->cfg_trigger_slope;
373                 if (idx >= ARRAY_SIZE(signal_edge_names))
374                         return SR_ERR_BUG;
375                 *data = g_variant_new_string(signal_edge_names[idx]);
376                 break;
377         default:
378                 /* Must not happen for a key listed in devopts. */
379                 return SR_ERR_BUG;
380         }
381
382         return SR_OK;
383 }
384
385 /* Helper for mapping a string-typed configuration value to an index
386  * within a table of possible values.
387  */
388 static int lookup_index(GVariant *value, const char *const *table, int len)
389 {
390         const char *entry;
391         int i;
392
393         entry = g_variant_get_string(value, NULL);
394         if (!entry)
395                 return -1;
396
397         /* Linear search is fine for very small tables. */
398         for (i = 0; i < len; i++) {
399                 if (strcmp(entry, table[i]) == 0)
400                         return i;
401         }
402
403         return -1;
404 }
405
406 static int config_set(uint32_t key, GVariant *data,
407         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
408 {
409         uint64_t value;
410         struct dev_context *devc;
411         int idx;
412
413         (void)cg;
414
415         if (!sdi)
416                 return SR_ERR_ARG;
417
418         devc = sdi->priv;
419
420         if (!has_devopt(devc->model, key | SR_CONF_SET))
421                 return SR_ERR_NA;
422
423         switch (key) {
424         case SR_CONF_SAMPLERATE:
425                 value = g_variant_get_uint64(data);
426                 if (value < devc->model->samplerates[devc->model->num_samplerates - 1]
427                                 || value > devc->model->samplerates[0])
428                         return SR_ERR_SAMPLERATE;
429                 devc->samplerate = value;
430                 break;
431         case SR_CONF_LIMIT_MSEC:
432                 value = g_variant_get_uint64(data);
433                 if (value > MAX_LIMIT_MSEC)
434                         return SR_ERR_ARG;
435                 devc->limit_msec = value;
436                 break;
437         case SR_CONF_LIMIT_SAMPLES:
438                 value = g_variant_get_uint64(data);
439                 if (value > MAX_LIMIT_SAMPLES)
440                         return SR_ERR_ARG;
441                 devc->limit_samples = value;
442                 break;
443         case SR_CONF_RLE:
444                 devc->cfg_rle = g_variant_get_boolean(data);
445                 break;
446         case SR_CONF_EXTERNAL_CLOCK:
447                 devc->cfg_clock_source = (g_variant_get_boolean(data))
448                         ? CLOCK_EXT_CLK : CLOCK_INTERNAL;
449                 break;
450         case SR_CONF_CLOCK_EDGE:
451                 idx = lookup_index(data, ARRAY_AND_SIZE(signal_edge_names));
452                 if (idx < 0)
453                         return SR_ERR_ARG;
454                 devc->cfg_clock_edge = idx;
455                 break;
456         case SR_CONF_TRIGGER_SOURCE:
457                 idx = lookup_index(data, ARRAY_AND_SIZE(trigger_source_names));
458                 if (idx < 0)
459                         return SR_ERR_ARG;
460                 devc->cfg_trigger_source = idx;
461                 break;
462         case SR_CONF_TRIGGER_SLOPE:
463                 idx = lookup_index(data, ARRAY_AND_SIZE(signal_edge_names));
464                 if (idx < 0)
465                         return SR_ERR_ARG;
466                 devc->cfg_trigger_slope = idx;
467                 break;
468         default:
469                 /* Must not happen for a key listed in devopts. */
470                 return SR_ERR_BUG;
471         }
472
473         return SR_OK;
474 }
475
476 static int config_channel_set(const struct sr_dev_inst *sdi,
477         struct sr_channel *ch, unsigned int changes)
478 {
479         uint64_t channel_bit;
480         struct dev_context *devc;
481
482         if (!sdi)
483                 return SR_ERR_ARG;
484
485         devc = sdi->priv;
486
487         if (ch->index < 0 || ch->index >= devc->model->num_channels) {
488                 sr_err("Channel index %d out of range.", ch->index);
489                 return SR_ERR_BUG;
490         }
491
492         if ((changes & SR_CHANNEL_SET_ENABLED) != 0) {
493                 channel_bit = UINT64_C(1) << ch->index;
494
495                 /* Enable or disable logic input for this channel. */
496                 if (ch->enabled)
497                         devc->channel_mask |= channel_bit;
498                 else
499                         devc->channel_mask &= ~channel_bit;
500         }
501
502         return SR_OK;
503 }
504
505 /* Derive trigger masks from the session's trigger configuration. */
506 static int prepare_trigger_masks(const struct sr_dev_inst *sdi)
507 {
508         uint64_t trigger_mask, trigger_values, trigger_edge_mask;
509         uint64_t level_bit, type_bit;
510         struct dev_context *devc;
511         struct sr_trigger *trigger;
512         struct sr_trigger_stage *stage;
513         struct sr_trigger_match *match;
514         const GSList *node;
515         int idx;
516         enum sr_trigger_matches trg;
517
518         devc = sdi->priv;
519
520         trigger = sr_session_trigger_get(sdi->session);
521         if (!trigger || !trigger->stages)
522                 return SR_OK;
523
524         if (trigger->stages->next) {
525                 sr_err("This device only supports 1 trigger stage.");
526                 return SR_ERR_ARG;
527         }
528         stage = trigger->stages->data;
529
530         trigger_mask = 0;
531         trigger_values = 0;
532         trigger_edge_mask = 0;
533
534         for (node = stage->matches; node; node = node->next) {
535                 match = node->data;
536
537                 if (!match->channel->enabled)
538                         continue; /* Ignore disabled channel. */
539
540                 idx = match->channel->index;
541                 trg = match->match;
542
543                 if (idx < 0 || idx >= devc->model->num_channels) {
544                         sr_err("Channel index %d out of range.", idx);
545                         return SR_ERR_BUG; /* Should not happen. */
546                 }
547                 if (trg != SR_TRIGGER_ZERO
548                                 && trg != SR_TRIGGER_ONE
549                                 && trg != SR_TRIGGER_RISING
550                                 && trg != SR_TRIGGER_FALLING) {
551                         sr_err("Unsupported trigger match for CH%d.", idx + 1);
552                         return SR_ERR_ARG;
553                 }
554                 level_bit = (trg == SR_TRIGGER_ONE
555                         || trg == SR_TRIGGER_RISING) ? 1 : 0;
556                 type_bit = (trg == SR_TRIGGER_RISING
557                         || trg == SR_TRIGGER_FALLING) ? 1 : 0;
558
559                 trigger_mask |= UINT64_C(1) << idx;
560                 trigger_values |= level_bit << idx;
561                 trigger_edge_mask |= type_bit << idx;
562         }
563         devc->trigger_mask = trigger_mask;
564         devc->trigger_values = trigger_values;
565         devc->trigger_edge_mask = trigger_edge_mask;
566
567         return SR_OK;
568 }
569
570 static int config_commit(const struct sr_dev_inst *sdi)
571 {
572         struct dev_context *devc;
573         int ret;
574
575         devc = sdi->priv;
576
577         if (devc->acquisition) {
578                 sr_err("Acquisition still in progress?");
579                 return SR_ERR;
580         }
581
582         ret = prepare_trigger_masks(sdi);
583         if (ret != SR_OK)
584                 return ret;
585
586         ret = (*devc->model->apply_fpga_config)(sdi);
587         if (ret != SR_OK) {
588                 sr_err("Failed to apply FPGA configuration.");
589                 return ret;
590         }
591
592         return SR_OK;
593 }
594
595 static int config_list(uint32_t key, GVariant **data,
596         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
597 {
598         struct dev_context *devc;
599
600         devc = (sdi) ? sdi->priv : NULL;
601
602         switch (key) {
603         case SR_CONF_SCAN_OPTIONS:
604         case SR_CONF_DEVICE_OPTIONS:
605                 return std_opts_config_list(key, data, sdi, cg,
606                         ARRAY_AND_SIZE(scanopts), ARRAY_AND_SIZE(drvopts),
607                         (devc) ? devc->model->devopts : NULL,
608                         (devc) ? devc->model->num_devopts : 0);
609         }
610
611         if (!has_devopt(devc->model, key | SR_CONF_LIST))
612                 return SR_ERR_NA;
613
614         switch (key) {
615         case SR_CONF_SAMPLERATE:
616                 *data = std_gvar_samplerates(devc->model->samplerates, devc->model->num_samplerates);
617                 break;
618         case SR_CONF_TRIGGER_MATCH:
619                 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
620                 break;
621         case SR_CONF_TRIGGER_SOURCE:
622                 *data = g_variant_new_strv(ARRAY_AND_SIZE(trigger_source_names));
623                 break;
624         case SR_CONF_TRIGGER_SLOPE:
625         case SR_CONF_CLOCK_EDGE:
626                 *data = g_variant_new_strv(ARRAY_AND_SIZE(signal_edge_names));
627                 break;
628         default:
629                 /* Must not happen for a key listed in devopts. */
630                 return SR_ERR_BUG;
631         }
632
633         return SR_OK;
634 }
635
636 /* Set up the device hardware to begin capturing samples as soon as the
637  * configured trigger conditions are met, or immediately if no triggers
638  * are configured.
639  */
640 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
641 {
642         return lwla_start_acquisition(sdi);
643 }
644
645 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
646 {
647         struct dev_context *devc;
648
649         devc = sdi->priv;
650
651         if (devc->state != STATE_IDLE && !devc->cancel_requested) {
652                 devc->cancel_requested = TRUE;
653                 sr_dbg("Requesting cancel.");
654         }
655
656         return SR_OK;
657 }
658
659 static struct sr_dev_driver sysclk_lwla_driver_info = {
660         .name = "sysclk-lwla",
661         .longname = "SysClk LWLA series",
662         .api_version = 1,
663         .init = std_init,
664         .cleanup = std_cleanup,
665         .scan = scan,
666         .dev_list = std_dev_list,
667         .dev_clear = std_dev_clear,
668         .config_get = config_get,
669         .config_set = config_set,
670         .config_channel_set = config_channel_set,
671         .config_commit = config_commit,
672         .config_list = config_list,
673         .dev_open = dev_open,
674         .dev_close = dev_close,
675         .dev_acquisition_start = dev_acquisition_start,
676         .dev_acquisition_stop = dev_acquisition_stop,
677         .context = NULL,
678 };
679 SR_REGISTER_DEV_DRIVER(sysclk_lwla_driver_info);