]> sigrok.org Git - libsigrok.git/blob - hardware/sysclk-lwla/protocol.c
sysclk-lwla: Avoid warning due to bogus range check.
[libsigrok.git] / hardware / sysclk-lwla / protocol.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 "protocol.h"
21 #include <string.h>
22
23 /* Bit mask covering all 34 channels. */
24 #define ALL_CHANNELS_MASK (((uint64_t)1 << NUM_PROBES) - 1)
25
26 /* Bit mask for the RLE repeat-count-follows flag. */
27 #define RLE_FLAG_LEN_FOLLOWS ((uint64_t)1 << 35)
28
29 /* Start address of capture status memory area to read. */
30 #define CAP_STAT_ADDR 5
31
32 /* Number of 64-bit words read from the capture status memory. */
33 #define CAP_STAT_LEN 5
34
35 /* The bitstream filenames are indexed by the clock source enumeration.
36  */
37 static const char *const bitstream_map[] = {
38         FIRMWARE_DIR "/sysclk-lwla1034-off.bitstream",
39         FIRMWARE_DIR "/sysclk-lwla1034-int.bitstream",
40         FIRMWARE_DIR "/sysclk-lwla1034-extpos.bitstream",
41         FIRMWARE_DIR "/sysclk-lwla1034-extneg.bitstream",
42 };
43
44 /* Submit an already filled-in USB transfer.
45  */
46 static int submit_transfer(struct dev_context *devc,
47                            struct libusb_transfer *xfer)
48 {
49         int ret;
50
51         ret = libusb_submit_transfer(xfer);
52
53         if (ret != 0) {
54                 sr_err("Submit transfer failed: %s.", libusb_error_name(ret));
55                 devc->transfer_error = TRUE;
56                 return SR_ERR;
57         }
58
59         return SR_OK;
60 }
61
62 /* Set up the LWLA in preparation for an acquisition session.
63  */
64 static int capture_setup(const struct sr_dev_inst *sdi)
65 {
66         struct dev_context *devc;
67         uint64_t divider_count;
68         uint64_t memory_limit;
69         uint16_t command[3 + 10*4];
70
71         devc = sdi->priv;
72
73         command[0] = LWLA_WORD(CMD_CAP_SETUP);
74         command[1] = LWLA_WORD(0); /* address */
75         command[2] = LWLA_WORD(10); /* length */
76
77         command[3] = LWLA_WORD_0(devc->channel_mask);
78         command[4] = LWLA_WORD_1(devc->channel_mask);
79         command[5] = LWLA_WORD_2(devc->channel_mask);
80         command[6] = LWLA_WORD_3(devc->channel_mask);
81
82         /* Set the clock divide counter maximum for samplerates of up to
83          * 100 MHz. At the highest samplerate of 125 MHz the clock divider
84          * is bypassed.
85          */
86         if (devc->samplerate > 0 && devc->samplerate < SR_MHZ(100))
87                 divider_count = SR_MHZ(100) / devc->samplerate - 1;
88         else
89                 divider_count = 0;
90
91         command[7]  = LWLA_WORD_0(divider_count);
92         command[8]  = LWLA_WORD_1(divider_count);
93         command[9]  = LWLA_WORD_2(divider_count);
94         command[10] = LWLA_WORD_3(divider_count);
95
96         command[11] = LWLA_WORD_0(devc->trigger_values);
97         command[12] = LWLA_WORD_1(devc->trigger_values);
98         command[13] = LWLA_WORD_2(devc->trigger_values);
99         command[14] = LWLA_WORD_3(devc->trigger_values);
100
101         command[15] = LWLA_WORD_0(devc->trigger_edge_mask);
102         command[16] = LWLA_WORD_1(devc->trigger_edge_mask);
103         command[17] = LWLA_WORD_2(devc->trigger_edge_mask);
104         command[18] = LWLA_WORD_3(devc->trigger_edge_mask);
105
106         command[19] = LWLA_WORD_0(devc->trigger_mask);
107         command[20] = LWLA_WORD_1(devc->trigger_mask);
108         command[21] = LWLA_WORD_2(devc->trigger_mask);
109         command[22] = LWLA_WORD_3(devc->trigger_mask);
110
111         /* Set the capture memory full threshold. This is slightly less
112          * than the actual maximum, most likely in order to compensate for
113          * pipeline latency.
114          */
115         memory_limit = MEMORY_DEPTH - 16;
116
117         command[23] = LWLA_WORD_0(memory_limit);
118         command[24] = LWLA_WORD_1(memory_limit);
119         command[25] = LWLA_WORD_2(memory_limit);
120         command[26] = LWLA_WORD_3(memory_limit);
121
122         /* Fill remaining 64-bit words with zeroes. */
123         memset(&command[27], 0, 16 * sizeof(uint16_t));
124
125         return lwla_send_command(sdi->conn, command, G_N_ELEMENTS(command));
126 }
127
128 /* Issue a register write command as an asynchronous USB transfer.
129  */
130 static int issue_write_reg(const struct sr_dev_inst *sdi,
131                            unsigned int reg, unsigned int value)
132 {
133         struct dev_context *devc;
134         struct acquisition_state *acq;
135
136         devc = sdi->priv;
137         acq  = devc->acquisition;
138
139         acq->xfer_buf_out[0] = LWLA_WORD(CMD_WRITE_REG);
140         acq->xfer_buf_out[1] = LWLA_WORD(reg);
141         acq->xfer_buf_out[2] = LWLA_WORD_0(value);
142         acq->xfer_buf_out[3] = LWLA_WORD_1(value);
143
144         acq->xfer_out->length = 4 * sizeof(uint16_t);
145
146         return submit_transfer(devc, acq->xfer_out);
147 }
148
149 /* Issue a register write command as an asynchronous USB transfer for the
150  * next register/value pair of the currently active register write sequence.
151  */
152 static int issue_next_write_reg(const struct sr_dev_inst *sdi)
153 {
154         struct dev_context *devc;
155         struct regval_pair *regval;
156         int ret;
157
158         devc = sdi->priv;
159
160         if (devc->reg_write_pos >= devc->reg_write_len) {
161                 sr_err("Already written all registers in sequence.");
162                 return SR_ERR_BUG;
163         }
164         regval = &devc->reg_write_seq[devc->reg_write_pos];
165
166         ret = issue_write_reg(sdi, regval->reg, regval->val);
167         if (ret != SR_OK)
168                 return ret;
169
170         ++devc->reg_write_pos;
171         return SR_OK;
172 }
173
174 /* Issue a capture status request as an asynchronous USB transfer.
175  */
176 static void request_capture_status(const struct sr_dev_inst *sdi)
177 {
178         struct dev_context *devc;
179         struct acquisition_state *acq;
180
181         devc = sdi->priv;
182         acq  = devc->acquisition;
183
184         acq->xfer_buf_out[0] = LWLA_WORD(CMD_CAP_STATUS);
185         acq->xfer_buf_out[1] = LWLA_WORD(CAP_STAT_ADDR);
186         acq->xfer_buf_out[2] = LWLA_WORD(CAP_STAT_LEN);
187
188         acq->xfer_out->length = 3 * sizeof(uint16_t);
189
190         if (submit_transfer(devc, acq->xfer_out) == SR_OK)
191                 devc->state = STATE_STATUS_REQUEST;
192 }
193
194 /* Issue a request for the capture buffer fill level as
195  * an asynchronous USB transfer.
196  */
197 static void request_capture_length(const struct sr_dev_inst *sdi)
198 {
199         struct dev_context *devc;
200         struct acquisition_state *acq;
201
202         devc = sdi->priv;
203         acq  = devc->acquisition;
204
205         acq->xfer_buf_out[0] = LWLA_WORD(CMD_READ_REG);
206         acq->xfer_buf_out[1] = LWLA_WORD(REG_MEM_FILL);
207
208         acq->xfer_out->length = 2 * sizeof(uint16_t);
209
210         if (submit_transfer(devc, acq->xfer_out) == SR_OK)
211                 devc->state = STATE_LENGTH_REQUEST;
212 }
213
214 /* Initiate the capture memory read operation:  Reset the acquisition state
215  * and start a sequence of register writes in order to set up the device for
216  * reading from the capture buffer.
217  */
218 static void issue_read_start(const struct sr_dev_inst *sdi)
219 {
220         struct dev_context *devc;
221         struct acquisition_state *acq;
222         struct regval_pair *regvals;
223
224         devc = sdi->priv;
225         acq  = devc->acquisition;
226
227         /* Reset RLE state. */
228         acq->rle = RLE_STATE_DATA;
229         acq->sample  = 0;
230         acq->run_len = 0;
231
232         acq->captured_samples    = 0;
233         acq->transferred_samples = 0;
234
235         /* For some reason, the start address is 4 rather than 0. */
236         acq->mem_addr_done = 4;
237         acq->mem_addr_next = 4;
238         acq->mem_addr_stop = acq->mem_addr_fill;
239
240         /* Byte offset into the packet output buffer. */
241         acq->out_offset = 0;
242
243         regvals = devc->reg_write_seq;
244
245         regvals[0].reg = REG_DIV_BYPASS;
246         regvals[0].val = 1;
247
248         regvals[1].reg = REG_MEM_CTRL2;
249         regvals[1].val = 2;
250
251         regvals[2].reg = REG_MEM_CTRL4;
252         regvals[2].val = 4;
253
254         devc->reg_write_pos = 0;
255         devc->reg_write_len = 3;
256
257         if (issue_next_write_reg(sdi) == SR_OK)
258                 devc->state = STATE_READ_PREPARE;
259 }
260
261 static void issue_read_end(const struct sr_dev_inst *sdi)
262 {
263         struct dev_context *devc;
264
265         devc = sdi->priv;
266
267         if (issue_write_reg(sdi, REG_DIV_BYPASS, 0) == SR_OK)
268                 devc->state = STATE_READ_END;
269 }
270
271 /* Decode an incoming reponse to a buffer fill level request and act on it
272  * as appropriate.  Note that this function changes the device context state.
273  */
274 static void process_capture_length(const struct sr_dev_inst *sdi)
275 {
276         struct dev_context *devc;
277         struct acquisition_state *acq;
278
279         devc = sdi->priv;
280         acq  = devc->acquisition;
281
282         if (acq->xfer_in->actual_length != 4) {
283                 sr_err("Received size %d doesn't match expected size 4.",
284                        acq->xfer_in->actual_length);
285                 devc->transfer_error = TRUE;
286                 return;
287         }
288         acq->mem_addr_fill = LWLA_READ32(acq->xfer_buf_in);
289
290         sr_dbg("%lu words in capture buffer.",
291                (unsigned long)acq->mem_addr_fill);
292
293         if (acq->mem_addr_fill > 0 && sdi->status == SR_ST_ACTIVE)
294                 issue_read_start(sdi);
295         else
296                 issue_read_end(sdi);
297 }
298
299 /* Initiate a sequence of register write commands with the effect of
300  * cancelling a running capture operation.  This sets a new device state
301  * if issuing the first command succeeds.
302  */
303 static void issue_stop_capture(const struct sr_dev_inst *sdi)
304 {
305         struct dev_context *devc;
306         struct regval_pair *regvals;
307
308         devc = sdi->priv;
309
310         if (devc->stopping_in_progress)
311                 return;
312
313         regvals = devc->reg_write_seq;
314
315         regvals[0].reg = REG_CMD_CTRL2;
316         regvals[0].val = 10;
317
318         regvals[1].reg = REG_CMD_CTRL3;
319         regvals[1].val = 0;
320
321         regvals[2].reg = REG_CMD_CTRL4;
322         regvals[2].val = 0;
323
324         regvals[3].reg = REG_CMD_CTRL1;
325         regvals[3].val = 0;
326
327         regvals[4].reg = REG_DIV_BYPASS;
328         regvals[4].val = 0;
329
330         devc->reg_write_pos = 0;
331         devc->reg_write_len = 5;
332
333         if (issue_next_write_reg(sdi) == SR_OK) {
334                 devc->stopping_in_progress = TRUE;
335                 devc->state = STATE_STOP_CAPTURE;
336         }
337 }
338
339 /* Decode an incoming capture status reponse and act on it as appropriate.
340  * Note that this function changes the device state.
341  */
342 static void process_capture_status(const struct sr_dev_inst *sdi)
343 {
344         uint64_t duration;
345         uint64_t timescale;
346         struct dev_context *devc;
347         struct acquisition_state *acq;
348
349         devc = sdi->priv;
350         acq  = devc->acquisition;
351
352         if (acq->xfer_in->actual_length != CAP_STAT_LEN * 8) {
353                 sr_err("Received size %d doesn't match expected size %d.",
354                        acq->xfer_in->actual_length, CAP_STAT_LEN * 8);
355                 devc->transfer_error = TRUE;
356                 return;
357         }
358
359         /* TODO: Find out the actual bit width of these fields as stored
360          * in the FPGA.  These fields are definitely less than 64 bit wide
361          * internally, and the unused bits occasionally even contain garbage.
362          */
363         acq->mem_addr_fill = LWLA_READ32(&acq->xfer_buf_in[0]);
364         duration           = LWLA_READ32(&acq->xfer_buf_in[8]);
365         acq->capture_flags = LWLA_READ32(&acq->xfer_buf_in[16])
366                                 & STATUS_FLAG_MASK;
367
368         /* The 125 MHz setting is special, and uses the same timebase
369          * for the duration field as the 100 MHz setting.
370          */
371         timescale = MIN(devc->samplerate, SR_MHZ(100));
372         acq->captured_samples = (duration * timescale) / 1000;
373
374         sr_spew("Captured %lu words, %" PRIu64 " samples, flags 0x%02X",
375                 (unsigned long)acq->mem_addr_fill,
376                 acq->captured_samples, acq->capture_flags);
377
378         if (acq->captured_samples >= devc->limit_samples) {
379                 issue_stop_capture(sdi);
380                 return;
381         }
382         devc->state = STATE_STATUS_WAIT;
383
384         if ((acq->capture_flags & STATUS_TRIGGERED) == 0) {
385                 sr_spew("Waiting for trigger.");
386         } else if ((acq->capture_flags & STATUS_MEM_AVAIL) == 0) {
387                 sr_dbg("Capture memory filled.");
388                 request_capture_length(sdi);
389         } else if ((acq->capture_flags & STATUS_CAPTURING) != 0) {
390                 sr_spew("Sampling in progress.");
391         }
392 }
393
394 /* Issue a capture buffer read request as an asynchronous USB transfer.
395  * The address and size of the memory area to read are derived from the
396  * current acquisition state.
397  */
398 static void request_read_mem(const struct sr_dev_inst *sdi)
399 {
400         struct dev_context *devc;
401         struct acquisition_state *acq;
402         size_t count;
403
404         devc = sdi->priv;
405         acq  = devc->acquisition;
406
407         if (acq->mem_addr_next >= acq->mem_addr_stop)
408                 return;
409
410         /* Always read a multiple of 8 device words. */
411         count = (acq->mem_addr_stop - acq->mem_addr_next + 7) / 8 * 8;
412         count = MIN(count, READ_CHUNK_LEN);
413
414         acq->xfer_buf_out[0] = LWLA_WORD(CMD_READ_MEM);
415         acq->xfer_buf_out[1] = LWLA_WORD_0(acq->mem_addr_next);
416         acq->xfer_buf_out[2] = LWLA_WORD_1(acq->mem_addr_next);
417         acq->xfer_buf_out[3] = LWLA_WORD_0(count);
418         acq->xfer_buf_out[4] = LWLA_WORD_1(count);
419
420         acq->xfer_out->length = 5 * sizeof(uint16_t);
421
422         if (submit_transfer(devc, acq->xfer_out) == SR_OK) {
423                 acq->mem_addr_next += count;
424                 devc->state = STATE_READ_REQUEST;
425         }
426 }
427
428 /* Send a packet of logic samples to the session bus.  The payload is taken
429  * from the acquisition state.  The return value indicates whether to stop
430  * reading more samples.
431  */
432 static gboolean send_logic_packet(const struct sr_dev_inst *sdi)
433 {
434         uint64_t samples;
435         struct dev_context *devc;
436         struct acquisition_state *acq;
437         struct sr_datafeed_packet packet;
438         struct sr_datafeed_logic  logic;
439         int last;
440
441         devc = sdi->priv;
442         acq  = devc->acquisition;
443
444         if (acq->transferred_samples >= devc->limit_samples)
445                 return TRUE;
446
447         packet.type    = SR_DF_LOGIC;
448         packet.payload = &logic;
449         logic.unitsize = UNIT_SIZE;
450         logic.data     = acq->out_packet;
451         logic.length   = acq->out_offset;
452
453         samples = acq->out_offset / UNIT_SIZE;
454         last = FALSE;
455
456         /* Cut the packet short if necessary. */
457         if (acq->transferred_samples + samples >= devc->limit_samples) {
458                 samples = devc->limit_samples - acq->transferred_samples;
459                 logic.length = samples * UNIT_SIZE;
460                 last = TRUE;
461         }
462         acq->transferred_samples += samples;
463         acq->out_offset = 0;
464
465         /* Send off logic datafeed packet. */
466         sr_session_send(sdi, &packet);
467
468         return last;
469 }
470
471 /* Demangle and decompress incoming sample data from the capture buffer.
472  * The data chunk is taken from the acquisition state, and is expected to
473  * contain a multiple of 8 device words.
474  * All data currently in the acquisition buffer will be processed.  Packets
475  * of decoded samples are sent off to the session bus whenever the output
476  * buffer becomes full while decoding.
477  */
478 static int process_sample_data(const struct sr_dev_inst *sdi)
479 {
480         uint64_t sample;
481         uint64_t run_len;
482         uint64_t high_nibbles;
483         uint64_t word;
484         struct dev_context *devc;
485         struct acquisition_state *acq;
486         uint8_t *out_p;
487         uint16_t *slice;
488         size_t expect_len;
489         size_t actual_len;
490         size_t in_words_left;
491         size_t si;
492
493         devc = sdi->priv;
494         acq  = devc->acquisition;
495
496         if (acq->mem_addr_done >= acq->mem_addr_stop
497                         || acq->transferred_samples >= devc->limit_samples)
498                 return SR_OK;
499
500         in_words_left = MIN(acq->mem_addr_stop - acq->mem_addr_done,
501                             READ_CHUNK_LEN);
502         expect_len = LWLA1034_MEMBUF_LEN(in_words_left) * sizeof(uint16_t);
503         actual_len = acq->xfer_in->actual_length;
504
505         if (actual_len != expect_len) {
506                 sr_err("Received size %lu does not match expected size %lu.",
507                        (unsigned long)actual_len, (unsigned long)expect_len);
508                 devc->transfer_error = TRUE;
509                 return SR_ERR;
510         }
511         acq->mem_addr_done += in_words_left;
512         slice = acq->xfer_buf_in;
513         si = 0; /* word index within slice */
514
515         for (;;) {
516                 sample = acq->sample;
517                 /* Expand run-length samples into session packet. */
518                 for (run_len = acq->run_len; run_len > 0; --run_len) {
519                         out_p = &acq->out_packet[acq->out_offset];
520                         out_p[0] =  sample        & 0xFF;
521                         out_p[1] = (sample >>  8) & 0xFF;
522                         out_p[2] = (sample >> 16) & 0xFF;
523                         out_p[3] = (sample >> 24) & 0xFF;
524                         out_p[4] = (sample >> 32) & 0xFF;
525                         acq->out_offset += UNIT_SIZE;
526
527                         /* Send out packet if it is full. */
528                         if (acq->out_offset > PACKET_SIZE - UNIT_SIZE)
529                                 if (send_logic_packet(sdi))
530                                         return SR_OK; /* sample limit reached */
531                 }
532                 acq->run_len = 0;
533
534                 if (in_words_left == 0)
535                         break; /* done with current chunk */
536
537                 /* Now work on the current slice. */
538                 high_nibbles = LWLA_READ32(&slice[8 * 2]);
539                 word = LWLA_READ32(&slice[si * 2]);
540                 word |= (high_nibbles << (4 * si + 4)) & ((uint64_t)0xF << 32);
541
542                 if (acq->rle == RLE_STATE_DATA) {
543                         acq->sample = word & ALL_CHANNELS_MASK;
544                         acq->run_len = ((word >> NUM_PROBES) & 1) + 1;
545                         if (word & RLE_FLAG_LEN_FOLLOWS)
546                                 acq->rle = RLE_STATE_LEN;
547                 } else {
548                         acq->run_len += word << 1;
549                         acq->rle = RLE_STATE_DATA;
550                 }
551
552                 /* Move to next word. */
553                 if (++si >= 8) {
554                         si = 0;
555                         slice += 9 * 2;
556                 }
557                 --in_words_left;
558         }
559
560         /* Send out partially filled packet if it is the last one. */
561         if (acq->mem_addr_done >= acq->mem_addr_stop && acq->out_offset > 0)
562                 send_logic_packet(sdi);
563
564         return SR_OK;
565 }
566
567 /* Finish an acquisition session.  This sends the end packet to the session
568  * bus and removes the listener for asynchronous USB transfers.
569  */
570 static void end_acquisition(struct sr_dev_inst *sdi)
571 {
572         struct drv_context *drvc;
573         struct dev_context *devc;
574         struct sr_datafeed_packet packet;
575
576         drvc = sdi->driver->priv;
577         devc = sdi->priv;
578
579         if (devc->state == STATE_IDLE)
580                 return;
581
582         devc->state = STATE_IDLE;
583
584         /* Remove USB file descriptors from polling. */
585         usb_source_remove(drvc->sr_ctx);
586
587         packet.type = SR_DF_END;
588         sr_session_send(sdi, &packet);
589
590         lwla_free_acquisition_state(devc->acquisition);
591         devc->acquisition = NULL;
592
593         sdi->status = SR_ST_ACTIVE;
594 }
595
596 /* USB output transfer completion callback.
597  */
598 static void receive_transfer_out(struct libusb_transfer *transfer)
599 {
600         struct sr_dev_inst *sdi;
601         struct dev_context *devc;
602
603         sdi  = transfer->user_data;
604         devc = sdi->priv;
605
606         if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
607                 sr_err("Transfer to device failed: %d.", transfer->status);
608                 devc->transfer_error = TRUE;
609                 return;
610         }
611
612         if (devc->reg_write_pos < devc->reg_write_len) {
613                 issue_next_write_reg(sdi);
614         } else {
615                 switch (devc->state) {
616                 case STATE_START_CAPTURE:
617                         devc->state = STATE_STATUS_WAIT;
618                         break;
619                 case STATE_STATUS_REQUEST:
620                         devc->state = STATE_STATUS_RESPONSE;
621                         submit_transfer(devc, devc->acquisition->xfer_in);
622                         break;
623                 case STATE_STOP_CAPTURE:
624                         if (sdi->status == SR_ST_ACTIVE)
625                                 request_capture_length(sdi);
626                         else
627                                 end_acquisition(sdi);
628                         break;
629                 case STATE_LENGTH_REQUEST:
630                         devc->state = STATE_LENGTH_RESPONSE;
631                         submit_transfer(devc, devc->acquisition->xfer_in);
632                         break;
633                 case STATE_READ_PREPARE:
634                         request_read_mem(sdi);
635                         break;
636                 case STATE_READ_REQUEST:
637                         devc->state = STATE_READ_RESPONSE;
638                         submit_transfer(devc, devc->acquisition->xfer_in);
639                         break;
640                 case STATE_READ_END:
641                         end_acquisition(sdi);
642                         break;
643                 default:
644                         sr_err("Unexpected device state %d.", devc->state);
645                         break;
646                 }
647         }
648 }
649
650 /* USB input transfer completion callback.
651  */
652 static void receive_transfer_in(struct libusb_transfer *transfer)
653 {
654         struct sr_dev_inst *sdi;
655         struct dev_context *devc;
656         struct acquisition_state *acq;
657
658         sdi  = transfer->user_data;
659         devc = sdi->priv;
660         acq  = devc->acquisition;
661
662         if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
663                 sr_err("Transfer from device failed: %d.", transfer->status);
664                 devc->transfer_error = TRUE;
665                 return;
666         }
667
668         switch (devc->state) {
669         case STATE_STATUS_RESPONSE:
670                 process_capture_status(sdi);
671                 break;
672         case STATE_LENGTH_RESPONSE:
673                 process_capture_length(sdi);
674                 break;
675         case STATE_READ_RESPONSE:
676                 if (process_sample_data(sdi) == SR_OK
677                                 && acq->mem_addr_next < acq->mem_addr_stop
678                                 && acq->transferred_samples < devc->limit_samples)
679                         request_read_mem(sdi);
680                 else
681                         issue_read_end(sdi);
682                 break;
683         default:
684                 sr_err("Unexpected device state %d.", devc->state);
685                 break;
686         }
687 }
688
689 /* Initialize the LWLA.  This downloads a bitstream into the FPGA
690  * and executes a simple device test sequence.
691  */
692 SR_PRIV int lwla_init_device(const struct sr_dev_inst *sdi)
693 {
694         struct dev_context *devc;
695         int ret;
696         uint32_t value;
697
698         devc = sdi->priv;
699
700         /* Select internal clock if it hasn't been set yet */
701         if (devc->selected_clock_source == CLOCK_SOURCE_NONE)
702                 devc->selected_clock_source = CLOCK_SOURCE_INT;
703
704         /* Force reload of bitstream */
705         devc->cur_clock_source = CLOCK_SOURCE_NONE;
706
707         ret = lwla_set_clock_source(sdi);
708
709         if (ret != SR_OK)
710                 return ret;
711
712         ret = lwla_write_reg(sdi->conn, REG_CMD_CTRL2, 100);
713         if (ret != SR_OK)
714                 return ret;
715
716         ret = lwla_read_reg(sdi->conn, REG_CMD_CTRL1, &value);
717         if (ret != SR_OK)
718                 return ret;
719         sr_info("Received test word 0x%08X back.", value);
720         if (value != 0x12345678)
721                 return SR_ERR;
722
723         ret = lwla_read_reg(sdi->conn, REG_CMD_CTRL4, &value);
724         if (ret != SR_OK)
725                 return ret;
726         sr_info("Received test word 0x%08X back.", value);
727         if (value != 0x12345678)
728                 return SR_ERR;
729
730         ret = lwla_read_reg(sdi->conn, REG_CMD_CTRL3, &value);
731         if (ret != SR_OK)
732                 return ret;
733         sr_info("Received test word 0x%08X back.", value);
734         if (value != 0x87654321)
735                 return SR_ERR;
736
737         return ret;
738 }
739
740 /* Select the LWLA clock source.  If the clock source changed from the
741  * previous setting, this will download a new bitstream to the FPGA.
742  */
743 SR_PRIV int lwla_set_clock_source(const struct sr_dev_inst *sdi)
744 {
745         struct dev_context *devc;
746         int ret;
747         enum clock_source selected;
748         size_t idx;
749
750         devc = sdi->priv;
751         selected = devc->selected_clock_source;
752
753         if (devc->cur_clock_source != selected) {
754                 devc->cur_clock_source = CLOCK_SOURCE_NONE;
755                 idx = selected;
756                 if (idx >= G_N_ELEMENTS(bitstream_map)) {
757                         sr_err("Clock source (%d) out of range", selected);
758                         return SR_ERR_BUG;
759                 }
760                 ret = lwla_send_bitstream(sdi->conn, bitstream_map[idx]);
761                 if (ret == SR_OK)
762                         devc->cur_clock_source = selected;
763                 return ret;
764         }
765         return SR_OK;
766 }
767
768 /* Configure the LWLA in preparation for an acquisition session.
769  */
770 SR_PRIV int lwla_setup_acquisition(const struct sr_dev_inst *sdi)
771 {
772         struct dev_context *devc;
773         struct sr_usb_dev_inst *usb;
774         struct regval_pair regvals[7];
775         int ret;
776
777         devc = sdi->priv;
778         usb  = sdi->conn;
779
780         regvals[0].reg = REG_MEM_CTRL2;
781         regvals[0].val = 2;
782
783         regvals[1].reg = REG_MEM_CTRL2;
784         regvals[1].val = 1;
785
786         regvals[2].reg = REG_CMD_CTRL2;
787         regvals[2].val = 10;
788
789         regvals[3].reg = REG_CMD_CTRL3;
790         regvals[3].val = 0x74;
791
792         regvals[4].reg = REG_CMD_CTRL4;
793         regvals[4].val = 0;
794
795         regvals[5].reg = REG_CMD_CTRL1;
796         regvals[5].val = 0;
797
798         regvals[6].reg = REG_DIV_BYPASS;
799         regvals[6].val = (devc->samplerate > SR_MHZ(100)) ? 1 : 0;
800
801         ret = lwla_write_regs(usb, regvals, G_N_ELEMENTS(regvals));
802         if (ret != SR_OK)
803                 return ret;
804
805         return capture_setup(sdi);
806 }
807
808 /* Start the capture operation on the LWLA device.  Beginning with this
809  * function, all USB transfers will be asynchronous until the end of the
810  * acquisition session.
811  */
812 SR_PRIV int lwla_start_acquisition(const struct sr_dev_inst *sdi)
813 {
814         struct dev_context *devc;
815         struct sr_usb_dev_inst *usb;
816         struct acquisition_state *acq;
817         struct regval_pair *regvals;
818
819         devc = sdi->priv;
820         usb  = sdi->conn;
821         acq  = devc->acquisition;
822
823         libusb_fill_bulk_transfer(acq->xfer_out, usb->devhdl, EP_COMMAND,
824                                   (unsigned char *)acq->xfer_buf_out, 0,
825                                   &receive_transfer_out,
826                                   (struct sr_dev_inst *)sdi, USB_TIMEOUT);
827
828         libusb_fill_bulk_transfer(acq->xfer_in, usb->devhdl, EP_REPLY,
829                                   (unsigned char *)acq->xfer_buf_in,
830                                   sizeof acq->xfer_buf_in,
831                                   &receive_transfer_in,
832                                   (struct sr_dev_inst *)sdi, USB_TIMEOUT);
833
834         regvals = devc->reg_write_seq;
835
836         regvals[0].reg = REG_CMD_CTRL2;
837         regvals[0].val = 10;
838
839         regvals[1].reg = REG_CMD_CTRL3;
840         regvals[1].val = 1;
841
842         regvals[2].reg = REG_CMD_CTRL4;
843         regvals[2].val = 0;
844
845         regvals[3].reg = REG_CMD_CTRL1;
846         regvals[3].val = 0;
847
848         devc->reg_write_pos = 0;
849         devc->reg_write_len = 4;
850
851         devc->state = STATE_START_CAPTURE;
852
853         return issue_next_write_reg(sdi);
854 }
855
856 /* Allocate an acquisition state object.
857  */
858 SR_PRIV struct acquisition_state *lwla_alloc_acquisition_state(void)
859 {
860         struct acquisition_state *acq;
861
862         acq = g_try_new0(struct acquisition_state, 1);
863         if (!acq) {
864                 sr_err("Acquisition state malloc failed.");
865                 return NULL;
866         }
867
868         acq->xfer_in = libusb_alloc_transfer(0);
869         if (!acq->xfer_in) {
870                 sr_err("Transfer malloc failed.");
871                 g_free(acq);
872                 return NULL;
873         }
874
875         acq->xfer_out = libusb_alloc_transfer(0);
876         if (!acq->xfer_out) {
877                 sr_err("Transfer malloc failed.");
878                 libusb_free_transfer(acq->xfer_in);
879                 g_free(acq);
880                 return NULL;
881         }
882
883         return acq;
884 }
885
886 /* Deallocate an acquisition state object.
887  */
888 SR_PRIV void lwla_free_acquisition_state(struct acquisition_state *acq)
889 {
890         if (acq) {
891                 libusb_free_transfer(acq->xfer_out);
892                 libusb_free_transfer(acq->xfer_in);
893                 g_free(acq);
894         }
895 }
896
897 /* USB I/O source callback.
898  */
899 SR_PRIV int lwla_receive_data(int fd, int revents, void *cb_data)
900 {
901         struct sr_dev_inst *sdi;
902         struct dev_context *devc;
903         struct drv_context *drvc;
904         struct timeval tv;
905         int ret;
906
907         (void)fd;
908
909         sdi  = cb_data;
910         devc = sdi->priv;
911         drvc = sdi->driver->priv;
912
913         if (!devc || !drvc)
914                 return FALSE;
915
916         /* No timeout: return immediately. */
917         tv.tv_sec  = 0;
918         tv.tv_usec = 0;
919
920         ret = libusb_handle_events_timeout_completed(drvc->sr_ctx->libusb_ctx,
921                                                      &tv, NULL);
922         if (ret != 0)
923                 sr_err("Event handling failed: %s.", libusb_error_name(ret));
924
925         /* If no event flags are set the timeout must have expired. */
926         if (revents == 0 && devc->state == STATE_STATUS_WAIT) {
927                 if (sdi->status == SR_ST_STOPPING)
928                         issue_stop_capture(sdi);
929                 else
930                         request_capture_status(sdi);
931         }
932
933         /* Check if an error occurred on a transfer. */
934         if (devc->transfer_error)
935                 end_acquisition(sdi);
936
937         return TRUE;
938 }