]> sigrok.org Git - libsigrok.git/blob - hardware/fx2lafw/protocol.c
fx2lafw: Organize driver into api.c / protocol.[ch].
[libsigrok.git] / 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 "protocol.h"
22
23 /* Protocol commands */
24 #define CMD_GET_FW_VERSION              0xb0
25 #define CMD_START                       0xb1
26 #define CMD_GET_REVID_VERSION           0xb2
27
28 #define CMD_START_FLAGS_WIDE_POS        5
29 #define CMD_START_FLAGS_CLK_SRC_POS     6
30
31 #define CMD_START_FLAGS_SAMPLE_8BIT     (0 << CMD_START_FLAGS_WIDE_POS)
32 #define CMD_START_FLAGS_SAMPLE_16BIT    (1 << CMD_START_FLAGS_WIDE_POS)
33
34 #define CMD_START_FLAGS_CLK_30MHZ       (0 << CMD_START_FLAGS_CLK_SRC_POS)
35 #define CMD_START_FLAGS_CLK_48MHZ       (1 << CMD_START_FLAGS_CLK_SRC_POS)
36
37 #pragma pack(push, 1)
38
39 struct version_info {
40         uint8_t major;
41         uint8_t minor;
42 };
43
44 struct cmd_start_acquisition {
45         uint8_t flags;
46         uint8_t sample_delay_h;
47         uint8_t sample_delay_l;
48 };
49
50 #pragma pack(pop)
51
52 static int command_get_fw_version(libusb_device_handle *devhdl,
53                                   struct version_info *vi)
54 {
55         int ret;
56
57         ret = libusb_control_transfer(devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
58                 LIBUSB_ENDPOINT_IN, CMD_GET_FW_VERSION, 0x0000, 0x0000,
59                 (unsigned char *)vi, sizeof(struct version_info), 100);
60
61         if (ret < 0) {
62                 sr_err("Unable to get version info: %s.",
63                        libusb_error_name(ret));
64                 return SR_ERR;
65         }
66
67         return SR_OK;
68 }
69
70 static int command_get_revid_version(libusb_device_handle *devhdl,
71                                      uint8_t *revid)
72 {
73         int ret;
74
75         ret = libusb_control_transfer(devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
76                 LIBUSB_ENDPOINT_IN, CMD_GET_REVID_VERSION, 0x0000, 0x0000,
77                 revid, 1, 100);
78
79         if (ret < 0) {
80                 sr_err("Unable to get REVID: %s.", libusb_error_name(ret));
81                 return SR_ERR;
82         }
83
84         return SR_OK;
85 }
86
87 SR_PRIV int fx2lafw_command_start_acquisition(libusb_device_handle *devhdl,
88                 uint64_t samplerate, gboolean samplewide)
89 {
90         struct cmd_start_acquisition cmd;
91         int delay = 0, ret;
92
93         /* Compute the sample rate. */
94         if (samplewide && 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         if ((SR_MHZ(48) % samplerate) == 0) {
101                 cmd.flags = CMD_START_FLAGS_CLK_48MHZ;
102                 delay = SR_MHZ(48) / samplerate - 1;
103                 if (delay > MAX_SAMPLE_DELAY)
104                         delay = 0;
105         }
106
107         if (delay == 0 && (SR_MHZ(30) % samplerate) == 0) {
108                 cmd.flags = CMD_START_FLAGS_CLK_30MHZ;
109                 delay = SR_MHZ(30) / samplerate - 1;
110         }
111
112         sr_info("GPIF delay = %d, clocksource = %sMHz.", delay,
113                 (cmd.flags & CMD_START_FLAGS_CLK_48MHZ) ? "48" : "30");
114
115         if (delay <= 0 || delay > MAX_SAMPLE_DELAY) {
116                 sr_err("Unable to sample at %" PRIu64 "Hz.", samplerate);
117                 return SR_ERR;
118         }
119
120         cmd.sample_delay_h = (delay >> 8) & 0xff;
121         cmd.sample_delay_l = delay & 0xff;
122
123         /* Select the sampling width. */
124         cmd.flags |= samplewide ? CMD_START_FLAGS_SAMPLE_16BIT :
125                 CMD_START_FLAGS_SAMPLE_8BIT;
126
127         /* Send the control message. */
128         ret = libusb_control_transfer(devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
129                         LIBUSB_ENDPOINT_OUT, CMD_START, 0x0000, 0x0000,
130                         (unsigned char *)&cmd, sizeof(cmd), 100);
131         if (ret < 0) {
132                 sr_err("Unable to send start command: %s.",
133                        libusb_error_name(ret));
134                 return SR_ERR;
135         }
136
137         return SR_OK;
138 }
139
140 /**
141  * Check the USB configuration to determine if this is an fx2lafw device.
142  *
143  * @return TRUE if the device's configuration profile match fx2lafw
144  *         configuration, FALSE otherwise.
145  */
146 SR_PRIV gboolean fx2lafw_check_conf_profile(libusb_device *dev)
147 {
148         struct libusb_device_descriptor des;
149         struct libusb_device_handle *hdl;
150         gboolean ret;
151         unsigned char strdesc[64];
152
153         hdl = NULL;
154         ret = FALSE;
155         while (!ret) {
156                 /* Assume the FW has not been loaded, unless proven wrong. */
157                 if (libusb_get_device_descriptor(dev, &des) != 0)
158                         break;
159
160                 if (libusb_open(dev, &hdl) != 0)
161                         break;
162
163                 if (libusb_get_string_descriptor_ascii(hdl,
164                     des.iManufacturer, strdesc, sizeof(strdesc)) < 0)
165                         break;
166                 if (strncmp((const char *)strdesc, "sigrok", 6))
167                         break;
168
169                 if (libusb_get_string_descriptor_ascii(hdl,
170                                 des.iProduct, strdesc, sizeof(strdesc)) < 0)
171                         break;
172                 if (strncmp((const char *)strdesc, "fx2lafw", 7))
173                         break;
174
175                 /* If we made it here, it must be an fx2lafw. */
176                 ret = TRUE;
177         }
178         if (hdl)
179                 libusb_close(hdl);
180
181         return ret;
182 }
183
184 SR_PRIV int fx2lafw_dev_open(struct sr_dev_inst *sdi, struct sr_dev_driver *di)
185 {
186         libusb_device **devlist;
187         struct sr_usb_dev_inst *usb;
188         struct libusb_device_descriptor des;
189         struct dev_context *devc;
190         struct drv_context *drvc;
191         struct version_info vi;
192         int ret, skip, i, device_count;
193         uint8_t revid;
194
195         drvc = di->priv;
196         devc = sdi->priv;
197         usb = sdi->conn;
198
199         if (sdi->status == SR_ST_ACTIVE)
200                 /* Device is already in use. */
201                 return SR_ERR;
202
203         skip = 0;
204         device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
205         if (device_count < 0) {
206                 sr_err("Failed to get device list: %s.",
207                        libusb_error_name(device_count));
208                 return SR_ERR;
209         }
210
211         for (i = 0; i < device_count; i++) {
212                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
213                         sr_err("Failed to get device descriptor: %s.",
214                                libusb_error_name(ret));
215                         continue;
216                 }
217
218                 if (des.idVendor != devc->profile->vid
219                     || des.idProduct != devc->profile->pid)
220                         continue;
221
222                 if (sdi->status == SR_ST_INITIALIZING) {
223                         if (skip != sdi->index) {
224                                 /* Skip devices of this type that aren't the one we want. */
225                                 skip += 1;
226                                 continue;
227                         }
228                 } else if (sdi->status == SR_ST_INACTIVE) {
229                         /*
230                          * This device is fully enumerated, so we need to find
231                          * this device by vendor, product, bus and address.
232                          */
233                         if (libusb_get_bus_number(devlist[i]) != usb->bus
234                                 || libusb_get_device_address(devlist[i]) != usb->address)
235                                 /* This is not the one. */
236                                 continue;
237                 }
238
239                 if (!(ret = libusb_open(devlist[i], &usb->devhdl))) {
240                         if (usb->address == 0xff)
241                                 /*
242                                  * First time we touch this device after FW
243                                  * upload, so we don't know the address yet.
244                                  */
245                                 usb->address = libusb_get_device_address(devlist[i]);
246                 } else {
247                         sr_err("Failed to open device: %s.",
248                                libusb_error_name(ret));
249                         break;
250                 }
251
252                 ret = command_get_fw_version(usb->devhdl, &vi);
253                 if (ret != SR_OK) {
254                         sr_err("Failed to get firmware version.");
255                         break;
256                 }
257
258                 ret = command_get_revid_version(usb->devhdl, &revid);
259                 if (ret != SR_OK) {
260                         sr_err("Failed to get REVID.");
261                         break;
262                 }
263
264                 /*
265                  * Changes in major version mean incompatible/API changes, so
266                  * bail out if we encounter an incompatible version.
267                  * Different minor versions are OK, they should be compatible.
268                  */
269                 if (vi.major != FX2LAFW_REQUIRED_VERSION_MAJOR) {
270                         sr_err("Expected firmware version %d.x, "
271                                "got %d.%d.", FX2LAFW_REQUIRED_VERSION_MAJOR,
272                                vi.major, vi.minor);
273                         break;
274                 }
275
276                 sdi->status = SR_ST_ACTIVE;
277                 sr_info("Opened device %d on %d.%d, "
278                         "interface %d, firmware %d.%d.",
279                         sdi->index, usb->bus, usb->address,
280                         USB_INTERFACE, vi.major, vi.minor);
281
282                 sr_info("Detected REVID=%d, it's a Cypress CY7C68013%s.",
283                         revid, (revid != 1) ? " (FX2)" : "A (FX2LP)");
284
285                 break;
286         }
287         libusb_free_device_list(devlist, 1);
288
289         if (sdi->status != SR_ST_ACTIVE)
290                 return SR_ERR;
291
292         return SR_OK;
293 }
294
295 SR_PRIV int fx2lafw_configure_probes(const struct sr_dev_inst *sdi)
296 {
297         struct dev_context *devc;
298         struct sr_probe *probe;
299         GSList *l;
300         int probe_bit, stage, i;
301         char *tc;
302
303         devc = sdi->priv;
304         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
305                 devc->trigger_mask[i] = 0;
306                 devc->trigger_value[i] = 0;
307         }
308
309         stage = -1;
310         for (l = sdi->probes; l; l = l->next) {
311                 probe = (struct sr_probe *)l->data;
312                 if (probe->enabled == FALSE)
313                         continue;
314
315                 if (probe->index > 7)
316                         devc->sample_wide = TRUE;
317
318                 probe_bit = 1 << (probe->index);
319                 if (!(probe->trigger))
320                         continue;
321
322                 stage = 0;
323                 for (tc = probe->trigger; *tc; tc++) {
324                         devc->trigger_mask[stage] |= probe_bit;
325                         if (*tc == '1')
326                                 devc->trigger_value[stage] |= probe_bit;
327                         stage++;
328                         if (stage > NUM_TRIGGER_STAGES)
329                                 return SR_ERR;
330                 }
331         }
332
333         if (stage == -1)
334                 /*
335                  * We didn't configure any triggers, make sure acquisition
336                  * doesn't wait for any.
337                  */
338                 devc->trigger_stage = TRIGGER_FIRED;
339         else
340                 devc->trigger_stage = 0;
341
342         return SR_OK;
343 }
344
345 SR_PRIV struct dev_context *fx2lafw_dev_new(void)
346 {
347         struct dev_context *devc;
348
349         if (!(devc = g_try_malloc(sizeof(struct dev_context)))) {
350                 sr_err("Device context malloc failed.");
351                 return NULL;
352         }
353
354         devc->profile = NULL;
355         devc->fw_updated = 0;
356         devc->cur_samplerate = 0;
357         devc->limit_samples = 0;
358         devc->sample_wide = 0;
359
360         return devc;
361 }
362
363 SR_PRIV void fx2lafw_abort_acquisition(struct dev_context *devc)
364 {
365         int i;
366
367         devc->num_samples = -1;
368
369         for (i = devc->num_transfers - 1; i >= 0; i--) {
370                 if (devc->transfers[i])
371                         libusb_cancel_transfer(devc->transfers[i]);
372         }
373 }
374
375 static void finish_acquisition(struct dev_context *devc)
376 {
377         struct sr_datafeed_packet packet;
378         int i;
379
380         /* Terminate session. */
381         packet.type = SR_DF_END;
382         sr_session_send(devc->cb_data, &packet);
383
384         /* Remove fds from polling. */
385         for (i = 0; devc->usbfd[i] != -1; i++)
386                 sr_source_remove(devc->usbfd[i]);
387         g_free(devc->usbfd);
388
389         devc->num_transfers = 0;
390         g_free(devc->transfers);
391 }
392
393 static void free_transfer(struct libusb_transfer *transfer)
394 {
395         struct dev_context *devc;
396         unsigned int i;
397
398         devc = transfer->user_data;
399
400         g_free(transfer->buffer);
401         transfer->buffer = NULL;
402         libusb_free_transfer(transfer);
403
404         for (i = 0; i < devc->num_transfers; i++) {
405                 if (devc->transfers[i] == transfer) {
406                         devc->transfers[i] = NULL;
407                         break;
408                 }
409         }
410
411         devc->submitted_transfers--;
412         if (devc->submitted_transfers == 0)
413                 finish_acquisition(devc);
414 }
415
416 static void resubmit_transfer(struct libusb_transfer *transfer)
417 {
418         int ret;
419
420         if ((ret = libusb_submit_transfer(transfer)) == LIBUSB_SUCCESS)
421                 return;
422
423         free_transfer(transfer);
424         /* TODO: Stop session? */
425
426         sr_err("%s: %s", __func__, libusb_error_name(ret));
427 }
428
429 SR_PRIV void fx2lafw_receive_transfer(struct libusb_transfer *transfer)
430 {
431         gboolean packet_has_error = FALSE;
432         struct sr_datafeed_packet packet;
433         struct sr_datafeed_logic logic;
434         struct dev_context *devc;
435         int trigger_offset, i, sample_width, cur_sample_count;
436         int trigger_offset_bytes;
437         uint8_t *cur_buf;
438
439         devc = transfer->user_data;
440
441         /*
442          * If acquisition has already ended, just free any queued up
443          * transfer that come in.
444          */
445         if (devc->num_samples == -1) {
446                 free_transfer(transfer);
447                 return;
448         }
449
450         sr_info("receive_transfer(): status %d received %d bytes.",
451                 transfer->status, transfer->actual_length);
452
453         /* Save incoming transfer before reusing the transfer struct. */
454         cur_buf = transfer->buffer;
455         sample_width = devc->sample_wide ? 2 : 1;
456         cur_sample_count = transfer->actual_length / sample_width;
457
458         switch (transfer->status) {
459         case LIBUSB_TRANSFER_NO_DEVICE:
460                 fx2lafw_abort_acquisition(devc);
461                 free_transfer(transfer);
462                 return;
463         case LIBUSB_TRANSFER_COMPLETED:
464         case LIBUSB_TRANSFER_TIMED_OUT: /* We may have received some data though. */
465                 break;
466         default:
467                 packet_has_error = TRUE;
468                 break;
469         }
470
471         if (transfer->actual_length == 0 || packet_has_error) {
472                 devc->empty_transfer_count++;
473                 if (devc->empty_transfer_count > MAX_EMPTY_TRANSFERS) {
474                         /*
475                          * The FX2 gave up. End the acquisition, the frontend
476                          * will work out that the samplecount is short.
477                          */
478                         fx2lafw_abort_acquisition(devc);
479                         free_transfer(transfer);
480                 } else {
481                         resubmit_transfer(transfer);
482                 }
483                 return;
484         } else {
485                 devc->empty_transfer_count = 0;
486         }
487
488         trigger_offset = 0;
489         if (devc->trigger_stage >= 0) {
490                 for (i = 0; i < cur_sample_count; i++) {
491
492                         const uint16_t cur_sample = devc->sample_wide ?
493                                 *((const uint16_t*)cur_buf + i) :
494                                 *((const uint8_t*)cur_buf + i);
495
496                         if ((cur_sample & devc->trigger_mask[devc->trigger_stage]) ==
497                                 devc->trigger_value[devc->trigger_stage]) {
498                                 /* Match on this trigger stage. */
499                                 devc->trigger_buffer[devc->trigger_stage] = cur_sample;
500                                 devc->trigger_stage++;
501
502                                 if (devc->trigger_stage == NUM_TRIGGER_STAGES ||
503                                         devc->trigger_mask[devc->trigger_stage] == 0) {
504                                         /* Match on all trigger stages, we're done. */
505                                         trigger_offset = i + 1;
506
507                                         /*
508                                          * TODO: Send pre-trigger buffer to session bus.
509                                          * Tell the frontend we hit the trigger here.
510                                          */
511                                         packet.type = SR_DF_TRIGGER;
512                                         packet.payload = NULL;
513                                         sr_session_send(devc->cb_data, &packet);
514
515                                         /*
516                                          * Send the samples that triggered it,
517                                          * since we're skipping past them.
518                                          */
519                                         packet.type = SR_DF_LOGIC;
520                                         packet.payload = &logic;
521                                         logic.unitsize = sizeof(*devc->trigger_buffer);
522                                         logic.length = devc->trigger_stage * logic.unitsize;
523                                         logic.data = devc->trigger_buffer;
524                                         sr_session_send(devc->cb_data, &packet);
525
526                                         devc->trigger_stage = TRIGGER_FIRED;
527                                         break;
528                                 }
529                         } else if (devc->trigger_stage > 0) {
530                                 /*
531                                  * We had a match before, but not in the next sample. However, we may
532                                  * have a match on this stage in the next bit -- trigger on 0001 will
533                                  * fail on seeing 00001, so we need to go back to stage 0 -- but at
534                                  * the next sample from the one that matched originally, which the
535                                  * counter increment at the end of the loop takes care of.
536                                  */
537                                 i -= devc->trigger_stage;
538                                 if (i < -1)
539                                         i = -1; /* Oops, went back past this buffer. */
540                                 /* Reset trigger stage. */
541                                 devc->trigger_stage = 0;
542                         }
543                 }
544         }
545
546         if (devc->trigger_stage == TRIGGER_FIRED) {
547                 /* Send the incoming transfer to the session bus. */
548                 trigger_offset_bytes = trigger_offset * sample_width;
549                 packet.type = SR_DF_LOGIC;
550                 packet.payload = &logic;
551                 logic.length = transfer->actual_length - trigger_offset_bytes;
552                 logic.unitsize = sample_width;
553                 logic.data = cur_buf + trigger_offset_bytes;
554                 sr_session_send(devc->cb_data, &packet);
555
556                 devc->num_samples += cur_sample_count;
557                 if (devc->limit_samples &&
558                         (unsigned int)devc->num_samples > devc->limit_samples) {
559                         fx2lafw_abort_acquisition(devc);
560                         free_transfer(transfer);
561                         return;
562                 }
563         } else {
564                 /*
565                  * TODO: Buffer pre-trigger data in capture
566                  * ratio-sized buffer.
567                  */
568         }
569
570         resubmit_transfer(transfer);
571 }
572
573 static unsigned int to_bytes_per_ms(unsigned int samplerate)
574 {
575         return samplerate / 1000;
576 }
577
578 SR_PRIV size_t fx2lafw_get_buffer_size(struct dev_context *devc)
579 {
580         size_t s;
581
582         /*
583          * The buffer should be large enough to hold 10ms of data and
584          * a multiple of 512.
585          */
586         s = 10 * to_bytes_per_ms(devc->cur_samplerate);
587         return (s + 511) & ~511;
588 }
589
590 SR_PRIV unsigned int fx2lafw_get_number_of_transfers(struct dev_context *devc)
591 {
592         unsigned int n;
593
594         /* Total buffer size should be able to hold about 500ms of data. */
595         n = (500 * to_bytes_per_ms(devc->cur_samplerate) /
596                 fx2lafw_get_buffer_size(devc));
597
598         if (n > NUM_SIMUL_TRANSFERS)
599                 return NUM_SIMUL_TRANSFERS;
600
601         return n;
602 }
603
604 SR_PRIV unsigned int fx2lafw_get_timeout(struct dev_context *devc)
605 {
606         size_t total_size;
607         unsigned int timeout;
608
609         total_size = fx2lafw_get_buffer_size(devc) *
610                         fx2lafw_get_number_of_transfers(devc);
611         timeout = total_size / to_bytes_per_ms(devc->cur_samplerate);
612         return timeout + timeout / 4; /* Leave a headroom of 25% percent. */
613 }