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