]> sigrok.org Git - libsigrok.git/blob - src/hardware/lecroy-logicstudio/protocol.c
output/csv: use intermediate time_t var, silence compiler warning
[libsigrok.git] / src / hardware / lecroy-logicstudio / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2015 Tilman Sauerbeck <tilman@code-monkey.de>
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 <string.h>
22 #include <assert.h>
23 #include "protocol.h"
24
25 #define EP_INTR (LIBUSB_ENDPOINT_IN | 1)
26 #define EP_BULK (LIBUSB_ENDPOINT_IN | 2)
27 #define EP_BITSTREAM (LIBUSB_ENDPOINT_OUT | 6)
28
29 #define CTRL_IN (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN)
30 #define CTRL_OUT (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT)
31
32 #define USB_COMMAND_READ_WRITE_REGS 0xb1
33 #define USB_COMMAND_WRITE_STATUS_REG 0xb2
34 #define USB_COMMAND_START_UPLOAD 0xb3
35 #define USB_COMMAND_VERIFY_UPLOAD 0xb4
36
37 #define USB_TIMEOUT_MS 100
38
39 /* Firmware for acquisition on 8 channels. */
40 #define FPGA_FIRMWARE_8 "lecroy-logicstudio16-8.bitstream"
41 /* Firmware for acquisition on 16 channels. */
42 #define FPGA_FIRMWARE_16 "lecroy-logicstudio16-16.bitstream"
43
44 #define FPGA_FIRMWARE_SIZE 464196
45 #define FPGA_FIRMWARE_CHUNK_SIZE 2048
46
47 #define NUM_TRIGGER_STAGES 2
48 #define TRIGGER_CFG_SIZE 45
49
50 #define ALIGN2_DOWN(n, p) ((((n) > (p)) ? ((n) - (p)) : (n)) & ~((p) - 1))
51
52 #define TRIGGER_OP_A 0x1000
53 #define TRIGGER_OP_B 0x2000
54 #define TRIGGER_OP_A_OR_B 0x3000
55 #define TRIGGER_OP_A_AND_B 0x4000
56 #define TRIGGER_OP_A_THEN_B 0x8000
57
58 #define REG_ACQUISITION_ID 0x00
59 #define REG_SAMPLERATE 0x02
60 #define REG_PRETRIG_LO 0x03
61 #define REG_PRETRIG_HI 0x04
62 #define REG_POSTTRIG_LO 0x05
63 #define REG_POSTTRIG_HI 0x06
64 #define REG_ARM_TRIGGER 0x07
65 #define REG_FETCH_SAMPLES 0x08
66 #define REG_UNK1_LO 0x09
67 #define REG_UNK1_HI 0x0a
68 #define REG_UNK2_LO 0x0b
69 #define REG_UNK2_HI 0x0c
70 #define REG_UNK3_LO 0x0d
71 #define REG_UNK3_HI 0x0e
72 #define REG_UNK4_LO 0x0f
73 #define REG_UNK4_HI 0x10
74 #define REG_UNK5_LO 0x11
75 #define REG_UNK5_HI 0x12
76 #define REG_UNK6_LO 0x13
77 #define REG_UNK6_HI 0x14
78 #define REG_UNK0_LO 0x15
79 #define REG_UNK0_HI 0x16
80 #define REG_TRIGGER_CFG 0x18
81 #define REG_TRIGGER_COMBINE_OP 0x1b
82 #define REG_SELECT_CHANNELS 0x21
83 #define REG_VOLTAGE_THRESH_EXTERNAL 0x22
84 #define REG_VOLTAGE_THRESH_LOWER_CHANNELS 0x23
85 #define REG_VOLTAGE_THRESH_UPPER_CHANNELS 0x24
86
87 struct samplerate_info {
88         /** The samplerate in Hz. */
89         uint64_t samplerate;
90
91         /**
92          * The offset to add to the sample offset for when the trigger fired.
93          *
94          * @note The value stored here only applies to 8 channel mode.
95          *       When acquiring 16 channels, subtract another 8 samples.
96          */
97         int8_t trigger_sample_offset;
98
99         uint8_t cfg;
100 };
101
102 struct trigger_config {
103         uint16_t rising_edges;
104         uint16_t falling_edges;
105         uint16_t any_edges;
106
107         uint16_t ones;
108         uint16_t zeroes;
109 };
110
111 /** A register and its value. */
112 struct regval {
113         uint8_t reg;
114         uint16_t val;
115 };
116
117 static void LIBUSB_CALL handle_fetch_samples_done(struct libusb_transfer *xfer);
118 static void LIBUSB_CALL recv_bulk_transfer(struct libusb_transfer *xfer);
119
120 static const struct samplerate_info samplerates[] = {
121         { SR_GHZ(1),  -24, 0x1f },
122         { SR_MHZ(500), -6, 0x00 },
123         { SR_MHZ(250), -4, 0x01 },
124         { SR_MHZ(100),  2, 0x03 },
125         { SR_MHZ(50),   4, 0x04 },
126         { SR_MHZ(25),   8, 0x05 },
127         { SR_MHZ(10),   4, 0x07 },
128         { SR_MHZ(5),    8, 0x08 },
129         { SR_KHZ(2500), 8, 0x09 },
130         { SR_KHZ(1000), 8, 0x0b },
131         { SR_KHZ(500),  8, 0x0c },
132         { SR_KHZ(250),  8, 0x0d },
133         { SR_KHZ(100),  8, 0x0f },
134         { SR_KHZ(50),   8, 0x10 },
135         { SR_KHZ(25),   8, 0x11 },
136         { SR_KHZ(10),   8, 0x13 },
137         { SR_KHZ(5),    8, 0x14 },
138         { SR_HZ(2500),  8, 0x15 },
139         { SR_HZ(1000),  8, 0x17 },
140 };
141
142 static int read_register(const struct sr_dev_inst *sdi,
143         uint8_t reg, uint16_t *value)
144 {
145         struct sr_usb_dev_inst *usb;
146         uint8_t data[2];
147         int r;
148
149         usb = sdi->conn;
150
151         r = libusb_control_transfer(usb->devhdl, CTRL_IN,
152                 USB_COMMAND_READ_WRITE_REGS, reg, 5444,
153                 data, sizeof(data), USB_TIMEOUT_MS);
154
155         if (r != sizeof(data)) {
156                 sr_err("CTRL_IN failed: %i.", r);
157                 return SR_ERR;
158         }
159
160         *value = RB16(data);
161
162         return SR_OK;
163 }
164
165 static int write_registers_sync(const struct sr_dev_inst *sdi,
166         unsigned int wValue, unsigned int wIndex,
167         const struct regval *regs, size_t num_regs)
168 {
169         struct sr_usb_dev_inst *usb;
170         uint8_t *buf;
171         size_t i, bufsiz;
172         int r;
173
174         usb = sdi->conn;
175
176         /* Try to avoid overflowing the stack. */
177         if (num_regs > 32)
178                 return SR_ERR;
179
180         bufsiz = num_regs * 3;
181         buf = alloca(bufsiz);
182
183         for (i = 0; i < num_regs; i++) {
184                 W8(&buf[i * 3 + 0], regs[i].reg);
185                 WB16(&buf[i * 3 + 1], regs[i].val);
186         }
187
188         r = libusb_control_transfer(usb->devhdl, CTRL_OUT,
189                         USB_COMMAND_READ_WRITE_REGS, wValue, wIndex,
190                         buf, bufsiz, USB_TIMEOUT_MS);
191
192         if (r != (int) bufsiz) {
193                 sr_err("write_registers_sync(%u/%u) failed.", wValue, wIndex);
194                 return SR_ERR;
195         }
196
197         return SR_OK;
198 }
199
200 static int write_registers_async(const struct sr_dev_inst *sdi,
201         unsigned int wValue, unsigned int wIndex,
202         const struct regval *regs, size_t num_regs,
203         libusb_transfer_cb_fn callback)
204 {
205         struct sr_usb_dev_inst *usb;
206         struct libusb_transfer *xfer;
207         uint8_t *buf, *xfer_buf;
208         size_t i;
209
210         usb = sdi->conn;
211
212         xfer = libusb_alloc_transfer(0);
213         xfer_buf = g_malloc(LIBUSB_CONTROL_SETUP_SIZE + (num_regs * 3));
214
215         libusb_fill_control_setup(xfer_buf, CTRL_OUT,
216                 USB_COMMAND_READ_WRITE_REGS, wValue, wIndex, num_regs * 3);
217
218         buf = xfer_buf + LIBUSB_CONTROL_SETUP_SIZE;
219
220         for (i = 0; i < num_regs; i++) {
221                 W8(&buf[i * 3 + 0], regs[i].reg);
222                 WB16(&buf[i * 3 + 1], regs[i].val);
223         }
224
225         libusb_fill_control_transfer(xfer, usb->devhdl,
226                 xfer_buf, callback, (void *) sdi, USB_TIMEOUT_MS);
227
228         if (libusb_submit_transfer(xfer) < 0) {
229                 g_free(xfer->buffer);
230                 xfer->buffer = NULL;
231                 libusb_free_transfer(xfer);
232                 return SR_ERR;
233         }
234
235         return SR_OK;
236 }
237
238 static void prep_regw(struct regval *regval, uint8_t reg, uint16_t val)
239 {
240         regval->reg = reg;
241         regval->val = val;
242 }
243
244 static void LIBUSB_CALL handle_fetch_samples_done(struct libusb_transfer *xfer)
245 {
246         const struct sr_dev_inst *sdi;
247         struct sr_usb_dev_inst *usb;
248         struct dev_context *devc;
249
250         sdi = xfer->user_data;
251         usb = sdi->conn;
252         devc = sdi->priv;
253
254         g_free(xfer->buffer);
255         xfer->buffer = NULL;
256
257         libusb_free_transfer(xfer);
258
259         libusb_fill_bulk_transfer(devc->bulk_xfer, usb->devhdl, EP_BULK,
260                 devc->fetched_samples, 17 << 10,
261                 recv_bulk_transfer, (void *)sdi, USB_TIMEOUT_MS);
262
263         libusb_submit_transfer(devc->bulk_xfer);
264 }
265
266 static void calc_unk0(uint32_t *a, uint32_t *b)
267 {
268         uint32_t t;
269
270         t = 20000 / 4;
271
272         if (a)
273                 *a = (t + 63) | 63;
274         if (b)
275                 *b = (t + 63) & ~63;
276 }
277
278 static int fetch_samples_async(const struct sr_dev_inst *sdi)
279 {
280         struct dev_context *devc;
281         struct regval cmd[12];
282         uint32_t unk1, unk2, unk3;
283         int i;
284
285         devc = sdi->priv;
286
287         unk1 = devc->earliest_sample % (devc->num_thousand_samples << 10);
288         unk1 = (unk1 * devc->num_enabled_channel_groups) / 8;
289
290         calc_unk0(&unk2, &unk3);
291
292         i = 0;
293
294         prep_regw(&cmd[i++], REG_UNK1_LO, (unk1 >>  0) & 0xffff);
295         prep_regw(&cmd[i++], REG_UNK1_HI, (unk1 >> 16) & 0xffff);
296
297         prep_regw(&cmd[i++], REG_FETCH_SAMPLES, devc->magic_fetch_samples);
298         prep_regw(&cmd[i++], REG_FETCH_SAMPLES, devc->magic_fetch_samples | 0x02);
299
300         prep_regw(&cmd[i++], REG_UNK1_LO, 0x0000);
301         prep_regw(&cmd[i++], REG_UNK1_HI, 0x0000);
302
303         prep_regw(&cmd[i++], REG_UNK2_LO, (unk2 >>  0) & 0xffff);
304         prep_regw(&cmd[i++], REG_UNK2_HI, (unk2 >> 16) & 0xffff);
305
306         prep_regw(&cmd[i++], REG_UNK3_LO, (unk3 >>  0) & 0xffff);
307         prep_regw(&cmd[i++], REG_UNK3_HI, (unk3 >> 16) & 0xffff);
308
309         devc->magic_fetch_samples = 0x01;
310         prep_regw(&cmd[i++], REG_FETCH_SAMPLES, devc->magic_fetch_samples + 0x01);
311         prep_regw(&cmd[i++], REG_FETCH_SAMPLES, devc->magic_fetch_samples | 0x02);
312
313         return write_registers_async(sdi, 0x12, 5444, ARRAY_AND_SIZE(cmd),
314                         handle_fetch_samples_done);
315 }
316
317 static int handle_intr_data(const struct sr_dev_inst *sdi, uint8_t *buffer)
318 {
319         struct dev_context *devc;
320         gboolean resubmit_intr_xfer;
321         uint64_t time_latest, time_trigger, sample_latest, sample_trigger;
322         uint32_t samplerate_divider;
323
324         resubmit_intr_xfer = TRUE;
325
326         if (!sdi)
327                 goto out;
328
329         devc = sdi->priv;
330
331         if (!devc->want_trigger)
332                 goto out;
333
334         /* Does this packet refer to our newly programmed trigger yet? */
335         if (RB16(&buffer[0x02]) != devc->acquisition_id)
336                 goto out;
337
338         switch (buffer[0x1f]) {
339         case 0x09:
340                 /* Storing pre-trigger samples. */
341                 break;
342         case 0x0a:
343                 /* Trigger armed? */
344                 break;
345         case 0x0b:
346                 /* Storing post-trigger samples. */
347                 break;
348         case 0x04:
349                 /* Acquisition complete. */
350                 devc->total_received_sample_bytes = 0;
351
352                 samplerate_divider = SR_GHZ(1) / devc->samplerate_info->samplerate;
353
354                 /*
355                  * These timestamps seem to be in units of eight nanoseconds.
356                  * The first one refers to the time when the latest sample
357                  * was written to the device's sample buffer, and the second
358                  * one refers to the time when the trigger fired.
359                  *
360                  * They are stored as 48 bit integers in the packet and we
361                  * shift it to the right by 16 to make up for that.
362                  */
363                 time_latest = RB64(&buffer[0x6]) >> 16;
364                 time_trigger = RB64(&buffer[0xc]) >> 16;
365
366                 /* Convert timestamps to sample offsets. */
367                 sample_latest = time_latest * 8;
368                 sample_latest /= samplerate_divider;
369
370                 sample_latest = ALIGN2_DOWN(sample_latest,
371                         8 / devc->num_enabled_channel_groups);
372
373                 devc->earliest_sample = sample_latest -
374                         (devc->num_thousand_samples * 1000);
375
376                 sample_trigger = time_trigger * 8;
377
378                 /* Fill the zero bits on the right. */
379                 sample_trigger |= RB16(&buffer[0x12]) & 7;
380
381                 sample_trigger += devc->samplerate_info->trigger_sample_offset;
382
383                 if (devc->num_enabled_channel_groups > 1)
384                         sample_trigger -= 8;
385
386                 sample_trigger -= 0x18;
387
388                 if (samplerate_divider > 1) {
389                         /* FIXME: Underflow. */
390                         sample_trigger -= samplerate_divider;
391                         sample_trigger /= samplerate_divider;
392                 }
393
394                 /*
395                  * Seems the hardware reports one sample too early,
396                  * so make up for that.
397                  */
398                 sample_trigger++;
399
400                 devc->trigger_sample = sample_trigger;
401
402                 fetch_samples_async(sdi);
403
404                 /*
405                  * Don't re-submit the interrupt transfer;
406                  * we need to get the samples instead.
407                  */
408                 resubmit_intr_xfer = FALSE;
409
410                 break;
411         default:
412                 break;
413         }
414
415 out:
416         return resubmit_intr_xfer;
417 }
418
419 static int upload_fpga_bitstream(const struct sr_dev_inst *sdi,
420         const char *firmware_name)
421 {
422         struct drv_context *drvc;
423         struct sr_usb_dev_inst *usb;
424         struct sr_resource firmware;
425         uint8_t firmware_chunk[FPGA_FIRMWARE_CHUNK_SIZE];
426         uint8_t upload_succeeded;
427         ssize_t chunk_size;
428         int i, r, ret, actual_length;
429
430         drvc = sdi->driver->context;
431         usb = sdi->conn;
432
433         ret = sr_resource_open(drvc->sr_ctx, &firmware,
434                         SR_RESOURCE_FIRMWARE, firmware_name);
435
436         if (ret != SR_OK)
437                 return ret;
438
439         ret = SR_ERR;
440
441         if (firmware.size != FPGA_FIRMWARE_SIZE) {
442                 sr_err("Invalid FPGA firmware file size: %" PRIu64 " bytes.",
443                         firmware.size);
444                 goto out;
445         }
446
447         /* Initiate upload. */
448         r = libusb_control_transfer(usb->devhdl, CTRL_OUT,
449                 USB_COMMAND_START_UPLOAD, 0x07, 5444,
450                 NULL, 0, USB_TIMEOUT_MS);
451
452         if (r != 0) {
453                 sr_err("Failed to initiate firmware upload: %s.",
454                                 libusb_error_name(ret));
455                 goto out;
456         }
457
458         for (;;) {
459                 chunk_size = sr_resource_read(drvc->sr_ctx, &firmware,
460                         firmware_chunk, sizeof(firmware_chunk));
461
462                 if (chunk_size < 0)
463                         goto out;
464
465                 if (chunk_size == 0)
466                         break;
467
468                 actual_length = chunk_size;
469
470                 r = libusb_bulk_transfer(usb->devhdl, EP_BITSTREAM,
471                         firmware_chunk, chunk_size, &actual_length, USB_TIMEOUT_MS);
472
473                 if (r != 0 || (ssize_t)actual_length != chunk_size) {
474                         sr_err("FPGA firmware upload failed.");
475                         goto out;
476                 }
477         }
478
479         /* Verify upload. */
480         for (i = 0; i < 4; i++) {
481                 g_usleep(250000);
482
483                 upload_succeeded = 0x00;
484
485                 r = libusb_control_transfer(usb->devhdl, CTRL_IN,
486                         USB_COMMAND_VERIFY_UPLOAD, 0x07, 5444,
487                         &upload_succeeded, sizeof(upload_succeeded),
488                         USB_TIMEOUT_MS);
489
490                 if (r != sizeof(upload_succeeded)) {
491                         sr_err("CTRL_IN failed: %i.", r);
492                         return SR_ERR;
493                 }
494
495                 if (upload_succeeded == 0x01) {
496                         ret = SR_OK;
497                         break;
498                 }
499         }
500
501 out:
502         sr_resource_close(drvc->sr_ctx, &firmware);
503
504         return ret;
505 }
506
507 static int upload_trigger(const struct sr_dev_inst *sdi,
508         uint8_t reg_values[TRIGGER_CFG_SIZE], uint8_t reg_offset)
509 {
510         struct regval regs[3 * 5];
511         uint16_t value;
512         int i, j, k;
513
514         for (i = 0; i < TRIGGER_CFG_SIZE; i += 5) {
515                 k = 0;
516
517                 for (j = 0; j < 5; j++) {
518                         value = ((reg_offset + i + j) << 8) | reg_values[i + j];
519
520                         prep_regw(&regs[k++], REG_TRIGGER_CFG, value);
521                         prep_regw(&regs[k++], REG_TRIGGER_CFG, value | 0x8000);
522                         prep_regw(&regs[k++], REG_TRIGGER_CFG, value);
523                 }
524
525                 if (write_registers_sync(sdi, 0x12, 5444, ARRAY_AND_SIZE(regs))) {
526                         sr_err("Failed to upload trigger config.");
527                         return SR_ERR;
528                 }
529         }
530
531         return SR_OK;
532 }
533
534 static int program_trigger(const struct sr_dev_inst *sdi,
535         struct trigger_config *stages, int num_filled_stages)
536 {
537         struct trigger_config *block;
538         struct regval combine_op;
539         uint8_t buf[TRIGGER_CFG_SIZE];
540         const uint8_t reg_offsets[] = { 0x00, 0x40 };
541         int i;
542
543         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
544                 block = &stages[i];
545
546                 memset(buf, 0, sizeof(buf));
547
548                 WL16(&buf[0x00], ~(block->rising_edges | block->falling_edges));
549                 WL16(&buf[0x05], block->rising_edges | block->falling_edges | block->any_edges);
550
551                 if (block->ones | block->zeroes)
552                         buf[0x09] = 0x10;
553
554                 WL16(&buf[0x0a], block->rising_edges);
555                 WL16(&buf[0x0f], block->ones | block->zeroes);
556                 buf[0x13] = 0x10;
557                 WL16(&buf[0x14], block->ones | 0x8000);
558
559                 if (block->ones == 0x01)
560                         WL16(&buf[0x19], block->ones << 1);
561                 else
562                         WL16(&buf[0x19], block->ones | 0x0001);
563
564                 /*
565                  * The final trigger has some special stuff.
566                  * Not sure of the meaning yet.
567                  */
568                 if (i == NUM_TRIGGER_STAGES - 1) {
569                         buf[0x09] = 0x10; /* This is most likely wrong. */
570
571                         buf[0x28] = 0xff;
572                         buf[0x29] = 0xff;
573                         buf[0x2a] = 0xff;
574                         buf[0x2b] = 0xff;
575                         buf[0x2c] = 0x80;
576                 }
577
578                 if (upload_trigger(sdi, buf, reg_offsets[i]) < 0)
579                         return SR_ERR;
580         }
581
582         /*
583          * If both available stages are used, AND them in the trigger
584          * criteria.
585          *
586          * Once sigrok learns to teach devices about the combination
587          * that the user wants, this seems to be the best default since
588          * edge triggers cannot be AND'ed otherwise
589          * (they are always OR'd within a single stage).
590          */
591         prep_regw(&combine_op, REG_TRIGGER_COMBINE_OP,
592                 num_filled_stages > 1 ? TRIGGER_OP_A_AND_B : TRIGGER_OP_A);
593
594         return write_registers_sync(sdi, 0x12, 5444, &combine_op, 1);
595 }
596
597 static gboolean transform_trigger(struct sr_trigger_stage *stage,
598         struct trigger_config *config)
599 {
600         GSList *l;
601         struct sr_trigger_match *match;
602         uint32_t channel_mask;
603         gboolean ret;
604
605         ret = FALSE;
606
607         for (l = stage->matches; l; l = l->next) {
608                 match = l->data;
609
610                 if (!match)
611                         continue;
612
613                 /* Ignore disabled channels. */
614                 if (!match->channel->enabled)
615                         continue;
616
617                 channel_mask = 1 << match->channel->index;
618
619                 switch (match->match) {
620                 case SR_TRIGGER_RISING:
621                         config->rising_edges |= channel_mask;
622                         break;
623                 case SR_TRIGGER_FALLING:
624                         config->falling_edges |= channel_mask;
625                         break;
626                 case SR_TRIGGER_EDGE:
627                         config->any_edges |= channel_mask;
628                         break;
629                 case SR_TRIGGER_ONE:
630                         config->ones |= channel_mask;
631                         break;
632                 case SR_TRIGGER_ZERO:
633                         config->zeroes |= channel_mask;
634                         break;
635                 }
636
637                 ret = TRUE;
638         }
639
640         return ret;
641 }
642
643 static int configure_trigger(const struct sr_dev_inst *sdi)
644 {
645         struct dev_context *devc;
646         struct sr_trigger *trigger;
647         struct sr_trigger_stage *stage;
648         struct sr_trigger_match *match;
649         struct trigger_config blocks[NUM_TRIGGER_STAGES];
650         gboolean stage_has_matches;
651         int num_filled_stages;
652         GSList *l, *ll;
653
654         devc = sdi->priv;
655
656         trigger = sr_session_trigger_get(sdi->session);
657
658         num_filled_stages = 0;
659
660         memset(blocks, 0, sizeof(blocks));
661
662         for (l = trigger ? trigger->stages : NULL; l; l = l->next) {
663                 stage = l->data;
664                 stage_has_matches = FALSE;
665
666                 /* Check if this stage has any interesting matches. */
667                 for (ll = stage->matches; ll; ll = ll->next) {
668                         match = ll->data;
669
670                         if (!match)
671                                 continue;
672
673                         /* Ignore disabled channels. */
674                         if (match->channel->enabled) {
675                                 stage_has_matches = TRUE;
676                                 break;
677                         }
678                 }
679
680                 if (stage_has_matches == FALSE)
681                         continue;
682
683                 if (num_filled_stages == NUM_TRIGGER_STAGES)
684                         return SR_ERR;
685
686                 if (transform_trigger(stage, &blocks[num_filled_stages]))
687                         num_filled_stages++;
688         }
689
690         devc->want_trigger = num_filled_stages > 0;
691
692         return program_trigger(sdi, blocks, num_filled_stages);
693 }
694
695 /** Update the bit mask of enabled channels. */
696 SR_PRIV void lls_update_channel_mask(const struct sr_dev_inst *sdi)
697 {
698         struct dev_context *devc;
699         struct sr_channel *channel;
700         GSList *l;
701
702         devc = sdi->priv;
703
704         devc->channel_mask = 0;
705
706         for (l = sdi->channels; l; l = l->next) {
707                 channel = l->data;
708                 if (channel->enabled)
709                         devc->channel_mask |= 1 << channel->index;
710         }
711 }
712
713 SR_PRIV int lls_set_samplerate(const struct sr_dev_inst *sdi,
714         uint64_t samplerate)
715 {
716         struct dev_context *devc;
717         size_t i;
718
719         devc = sdi->priv;
720
721         for (i = 0; i < ARRAY_SIZE(samplerates); i++) {
722                 if (samplerates[i].samplerate == samplerate) {
723                         devc->samplerate_info = &samplerates[i];
724                         return SR_OK;
725                 }
726         }
727
728         return SR_ERR;
729 }
730
731 SR_PRIV uint64_t lls_get_samplerate(const struct sr_dev_inst *sdi)
732 {
733         struct dev_context *devc;
734
735         devc = sdi->priv;
736
737         return devc->samplerate_info->samplerate;
738 }
739
740 static int read_0f12(const struct sr_dev_inst *sdi, uint64_t *value)
741 {
742         uint64_t u64;
743         uint16_t u16;
744         int r, reg;
745
746         u64 = 0;
747
748         /*
749          * Read the 64 bit register spread over 4 16 bit registers.
750          *
751          * Note that these don't seem to be the same registers we're writing
752          * when arming the trigger (ie REG_UNK4 and REG_UNK5).
753          * Seems there's multiple register spaces?
754          */
755         for (reg = 0x0f; reg <= 0x12; reg++) {
756                 r = read_register(sdi, reg, &u16);
757                 if (r != SR_OK)
758                         return r;
759                 u64 <<= 16;
760                 u64 |= u16;
761         }
762
763         *value = u64;
764
765         return SR_OK;
766 }
767
768 static int wait_for_dev_to_settle(const struct sr_dev_inst *sdi)
769 {
770         uint64_t old_value, new_value;
771         int r, i;
772
773         /* Get the initial value. */
774         r = read_0f12(sdi, &old_value);
775
776         if (r != SR_OK)
777                 return r;
778
779         /*
780          * We are looking for two consecutive reads that yield the
781          * same value. Try a couple of times.
782          */
783         for (i = 0; i < 100; i++) {
784                 r = read_0f12(sdi, &new_value);
785                 if (r != SR_OK)
786                         return r;
787
788                 if (old_value == new_value)
789                         return SR_OK;
790
791                 old_value = new_value;
792         }
793
794         return SR_ERR;
795 }
796
797 SR_PRIV int lls_setup_acquisition(const struct sr_dev_inst *sdi)
798 {
799         uint8_t status_reg_value[] = {
800                 0x1, 0x0, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc,
801                 0xd, 0xe, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6
802         };
803         struct regval threshold[3];
804         struct regval channels;
805         struct dev_context *devc;
806         struct sr_usb_dev_inst *usb;
807         gboolean lower_enabled, upper_enabled, upload_bitstream;
808         uint32_t num_thousand_samples, num_enabled_channel_groups;
809         int i, r;
810
811         usb = sdi->conn;
812         devc = sdi->priv;
813
814         prep_regw(&threshold[0], REG_VOLTAGE_THRESH_LOWER_CHANNELS, 0x00c3);
815         prep_regw(&threshold[1], REG_VOLTAGE_THRESH_UPPER_CHANNELS, 0x00c2);
816         prep_regw(&threshold[2], REG_VOLTAGE_THRESH_EXTERNAL, 0x003e);
817
818         lls_update_channel_mask(sdi);
819
820         lower_enabled = (devc->channel_mask & 0x00ff) != 0x00;
821         upper_enabled = (devc->channel_mask & 0xff00) != 0x00;
822
823         num_thousand_samples = 20;
824         num_enabled_channel_groups = 2;
825
826         if (lower_enabled != upper_enabled) {
827                 num_thousand_samples <<= 1;
828                 num_enabled_channel_groups >>= 1;
829         }
830
831         if (upper_enabled && !lower_enabled)
832                 prep_regw(&channels, REG_SELECT_CHANNELS, 0x01);
833         else
834                 prep_regw(&channels, REG_SELECT_CHANNELS, 0x00);
835
836         /*
837          * If the number of enabled channel groups changed since
838          * the last acquisition, we need to switch FPGA bitstreams.
839          * This works for the initial bitstream upload because
840          * devc->num_enabled_channel_groups is initialized to zero.
841          */
842         upload_bitstream =
843                 devc->num_enabled_channel_groups != num_enabled_channel_groups;
844
845         if (upload_bitstream) {
846                 if (lls_stop_acquisition(sdi)) {
847                         sr_err("Cannot stop acquisition for FPGA bitstream upload.");
848                         return SR_ERR;
849                 }
850
851                 for (i = 0; i < 3; i++)
852                         if (write_registers_sync(sdi, 0x0, 0x0, &threshold[i], 1))
853                                 return SR_ERR;
854
855                 if (num_enabled_channel_groups == 1)
856                         r = upload_fpga_bitstream(sdi, FPGA_FIRMWARE_8);
857                 else
858                         r = upload_fpga_bitstream(sdi, FPGA_FIRMWARE_16);
859
860                 if (r != SR_OK) {
861                         sr_err("Firmware not accepted by device.");
862                         return SR_ERR;
863                 }
864
865                 r = wait_for_dev_to_settle(sdi);
866
867                 if (r != SR_OK) {
868                         sr_err("Device did not settle in time.");
869                         return SR_ERR;
870                 }
871
872                 for (i = 0; i < 3; i++)
873                         if (write_registers_sync(sdi, 0x12, 5444, &threshold[i], 1))
874                                 return SR_ERR;
875
876                 devc->magic_arm_trigger = 0x00;
877                 devc->magic_fetch_samples = 0x00;
878         }
879
880         if (write_registers_sync(sdi, 0x12, 5444, &channels, 1))
881                 return SR_ERR;
882
883         if (configure_trigger(sdi) < 0)
884                 return SR_ERR;
885
886         if (write_registers_sync(sdi, 0x12, 5444, &threshold[0], 1))
887                 return SR_ERR;
888
889         if (write_registers_sync(sdi, 0x12, 5444, &threshold[1], 1))
890                 return SR_ERR;
891
892         if (upload_bitstream) {
893                 r = libusb_control_transfer(usb->devhdl, CTRL_OUT,
894                         USB_COMMAND_WRITE_STATUS_REG, 0x12, 5444,
895                         status_reg_value, sizeof(status_reg_value), USB_TIMEOUT_MS);
896
897                 if (r != sizeof(status_reg_value)) {
898                         sr_err("Failed to write status register: %s.",
899                                 libusb_error_name(r));
900                         return SR_ERR;
901                 }
902         }
903
904         devc->num_thousand_samples = num_thousand_samples;
905         devc->num_enabled_channel_groups = num_enabled_channel_groups;
906
907         return SR_OK;
908 }
909
910 static void LIBUSB_CALL recv_intr_transfer(struct libusb_transfer *xfer)
911 {
912         const struct sr_dev_inst *sdi;
913         struct drv_context *drvc;
914         struct dev_context *devc;
915
916         sdi = xfer->user_data;
917         drvc = sdi->driver->context;
918         devc = sdi->priv;
919
920         if (devc->abort_acquisition) {
921                 std_session_send_df_end(sdi);
922                 usb_source_remove(sdi->session, drvc->sr_ctx);
923                 return;
924         }
925
926         if (xfer->status == LIBUSB_TRANSFER_COMPLETED) {
927                 if (xfer->actual_length != INTR_BUF_SIZE)
928                         sr_err("Invalid size of interrupt transfer: %u.",
929                                 xfer->actual_length);
930                 else if (handle_intr_data(sdi, xfer->buffer)) {
931                         if (libusb_submit_transfer(xfer) < 0)
932                                 sr_err("Failed to submit interrupt transfer.");
933                 }
934         }
935 }
936
937 static void send_samples(const struct sr_dev_inst *sdi,
938         uint8_t *samples, uint32_t length)
939 {
940         struct dev_context *devc;
941         struct sr_datafeed_packet packet;
942         struct sr_datafeed_logic logic;
943         gboolean lower_enabled, upper_enabled;
944         uint32_t shift, i;
945
946         devc = sdi->priv;
947
948         lower_enabled = (devc->channel_mask & 0x00ff) != 0x00;
949         upper_enabled = (devc->channel_mask & 0xff00) != 0x00;
950
951         logic.unitsize = 2;
952
953         packet.type = SR_DF_LOGIC;
954         packet.payload = &logic;
955
956         if (lower_enabled && upper_enabled) {
957                 logic.length = length;
958                 logic.data = samples;
959
960                 sr_session_send(sdi, &packet);
961         } else {
962                 /* Which channel group is enabled? */
963                 shift = (lower_enabled) ? 0 : 8;
964
965                 while (length >= (CONV_8TO16_BUF_SIZE / 2)) {
966                         for (i = 0; i < (CONV_8TO16_BUF_SIZE / 2); i++) {
967                                 devc->conv8to16[i] = samples[i];
968                                 devc->conv8to16[i] <<= shift;
969                         }
970
971                         logic.length = CONV_8TO16_BUF_SIZE;
972                         logic.data = devc->conv8to16;
973
974                         sr_session_send(sdi, &packet);
975
976                         samples += CONV_8TO16_BUF_SIZE / 2;
977                         length -= CONV_8TO16_BUF_SIZE / 2;
978                 }
979
980                 /* Handle the remaining samples. */
981                 for (i = 0; i < length; i++) {
982                         devc->conv8to16[i] = samples[i];
983                         devc->conv8to16[i] <<= shift;
984                 }
985
986                 logic.length = length * 2;
987                 logic.data = devc->conv8to16;
988
989                 sr_session_send(sdi, &packet);
990         }
991 }
992
993 static uint16_t sample_to_byte_offset(struct dev_context *devc, uint64_t o)
994 {
995         o %= devc->num_thousand_samples << 10;
996
997         /* We have 8 bit per channel group, so this gets us a byte offset. */
998         return o * devc->num_enabled_channel_groups;
999 }
1000
1001 static void LIBUSB_CALL recv_bulk_transfer(struct libusb_transfer *xfer)
1002 {
1003         const struct sr_dev_inst *sdi;
1004         struct dev_context *devc;
1005         struct drv_context *drvc;
1006         struct sr_datafeed_packet packet;
1007         uint32_t bytes_left, length;
1008         uint16_t read_offset, trigger_offset;
1009
1010         sdi = xfer->user_data;
1011
1012         if (!sdi)
1013                 return;
1014
1015         drvc = sdi->driver->context;
1016         devc = sdi->priv;
1017
1018         devc->total_received_sample_bytes += xfer->actual_length;
1019
1020         if (devc->total_received_sample_bytes < SAMPLE_BUF_SIZE) {
1021                 xfer->buffer = devc->fetched_samples
1022                         + devc->total_received_sample_bytes;
1023
1024                 xfer->length = MIN(16 << 10,
1025                         SAMPLE_BUF_SIZE - devc->total_received_sample_bytes);
1026
1027                 libusb_submit_transfer(xfer);
1028                 return;
1029         }
1030
1031         usb_source_remove(sdi->session, drvc->sr_ctx);
1032
1033         read_offset = sample_to_byte_offset(devc, devc->earliest_sample);
1034         trigger_offset = sample_to_byte_offset(devc, devc->trigger_sample);
1035
1036         /*
1037          * The last few bytes seem to contain garbage data,
1038          * so ignore them.
1039          */
1040         bytes_left = (SAMPLE_BUF_SIZE >> 10) * 1000;
1041
1042         sr_spew("Start reading at offset 0x%04hx.", read_offset);
1043         sr_spew("Trigger offset 0x%04hx.", trigger_offset);
1044
1045         if (trigger_offset < read_offset) {
1046                 length = MIN(bytes_left, SAMPLE_BUF_SIZE - read_offset);
1047
1048                 sr_spew("Sending %u pre-trigger bytes starting at 0x%04hx.",
1049                         length, read_offset);
1050
1051                 send_samples(sdi, &devc->fetched_samples[read_offset], length);
1052
1053                 bytes_left -= length;
1054                 read_offset = 0;
1055         }
1056
1057         {
1058                 length = MIN(bytes_left, (uint32_t)(trigger_offset - read_offset));
1059
1060                 sr_spew("Sending %u pre-trigger bytes starting at 0x%04hx.",
1061                         length, read_offset);
1062
1063                 send_samples(sdi, &devc->fetched_samples[read_offset], length);
1064
1065                 bytes_left -= length;
1066
1067                 read_offset += length;
1068                 read_offset %= SAMPLE_BUF_SIZE;
1069         }
1070
1071         /* Here comes the trigger. */
1072         packet.type = SR_DF_TRIGGER;
1073         packet.payload = NULL;
1074
1075         sr_session_send(sdi, &packet);
1076
1077         /* Send post-trigger samples. */
1078         while (bytes_left > 0) {
1079                 length = MIN(bytes_left, SAMPLE_BUF_SIZE - read_offset);
1080
1081                 sr_spew("Sending %u post-trigger bytes starting at 0x%04hx.",
1082                         length, read_offset);
1083
1084                 send_samples(sdi, &devc->fetched_samples[read_offset], length);
1085
1086                 bytes_left -= length;
1087
1088                 read_offset += length;
1089                 read_offset %= SAMPLE_BUF_SIZE;
1090         }
1091
1092         std_session_send_df_end(sdi);
1093 }
1094
1095 static uint32_t transform_sample_count(struct dev_context *devc,
1096         uint32_t samples)
1097 {
1098         uint32_t d = 8 / devc->num_enabled_channel_groups;
1099
1100         return (samples + 0x1c + d + d - 1) / d;
1101 }
1102
1103 SR_PRIV int lls_start_acquisition(const struct sr_dev_inst *sdi)
1104 {
1105         struct sr_usb_dev_inst *usb;
1106         struct dev_context *devc;
1107         struct regval cmd[17];
1108         uint32_t unk0, total_samples, pre_trigger_samples, post_trigger_samples;
1109         uint32_t pre_trigger_tr, post_trigger_tr;
1110         int i;
1111
1112         usb = sdi->conn;
1113         devc = sdi->priv;
1114
1115         devc->abort_acquisition = FALSE;
1116
1117         libusb_fill_interrupt_transfer(devc->intr_xfer, usb->devhdl, EP_INTR,
1118                 devc->intr_buf, INTR_BUF_SIZE,
1119                 recv_intr_transfer, (void *) sdi, USB_TIMEOUT_MS);
1120
1121         libusb_submit_transfer(devc->intr_xfer);
1122
1123         if (devc->want_trigger == FALSE)
1124                 return SR_OK;
1125
1126         calc_unk0(&unk0, NULL);
1127
1128         total_samples = devc->num_thousand_samples * 1000;
1129
1130         pre_trigger_samples = (total_samples * devc->capture_ratio) / 100;
1131         post_trigger_samples = total_samples - pre_trigger_samples;
1132
1133         pre_trigger_tr = transform_sample_count(devc, pre_trigger_samples);
1134         post_trigger_tr = transform_sample_count(devc, post_trigger_samples);
1135
1136         i = 0;
1137
1138         prep_regw(&cmd[i++], REG_ARM_TRIGGER, devc->magic_arm_trigger);
1139         prep_regw(&cmd[i++], REG_ARM_TRIGGER, devc->magic_arm_trigger | 0x02);
1140
1141         prep_regw(&cmd[i++], REG_UNK6_LO, 0x0000);
1142         prep_regw(&cmd[i++], REG_UNK6_HI, 0x0000);
1143
1144         prep_regw(&cmd[i++], REG_UNK0_LO, (unk0 >>  0) & 0xffff);
1145         prep_regw(&cmd[i++], REG_UNK0_HI, (unk0 >> 16) & 0xffff);
1146
1147         prep_regw(&cmd[i++], REG_UNK4_LO, 0x0000);
1148         prep_regw(&cmd[i++], REG_UNK4_HI, 0x0000);
1149
1150         prep_regw(&cmd[i++], REG_UNK5_LO, 0x0000);
1151         prep_regw(&cmd[i++], REG_UNK5_HI, 0x0000);
1152
1153         prep_regw(&cmd[i++], REG_ACQUISITION_ID, ++devc->acquisition_id);
1154         prep_regw(&cmd[i++], REG_SAMPLERATE, devc->samplerate_info->cfg);
1155
1156         prep_regw(&cmd[i++], REG_PRETRIG_LO, (pre_trigger_tr >>  0) & 0xffff);
1157         prep_regw(&cmd[i++], REG_PRETRIG_HI, (pre_trigger_tr >> 16) & 0xffff);
1158
1159         prep_regw(&cmd[i++], REG_POSTTRIG_LO, (post_trigger_tr >>  0) & 0xffff);
1160         prep_regw(&cmd[i++], REG_POSTTRIG_HI, (post_trigger_tr >> 16) & 0xffff);
1161
1162         devc->magic_arm_trigger = 0x0c;
1163         prep_regw(&cmd[i++], REG_ARM_TRIGGER, devc->magic_arm_trigger | 0x01);
1164
1165         return write_registers_sync(sdi, 0x12, 5444, ARRAY_AND_SIZE(cmd));
1166 }
1167
1168 SR_PRIV int lls_stop_acquisition(const struct sr_dev_inst *sdi)
1169 {
1170         struct dev_context *devc;
1171         struct regval cmd[2];
1172         int i;
1173
1174         devc = sdi->priv;
1175
1176         devc->abort_acquisition = TRUE;
1177
1178         i = 0;
1179
1180         prep_regw(&cmd[i++], REG_ARM_TRIGGER, devc->magic_arm_trigger);
1181         prep_regw(&cmd[i++], REG_ARM_TRIGGER, devc->magic_arm_trigger | 0x02);
1182
1183         assert(i == ARRAY_SIZE(cmd));
1184
1185         return write_registers_sync(sdi, 0x12, 5444, ARRAY_AND_SIZE(cmd));
1186 }