]> sigrok.org Git - libsigrok.git/blob - hardware/fx2lafw/protocol.c
Replace 'probe' with 'channel' in most places.
[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_channels(const struct sr_dev_inst *sdi)
296 {
297         struct dev_context *devc;
298         struct sr_channel *ch;
299         GSList *l;
300         int channel_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->channels; l; l = l->next) {
311                 ch = (struct sr_channel *)l->data;
312                 if (ch->enabled == FALSE)
313                         continue;
314
315                 if (ch->index > 7)
316                         devc->sample_wide = TRUE;
317
318                 channel_bit = 1 << (ch->index);
319                 if (!(ch->trigger))
320                         continue;
321
322                 stage = 0;
323                 for (tc = ch->trigger; *tc; tc++) {
324                         devc->trigger_mask[stage] |= channel_bit;
325                         if (*tc == '1')
326                                 devc->trigger_value[stage] |= channel_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 = FALSE;
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
379         /* Terminate session. */
380         packet.type = SR_DF_END;
381         sr_session_send(devc->cb_data, &packet);
382
383         /* Remove fds from polling. */
384         usb_source_remove(devc->ctx);
385
386         devc->num_transfers = 0;
387         g_free(devc->transfers);
388 }
389
390 static void free_transfer(struct libusb_transfer *transfer)
391 {
392         struct dev_context *devc;
393         unsigned int i;
394
395         devc = transfer->user_data;
396
397         g_free(transfer->buffer);
398         transfer->buffer = NULL;
399         libusb_free_transfer(transfer);
400
401         for (i = 0; i < devc->num_transfers; i++) {
402                 if (devc->transfers[i] == transfer) {
403                         devc->transfers[i] = NULL;
404                         break;
405                 }
406         }
407
408         devc->submitted_transfers--;
409         if (devc->submitted_transfers == 0)
410                 finish_acquisition(devc);
411 }
412
413 static void resubmit_transfer(struct libusb_transfer *transfer)
414 {
415         int ret;
416
417         if ((ret = libusb_submit_transfer(transfer)) == LIBUSB_SUCCESS)
418                 return;
419
420         free_transfer(transfer);
421         /* TODO: Stop session? */
422
423         sr_err("%s: %s", __func__, libusb_error_name(ret));
424 }
425
426 SR_PRIV void fx2lafw_receive_transfer(struct libusb_transfer *transfer)
427 {
428         gboolean packet_has_error = FALSE;
429         struct sr_datafeed_packet packet;
430         struct sr_datafeed_logic logic;
431         struct dev_context *devc;
432         int trigger_offset, i, sample_width, cur_sample_count;
433         int trigger_offset_bytes;
434         uint8_t *cur_buf;
435         uint16_t cur_sample;
436
437         devc = transfer->user_data;
438
439         /*
440          * If acquisition has already ended, just free any queued up
441          * transfer that come in.
442          */
443         if (devc->num_samples == -1) {
444                 free_transfer(transfer);
445                 return;
446         }
447
448         sr_info("receive_transfer(): status %d received %d bytes.",
449                 transfer->status, transfer->actual_length);
450
451         /* Save incoming transfer before reusing the transfer struct. */
452         cur_buf = transfer->buffer;
453         sample_width = devc->sample_wide ? 2 : 1;
454         cur_sample_count = transfer->actual_length / sample_width;
455
456         switch (transfer->status) {
457         case LIBUSB_TRANSFER_NO_DEVICE:
458                 fx2lafw_abort_acquisition(devc);
459                 free_transfer(transfer);
460                 return;
461         case LIBUSB_TRANSFER_COMPLETED:
462         case LIBUSB_TRANSFER_TIMED_OUT: /* We may have received some data though. */
463                 break;
464         default:
465                 packet_has_error = TRUE;
466                 break;
467         }
468
469         if (transfer->actual_length == 0 || packet_has_error) {
470                 devc->empty_transfer_count++;
471                 if (devc->empty_transfer_count > MAX_EMPTY_TRANSFERS) {
472                         /*
473                          * The FX2 gave up. End the acquisition, the frontend
474                          * will work out that the samplecount is short.
475                          */
476                         fx2lafw_abort_acquisition(devc);
477                         free_transfer(transfer);
478                 } else {
479                         resubmit_transfer(transfer);
480                 }
481                 return;
482         } else {
483                 devc->empty_transfer_count = 0;
484         }
485
486         trigger_offset = 0;
487         if (devc->trigger_stage >= 0) {
488                 for (i = 0; i < cur_sample_count; i++) {
489
490                         cur_sample = devc->sample_wide ?
491                                 *((uint16_t *)cur_buf + i) :
492                                 *((uint8_t *)cur_buf + i);
493
494                         if ((cur_sample & devc->trigger_mask[devc->trigger_stage]) ==
495                                 devc->trigger_value[devc->trigger_stage]) {
496                                 /* Match on this trigger stage. */
497                                 devc->trigger_buffer[devc->trigger_stage] = cur_sample;
498                                 devc->trigger_stage++;
499
500                                 if (devc->trigger_stage == NUM_TRIGGER_STAGES ||
501                                         devc->trigger_mask[devc->trigger_stage] == 0) {
502                                         /* Match on all trigger stages, we're done. */
503                                         trigger_offset = i + 1;
504
505                                         /*
506                                          * TODO: Send pre-trigger buffer to session bus.
507                                          * Tell the frontend we hit the trigger here.
508                                          */
509                                         packet.type = SR_DF_TRIGGER;
510                                         packet.payload = NULL;
511                                         sr_session_send(devc->cb_data, &packet);
512
513                                         /*
514                                          * Send the samples that triggered it,
515                                          * since we're skipping past them.
516                                          */
517                                         packet.type = SR_DF_LOGIC;
518                                         packet.payload = &logic;
519                                         logic.unitsize = sample_width;
520                                         logic.length = devc->trigger_stage * logic.unitsize;
521                                         logic.data = devc->trigger_buffer;
522                                         sr_session_send(devc->cb_data, &packet);
523
524                                         devc->trigger_stage = TRIGGER_FIRED;
525                                         break;
526                                 }
527                         } else if (devc->trigger_stage > 0) {
528                                 /*
529                                  * We had a match before, but not in the next sample. However, we may
530                                  * have a match on this stage in the next bit -- trigger on 0001 will
531                                  * fail on seeing 00001, so we need to go back to stage 0 -- but at
532                                  * the next sample from the one that matched originally, which the
533                                  * counter increment at the end of the loop takes care of.
534                                  */
535                                 i -= devc->trigger_stage;
536                                 if (i < -1)
537                                         i = -1; /* Oops, went back past this buffer. */
538                                 /* Reset trigger stage. */
539                                 devc->trigger_stage = 0;
540                         }
541                 }
542         }
543
544         if (devc->trigger_stage == TRIGGER_FIRED) {
545                 /* Send the incoming transfer to the session bus. */
546                 trigger_offset_bytes = trigger_offset * sample_width;
547                 packet.type = SR_DF_LOGIC;
548                 packet.payload = &logic;
549                 logic.length = transfer->actual_length - trigger_offset_bytes;
550                 logic.unitsize = sample_width;
551                 logic.data = cur_buf + trigger_offset_bytes;
552                 sr_session_send(devc->cb_data, &packet);
553
554                 devc->num_samples += cur_sample_count;
555                 if (devc->limit_samples &&
556                         (unsigned int)devc->num_samples > devc->limit_samples) {
557                         fx2lafw_abort_acquisition(devc);
558                         free_transfer(transfer);
559                         return;
560                 }
561         } else {
562                 /*
563                  * TODO: Buffer pre-trigger data in capture
564                  * ratio-sized buffer.
565                  */
566         }
567
568         resubmit_transfer(transfer);
569 }
570
571 static unsigned int to_bytes_per_ms(unsigned int samplerate)
572 {
573         return samplerate / 1000;
574 }
575
576 SR_PRIV size_t fx2lafw_get_buffer_size(struct dev_context *devc)
577 {
578         size_t s;
579
580         /*
581          * The buffer should be large enough to hold 10ms of data and
582          * a multiple of 512.
583          */
584         s = 10 * to_bytes_per_ms(devc->cur_samplerate);
585         return (s + 511) & ~511;
586 }
587
588 SR_PRIV unsigned int fx2lafw_get_number_of_transfers(struct dev_context *devc)
589 {
590         unsigned int n;
591
592         /* Total buffer size should be able to hold about 500ms of data. */
593         n = (500 * to_bytes_per_ms(devc->cur_samplerate) /
594                 fx2lafw_get_buffer_size(devc));
595
596         if (n > NUM_SIMUL_TRANSFERS)
597                 return NUM_SIMUL_TRANSFERS;
598
599         return n;
600 }
601
602 SR_PRIV unsigned int fx2lafw_get_timeout(struct dev_context *devc)
603 {
604         size_t total_size;
605         unsigned int timeout;
606
607         total_size = fx2lafw_get_buffer_size(devc) *
608                         fx2lafw_get_number_of_transfers(devc);
609         timeout = total_size / to_bytes_per_ms(devc->cur_samplerate);
610         return timeout + timeout / 4; /* Leave a headroom of 25% percent. */
611 }