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