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