]> sigrok.org Git - libsigrok.git/blob - hardware/sysclk-lwla/protocol.c
39b9d893a99b63d1b69b1e62ff3a0f148ddfef8d
[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         struct acquisition_state *acq;
68         uint64_t divider_count;
69         uint64_t memory_limit;
70         uint16_t command[3 + 10*4];
71
72         devc = sdi->priv;
73         acq  = devc->acquisition;
74
75         command[0] = LWLA_WORD(CMD_CAP_SETUP);
76         command[1] = LWLA_WORD(0); /* address */
77         command[2] = LWLA_WORD(10); /* length */
78
79         command[3] = LWLA_WORD_0(devc->channel_mask);
80         command[4] = LWLA_WORD_1(devc->channel_mask);
81         command[5] = LWLA_WORD_2(devc->channel_mask);
82         command[6] = LWLA_WORD_3(devc->channel_mask);
83
84         /* Set the clock divide counter maximum for samplerates of up to
85          * 100 MHz. At the highest samplerate of 125 MHz the clock divider
86          * is bypassed.
87          */
88         if (!acq->bypass_clockdiv && devc->samplerate > 0)
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->samples_done = 0;
235
236         /* For some reason, the start address is 4 rather than 0. */
237         acq->mem_addr_done = 4;
238         acq->mem_addr_next = 4;
239         acq->mem_addr_stop = acq->mem_addr_fill;
240
241         /* Sample position in the packet output buffer. */
242         acq->out_index = 0;
243
244         regvals = devc->reg_write_seq;
245
246         regvals[0].reg = REG_DIV_BYPASS;
247         regvals[0].val = 1;
248
249         regvals[1].reg = REG_MEM_CTRL2;
250         regvals[1].val = 2;
251
252         regvals[2].reg = REG_MEM_CTRL4;
253         regvals[2].val = 4;
254
255         devc->reg_write_pos = 0;
256         devc->reg_write_len = 3;
257
258         if (issue_next_write_reg(sdi) == SR_OK)
259                 devc->state = STATE_READ_PREPARE;
260 }
261
262 /* Issue a command as an asynchronous USB transfer which returns the device
263  * to normal state after a read operation.  Sets a new device context state
264  * on success.
265  */
266 static void issue_read_end(const struct sr_dev_inst *sdi)
267 {
268         struct dev_context *devc;
269
270         devc = sdi->priv;
271
272         if (issue_write_reg(sdi, REG_DIV_BYPASS, 0) == SR_OK)
273                 devc->state = STATE_READ_END;
274 }
275
276 /* Decode an incoming reponse to a buffer fill level request and act on it
277  * as appropriate.  Note that this function changes the device context state.
278  */
279 static void process_capture_length(const struct sr_dev_inst *sdi)
280 {
281         struct dev_context *devc;
282         struct acquisition_state *acq;
283
284         devc = sdi->priv;
285         acq  = devc->acquisition;
286
287         if (acq->xfer_in->actual_length != 4) {
288                 sr_err("Received size %d doesn't match expected size 4.",
289                        acq->xfer_in->actual_length);
290                 devc->transfer_error = TRUE;
291                 return;
292         }
293         acq->mem_addr_fill = LWLA_READ32(acq->xfer_buf_in);
294
295         sr_dbg("%zu words in capture buffer.", acq->mem_addr_fill);
296
297         if (acq->mem_addr_fill > 0 && sdi->status == SR_ST_ACTIVE)
298                 issue_read_start(sdi);
299         else
300                 issue_read_end(sdi);
301 }
302
303 /* Initiate a sequence of register write commands with the effect of
304  * cancelling a running capture operation.  This sets a new device state
305  * if issuing the first command succeeds.
306  */
307 static void issue_stop_capture(const struct sr_dev_inst *sdi)
308 {
309         struct dev_context *devc;
310         struct regval_pair *regvals;
311
312         devc = sdi->priv;
313
314         if (devc->stopping_in_progress)
315                 return;
316
317         regvals = devc->reg_write_seq;
318
319         regvals[0].reg = REG_CMD_CTRL2;
320         regvals[0].val = 10;
321
322         regvals[1].reg = REG_CMD_CTRL3;
323         regvals[1].val = 0;
324
325         regvals[2].reg = REG_CMD_CTRL4;
326         regvals[2].val = 0;
327
328         regvals[3].reg = REG_CMD_CTRL1;
329         regvals[3].val = 0;
330
331         regvals[4].reg = REG_DIV_BYPASS;
332         regvals[4].val = 0;
333
334         devc->reg_write_pos = 0;
335         devc->reg_write_len = 5;
336
337         if (issue_next_write_reg(sdi) == SR_OK) {
338                 devc->stopping_in_progress = TRUE;
339                 devc->state = STATE_STOP_CAPTURE;
340         }
341 }
342
343 /* Decode an incoming capture status reponse and act on it as appropriate.
344  * Note that this function changes the device state.
345  */
346 static void process_capture_status(const struct sr_dev_inst *sdi)
347 {
348         uint64_t duration;
349         struct dev_context *devc;
350         struct acquisition_state *acq;
351         unsigned int mem_fill;
352         unsigned int flags;
353
354         devc = sdi->priv;
355         acq  = devc->acquisition;
356
357         if (acq->xfer_in->actual_length != CAP_STAT_LEN * 8) {
358                 sr_err("Received size %d doesn't match expected size %d.",
359                        acq->xfer_in->actual_length, CAP_STAT_LEN * 8);
360                 devc->transfer_error = TRUE;
361                 return;
362         }
363
364         /* TODO: Find out the actual bit width of these fields as stored
365          * in the FPGA.  These fields are definitely less than 64 bit wide
366          * internally, and the unused bits occasionally even contain garbage.
367          */
368         mem_fill = LWLA_READ32(&acq->xfer_buf_in[0]);
369         duration = LWLA_READ32(&acq->xfer_buf_in[8]);
370         flags    = LWLA_READ32(&acq->xfer_buf_in[16]) & STATUS_FLAG_MASK;
371
372         /* The LWLA1034 runs at 125 MHz if the clock divider is bypassed.
373          * However, the time base used for the duration is apparently not
374          * adjusted for this "boost" mode.  Whereas normally the duration
375          * unit is 1 ms, it is 0.8 ms when the clock divider is bypassed.
376          * As 0.8 = 100 MHz / 125 MHz, it seems that the internal cycle
377          * counter period is the same as at the 100 MHz setting.
378          */
379         if (acq->bypass_clockdiv)
380                 acq->duration_now = duration * 4 / 5;
381         else
382                 acq->duration_now = duration;
383
384         sr_spew("Captured %u words, %" PRIu64 " ms, flags 0x%02X.",
385                 mem_fill, acq->duration_now, flags);
386
387         if ((flags & STATUS_TRIGGERED) > (acq->capture_flags & STATUS_TRIGGERED))
388                 sr_info("Capture triggered.");
389
390         acq->capture_flags = flags;
391
392         if (acq->duration_now >= acq->duration_max) {
393                 sr_dbg("Time limit reached, stopping capture.");
394                 issue_stop_capture(sdi);
395                 return;
396         }
397         devc->state = STATE_STATUS_WAIT;
398
399         if ((acq->capture_flags & STATUS_TRIGGERED) == 0) {
400                 sr_spew("Waiting for trigger.");
401         } else if ((acq->capture_flags & STATUS_MEM_AVAIL) == 0) {
402                 sr_dbg("Capture memory filled.");
403                 request_capture_length(sdi);
404         } else if ((acq->capture_flags & STATUS_CAPTURING) != 0) {
405                 sr_spew("Sampling in progress.");
406         }
407 }
408
409 /* Issue a capture buffer read request as an asynchronous USB transfer.
410  * The address and size of the memory area to read are derived from the
411  * current acquisition state.
412  */
413 static void request_read_mem(const struct sr_dev_inst *sdi)
414 {
415         struct dev_context *devc;
416         struct acquisition_state *acq;
417         size_t count;
418
419         devc = sdi->priv;
420         acq  = devc->acquisition;
421
422         if (acq->mem_addr_next >= acq->mem_addr_stop)
423                 return;
424
425         /* Always read a multiple of 8 device words. */
426         count = (acq->mem_addr_stop - acq->mem_addr_next + 7) / 8 * 8;
427         count = MIN(count, READ_CHUNK_LEN);
428
429         acq->xfer_buf_out[0] = LWLA_WORD(CMD_READ_MEM);
430         acq->xfer_buf_out[1] = LWLA_WORD_0(acq->mem_addr_next);
431         acq->xfer_buf_out[2] = LWLA_WORD_1(acq->mem_addr_next);
432         acq->xfer_buf_out[3] = LWLA_WORD_0(count);
433         acq->xfer_buf_out[4] = LWLA_WORD_1(count);
434
435         acq->xfer_out->length = 5 * sizeof(uint16_t);
436
437         if (submit_transfer(devc, acq->xfer_out) == SR_OK) {
438                 acq->mem_addr_next += count;
439                 devc->state = STATE_READ_REQUEST;
440         }
441 }
442
443 /* Demangle and decompress incoming sample data from the capture buffer.
444  * The data chunk is taken from the acquisition state, and is expected to
445  * contain a multiple of 8 device words.
446  * All data currently in the acquisition buffer will be processed.  Packets
447  * of decoded samples are sent off to the session bus whenever the output
448  * buffer becomes full while decoding.
449  */
450 static int process_sample_data(const struct sr_dev_inst *sdi)
451 {
452         uint64_t sample;
453         uint64_t high_nibbles;
454         uint64_t word;
455         struct dev_context *devc;
456         struct acquisition_state *acq;
457         uint8_t *out_p;
458         uint16_t *slice;
459         struct sr_datafeed_packet packet;
460         struct sr_datafeed_logic logic;
461         size_t expect_len;
462         size_t actual_len;
463         size_t out_max_samples;
464         size_t out_run_samples;
465         size_t ri;
466         size_t in_words_left;
467         size_t si;
468
469         devc = sdi->priv;
470         acq  = devc->acquisition;
471
472         if (acq->mem_addr_done >= acq->mem_addr_stop
473                         || acq->samples_done >= acq->samples_max)
474                 return SR_OK;
475
476         in_words_left = MIN(acq->mem_addr_stop - acq->mem_addr_done,
477                             READ_CHUNK_LEN);
478         expect_len = LWLA1034_MEMBUF_LEN(in_words_left) * sizeof(uint16_t);
479         actual_len = acq->xfer_in->actual_length;
480
481         if (actual_len != expect_len) {
482                 sr_err("Received size %zu does not match expected size %zu.",
483                        actual_len, expect_len);
484                 devc->transfer_error = TRUE;
485                 return SR_ERR;
486         }
487         acq->mem_addr_done += in_words_left;
488
489         /* Prepare session packet. */
490         packet.type    = SR_DF_LOGIC;
491         packet.payload = &logic;
492         logic.unitsize = UNIT_SIZE;
493         logic.data     = acq->out_packet;
494
495         slice = acq->xfer_buf_in;
496         si = 0; /* word index within slice */
497
498         for (;;) {
499                 /* Calculate number of samples to write into packet. */
500                 out_max_samples = MIN(acq->samples_max - acq->samples_done,
501                                       PACKET_LENGTH - acq->out_index);
502                 out_run_samples = MIN(acq->run_len, out_max_samples);
503
504                 /* Expand run-length samples into session packet. */
505                 sample = acq->sample;
506                 out_p = &acq->out_packet[acq->out_index * UNIT_SIZE];
507
508                 for (ri = 0; ri < out_run_samples; ++ri) {
509                         out_p[0] =  sample        & 0xFF;
510                         out_p[1] = (sample >>  8) & 0xFF;
511                         out_p[2] = (sample >> 16) & 0xFF;
512                         out_p[3] = (sample >> 24) & 0xFF;
513                         out_p[4] = (sample >> 32) & 0xFF;
514                         out_p += UNIT_SIZE;
515                 }
516                 acq->run_len -= out_run_samples;
517                 acq->out_index += out_run_samples;
518                 acq->samples_done += out_run_samples;
519
520                 /* Packet full or sample count limit reached? */
521                 if (out_run_samples == out_max_samples) {
522                         logic.length = acq->out_index * UNIT_SIZE;
523                         sr_session_send(sdi, &packet);
524                         acq->out_index = 0;
525
526                         if (acq->samples_done >= acq->samples_max)
527                                 return SR_OK; /* sample limit reached */
528                         if (acq->run_len > 0)
529                                 continue; /* need another packet */
530                 }
531
532                 if (in_words_left == 0)
533                         break; /* done with current chunk */
534
535                 /* Now work on the current slice. */
536                 high_nibbles = LWLA_READ32(&slice[8 * 2]);
537                 word = LWLA_READ32(&slice[si * 2]);
538                 word |= (high_nibbles << (4 * si + 4)) & ((uint64_t)0xF << 32);
539
540                 if (acq->rle == RLE_STATE_DATA) {
541                         acq->sample = word & ALL_CHANNELS_MASK;
542                         acq->run_len = ((word >> NUM_PROBES) & 1) + 1;
543                         if (word & RLE_FLAG_LEN_FOLLOWS)
544                                 acq->rle = RLE_STATE_LEN;
545                 } else {
546                         acq->run_len += word << 1;
547                         acq->rle = RLE_STATE_DATA;
548                 }
549
550                 /* Move to next word. */
551                 if (++si >= 8) {
552                         si = 0;
553                         slice += 9 * 2;
554                 }
555                 --in_words_left;
556         }
557
558         /* Send out partially filled packet if this was the last chunk. */
559         if (acq->mem_addr_done >= acq->mem_addr_stop && acq->out_index > 0) {
560                 logic.length = acq->out_index * UNIT_SIZE;
561                 sr_session_send(sdi, &packet);
562                 acq->out_index = 0;
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->samples_done < acq->samples_max)
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_dbg("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_dbg("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_dbg("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 acquisition_state *acq;
775         struct regval_pair regvals[7];
776         int ret;
777
778         devc = sdi->priv;
779         usb  = sdi->conn;
780         acq  = devc->acquisition;
781
782         if (devc->limit_msec > 0) {
783                 acq->duration_max = devc->limit_msec;
784                 sr_info("Acquisition time limit %" PRIu64 " ms.",
785                         devc->limit_msec);
786         } else
787                 acq->duration_max = MAX_LIMIT_MSEC;
788
789         if (devc->limit_samples > 0) {
790                 acq->samples_max = devc->limit_samples;
791                 sr_info("Acquisition sample count limit %" PRIu64 ".",
792                         devc->limit_samples);
793         } else
794                 acq->samples_max = MAX_LIMIT_SAMPLES;
795
796         switch (devc->cur_clock_source) {
797         case CLOCK_SOURCE_INT:
798                 sr_info("Internal clock, samplerate %" PRIu64 ".",
799                         devc->samplerate);
800                 if (devc->samplerate == 0)
801                         return SR_ERR_BUG;
802                 /* At 125 MHz, the clock divider is bypassed. */
803                 acq->bypass_clockdiv = (devc->samplerate > SR_MHZ(100));
804
805                 /* If only one of the limits is set, derive the other one. */
806                 if (devc->limit_msec == 0 && devc->limit_samples > 0)
807                         acq->duration_max = devc->limit_samples
808                                         * 1000 / devc->samplerate + 1;
809                 else if (devc->limit_samples == 0 && devc->limit_msec > 0)
810                         acq->samples_max = devc->limit_msec
811                                         * devc->samplerate / 1000;
812                 break;
813         case CLOCK_SOURCE_EXT_FALL:
814                 sr_info("External clock, falling edge.");
815                 acq->bypass_clockdiv = TRUE;
816                 break;
817         case CLOCK_SOURCE_EXT_RISE:
818                 sr_info("External clock, rising edge.");
819                 acq->bypass_clockdiv = TRUE;
820                 break;
821         default:
822                 sr_err("No valid clock source has been configured.");
823                 return SR_ERR;
824         }
825
826         regvals[0].reg = REG_MEM_CTRL2;
827         regvals[0].val = 2;
828
829         regvals[1].reg = REG_MEM_CTRL2;
830         regvals[1].val = 1;
831
832         regvals[2].reg = REG_CMD_CTRL2;
833         regvals[2].val = 10;
834
835         regvals[3].reg = REG_CMD_CTRL3;
836         regvals[3].val = 0x74;
837
838         regvals[4].reg = REG_CMD_CTRL4;
839         regvals[4].val = 0;
840
841         regvals[5].reg = REG_CMD_CTRL1;
842         regvals[5].val = 0;
843
844         regvals[6].reg = REG_DIV_BYPASS;
845         regvals[6].val = acq->bypass_clockdiv;
846
847         ret = lwla_write_regs(usb, regvals, G_N_ELEMENTS(regvals));
848         if (ret != SR_OK)
849                 return ret;
850
851         return capture_setup(sdi);
852 }
853
854 /* Start the capture operation on the LWLA device.  Beginning with this
855  * function, all USB transfers will be asynchronous until the end of the
856  * acquisition session.
857  */
858 SR_PRIV int lwla_start_acquisition(const struct sr_dev_inst *sdi)
859 {
860         struct dev_context *devc;
861         struct sr_usb_dev_inst *usb;
862         struct acquisition_state *acq;
863         struct regval_pair *regvals;
864
865         devc = sdi->priv;
866         usb  = sdi->conn;
867         acq  = devc->acquisition;
868
869         acq->duration_now  = 0;
870         acq->mem_addr_fill = 0;
871         acq->capture_flags = 0;
872
873         libusb_fill_bulk_transfer(acq->xfer_out, usb->devhdl, EP_COMMAND,
874                                   (unsigned char *)acq->xfer_buf_out, 0,
875                                   &receive_transfer_out,
876                                   (struct sr_dev_inst *)sdi, USB_TIMEOUT);
877
878         libusb_fill_bulk_transfer(acq->xfer_in, usb->devhdl, EP_REPLY,
879                                   (unsigned char *)acq->xfer_buf_in,
880                                   sizeof acq->xfer_buf_in,
881                                   &receive_transfer_in,
882                                   (struct sr_dev_inst *)sdi, USB_TIMEOUT);
883
884         regvals = devc->reg_write_seq;
885
886         regvals[0].reg = REG_CMD_CTRL2;
887         regvals[0].val = 10;
888
889         regvals[1].reg = REG_CMD_CTRL3;
890         regvals[1].val = 1;
891
892         regvals[2].reg = REG_CMD_CTRL4;
893         regvals[2].val = 0;
894
895         regvals[3].reg = REG_CMD_CTRL1;
896         regvals[3].val = 0;
897
898         devc->reg_write_pos = 0;
899         devc->reg_write_len = 4;
900
901         devc->state = STATE_START_CAPTURE;
902
903         return issue_next_write_reg(sdi);
904 }
905
906 /* Allocate an acquisition state object.
907  */
908 SR_PRIV struct acquisition_state *lwla_alloc_acquisition_state(void)
909 {
910         struct acquisition_state *acq;
911
912         acq = g_try_new0(struct acquisition_state, 1);
913         if (!acq) {
914                 sr_err("Acquisition state malloc failed.");
915                 return NULL;
916         }
917
918         acq->xfer_in = libusb_alloc_transfer(0);
919         if (!acq->xfer_in) {
920                 sr_err("Transfer malloc failed.");
921                 g_free(acq);
922                 return NULL;
923         }
924
925         acq->xfer_out = libusb_alloc_transfer(0);
926         if (!acq->xfer_out) {
927                 sr_err("Transfer malloc failed.");
928                 libusb_free_transfer(acq->xfer_in);
929                 g_free(acq);
930                 return NULL;
931         }
932
933         return acq;
934 }
935
936 /* Deallocate an acquisition state object.
937  */
938 SR_PRIV void lwla_free_acquisition_state(struct acquisition_state *acq)
939 {
940         if (acq) {
941                 libusb_free_transfer(acq->xfer_out);
942                 libusb_free_transfer(acq->xfer_in);
943                 g_free(acq);
944         }
945 }
946
947 /* USB I/O source callback.
948  */
949 SR_PRIV int lwla_receive_data(int fd, int revents, void *cb_data)
950 {
951         struct sr_dev_inst *sdi;
952         struct dev_context *devc;
953         struct drv_context *drvc;
954         struct timeval tv;
955         int ret;
956
957         (void)fd;
958
959         sdi  = cb_data;
960         devc = sdi->priv;
961         drvc = sdi->driver->priv;
962
963         if (!devc || !drvc)
964                 return FALSE;
965
966         /* No timeout: return immediately. */
967         tv.tv_sec  = 0;
968         tv.tv_usec = 0;
969
970         ret = libusb_handle_events_timeout_completed(drvc->sr_ctx->libusb_ctx,
971                                                      &tv, NULL);
972         if (ret != 0)
973                 sr_err("Event handling failed: %s.", libusb_error_name(ret));
974
975         /* If no event flags are set the timeout must have expired. */
976         if (revents == 0 && devc->state == STATE_STATUS_WAIT) {
977                 if (sdi->status == SR_ST_STOPPING)
978                         issue_stop_capture(sdi);
979                 else
980                         request_capture_status(sdi);
981         }
982
983         /* Check if an error occurred on a transfer. */
984         if (devc->transfer_error)
985                 end_acquisition(sdi);
986
987         return TRUE;
988 }