]> sigrok.org Git - libsigrok.git/blob - hardware/sysclk-lwla/protocol.c
7c8cc80a13d45c84c48abf0e7aaced164c3acc37
[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         /* Byte offset into the packet output buffer. */
242         acq->out_offset = 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("%lu words in capture buffer.",
296                (unsigned long)acq->mem_addr_fill);
297
298         if (acq->mem_addr_fill > 0 && sdi->status == SR_ST_ACTIVE)
299                 issue_read_start(sdi);
300         else
301                 issue_read_end(sdi);
302 }
303
304 /* Initiate a sequence of register write commands with the effect of
305  * cancelling a running capture operation.  This sets a new device state
306  * if issuing the first command succeeds.
307  */
308 static void issue_stop_capture(const struct sr_dev_inst *sdi)
309 {
310         struct dev_context *devc;
311         struct regval_pair *regvals;
312
313         devc = sdi->priv;
314
315         if (devc->stopping_in_progress)
316                 return;
317
318         regvals = devc->reg_write_seq;
319
320         regvals[0].reg = REG_CMD_CTRL2;
321         regvals[0].val = 10;
322
323         regvals[1].reg = REG_CMD_CTRL3;
324         regvals[1].val = 0;
325
326         regvals[2].reg = REG_CMD_CTRL4;
327         regvals[2].val = 0;
328
329         regvals[3].reg = REG_CMD_CTRL1;
330         regvals[3].val = 0;
331
332         regvals[4].reg = REG_DIV_BYPASS;
333         regvals[4].val = 0;
334
335         devc->reg_write_pos = 0;
336         devc->reg_write_len = 5;
337
338         if (issue_next_write_reg(sdi) == SR_OK) {
339                 devc->stopping_in_progress = TRUE;
340                 devc->state = STATE_STOP_CAPTURE;
341         }
342 }
343
344 /* Decode an incoming capture status reponse and act on it as appropriate.
345  * Note that this function changes the device state.
346  */
347 static void process_capture_status(const struct sr_dev_inst *sdi)
348 {
349         uint64_t duration;
350         struct dev_context *devc;
351         struct acquisition_state *acq;
352
353         devc = sdi->priv;
354         acq  = devc->acquisition;
355
356         if (acq->xfer_in->actual_length != CAP_STAT_LEN * 8) {
357                 sr_err("Received size %d doesn't match expected size %d.",
358                        acq->xfer_in->actual_length, CAP_STAT_LEN * 8);
359                 devc->transfer_error = TRUE;
360                 return;
361         }
362
363         /* TODO: Find out the actual bit width of these fields as stored
364          * in the FPGA.  These fields are definitely less than 64 bit wide
365          * internally, and the unused bits occasionally even contain garbage.
366          */
367         acq->mem_addr_fill = LWLA_READ32(&acq->xfer_buf_in[0]);
368         duration           = LWLA_READ32(&acq->xfer_buf_in[8]);
369         acq->capture_flags = LWLA_READ32(&acq->xfer_buf_in[16])
370                                 & 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 %zu words, %" PRIu64 " ms, flags 0x%02X",
385                 acq->mem_addr_fill, acq->duration_now, acq->capture_flags);
386
387         if (acq->duration_now >= acq->duration_max) {
388                 issue_stop_capture(sdi);
389                 return;
390         }
391         devc->state = STATE_STATUS_WAIT;
392
393         if ((acq->capture_flags & STATUS_TRIGGERED) == 0) {
394                 sr_spew("Waiting for trigger.");
395         } else if ((acq->capture_flags & STATUS_MEM_AVAIL) == 0) {
396                 sr_dbg("Capture memory filled.");
397                 request_capture_length(sdi);
398         } else if ((acq->capture_flags & STATUS_CAPTURING) != 0) {
399                 sr_spew("Sampling in progress.");
400         }
401 }
402
403 /* Issue a capture buffer read request as an asynchronous USB transfer.
404  * The address and size of the memory area to read are derived from the
405  * current acquisition state.
406  */
407 static void request_read_mem(const struct sr_dev_inst *sdi)
408 {
409         struct dev_context *devc;
410         struct acquisition_state *acq;
411         size_t count;
412
413         devc = sdi->priv;
414         acq  = devc->acquisition;
415
416         if (acq->mem_addr_next >= acq->mem_addr_stop)
417                 return;
418
419         /* Always read a multiple of 8 device words. */
420         count = (acq->mem_addr_stop - acq->mem_addr_next + 7) / 8 * 8;
421         count = MIN(count, READ_CHUNK_LEN);
422
423         acq->xfer_buf_out[0] = LWLA_WORD(CMD_READ_MEM);
424         acq->xfer_buf_out[1] = LWLA_WORD_0(acq->mem_addr_next);
425         acq->xfer_buf_out[2] = LWLA_WORD_1(acq->mem_addr_next);
426         acq->xfer_buf_out[3] = LWLA_WORD_0(count);
427         acq->xfer_buf_out[4] = LWLA_WORD_1(count);
428
429         acq->xfer_out->length = 5 * sizeof(uint16_t);
430
431         if (submit_transfer(devc, acq->xfer_out) == SR_OK) {
432                 acq->mem_addr_next += count;
433                 devc->state = STATE_READ_REQUEST;
434         }
435 }
436
437 /* Send a packet of logic samples to the session bus.  The payload is taken
438  * from the acquisition state.  The return value indicates whether to stop
439  * reading more samples.
440  */
441 static gboolean send_logic_packet(const struct sr_dev_inst *sdi)
442 {
443         uint64_t samples;
444         struct dev_context *devc;
445         struct acquisition_state *acq;
446         struct sr_datafeed_packet packet;
447         struct sr_datafeed_logic  logic;
448         int last;
449
450         devc = sdi->priv;
451         acq  = devc->acquisition;
452
453         if (acq->samples_done >= acq->samples_max)
454                 return TRUE;
455
456         packet.type    = SR_DF_LOGIC;
457         packet.payload = &logic;
458         logic.unitsize = UNIT_SIZE;
459         logic.data     = acq->out_packet;
460         logic.length   = acq->out_offset;
461
462         samples = acq->out_offset / UNIT_SIZE;
463         last = FALSE;
464
465         /* Cut the packet short if necessary. */
466         if (acq->samples_done + samples >= acq->samples_max) {
467                 samples = acq->samples_max - acq->samples_done;
468                 logic.length = samples * UNIT_SIZE;
469                 last = TRUE;
470         }
471         acq->samples_done += samples;
472         acq->out_offset = 0;
473
474         /* Send off logic datafeed packet. */
475         sr_session_send(sdi, &packet);
476
477         return last;
478 }
479
480 /* Demangle and decompress incoming sample data from the capture buffer.
481  * The data chunk is taken from the acquisition state, and is expected to
482  * contain a multiple of 8 device words.
483  * All data currently in the acquisition buffer will be processed.  Packets
484  * of decoded samples are sent off to the session bus whenever the output
485  * buffer becomes full while decoding.
486  */
487 static int process_sample_data(const struct sr_dev_inst *sdi)
488 {
489         uint64_t sample;
490         uint64_t run_len;
491         uint64_t high_nibbles;
492         uint64_t word;
493         struct dev_context *devc;
494         struct acquisition_state *acq;
495         uint8_t *out_p;
496         uint16_t *slice;
497         size_t expect_len;
498         size_t actual_len;
499         size_t in_words_left;
500         size_t si;
501
502         devc = sdi->priv;
503         acq  = devc->acquisition;
504
505         if (acq->mem_addr_done >= acq->mem_addr_stop
506                         || acq->samples_done >= acq->samples_max)
507                 return SR_OK;
508
509         in_words_left = MIN(acq->mem_addr_stop - acq->mem_addr_done,
510                             READ_CHUNK_LEN);
511         expect_len = LWLA1034_MEMBUF_LEN(in_words_left) * sizeof(uint16_t);
512         actual_len = acq->xfer_in->actual_length;
513
514         if (actual_len != expect_len) {
515                 sr_err("Received size %lu does not match expected size %lu.",
516                        (unsigned long)actual_len, (unsigned long)expect_len);
517                 devc->transfer_error = TRUE;
518                 return SR_ERR;
519         }
520         acq->mem_addr_done += in_words_left;
521         slice = acq->xfer_buf_in;
522         si = 0; /* word index within slice */
523
524         for (;;) {
525                 sample = acq->sample;
526                 /* Expand run-length samples into session packet. */
527                 for (run_len = acq->run_len; run_len > 0; --run_len) {
528                         out_p = &acq->out_packet[acq->out_offset];
529                         out_p[0] =  sample        & 0xFF;
530                         out_p[1] = (sample >>  8) & 0xFF;
531                         out_p[2] = (sample >> 16) & 0xFF;
532                         out_p[3] = (sample >> 24) & 0xFF;
533                         out_p[4] = (sample >> 32) & 0xFF;
534                         acq->out_offset += UNIT_SIZE;
535
536                         /* Send out packet if it is full. */
537                         if (acq->out_offset > PACKET_SIZE - UNIT_SIZE)
538                                 if (send_logic_packet(sdi))
539                                         return SR_OK; /* sample limit reached */
540                 }
541                 acq->run_len = 0;
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_READ32(&slice[8 * 2]);
548                 word = LWLA_READ32(&slice[si * 2]);
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_PROBES) & 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                 if (++si >= 8) {
563                         si = 0;
564                         slice += 9 * 2;
565                 }
566                 --in_words_left;
567         }
568
569         /* Send out partially filled packet if it is the last one. */
570         if (acq->mem_addr_done >= acq->mem_addr_stop && acq->out_offset > 0)
571                 send_logic_packet(sdi);
572
573         return SR_OK;
574 }
575
576 /* Finish an acquisition session.  This sends the end packet to the session
577  * bus and removes the listener for asynchronous USB transfers.
578  */
579 static void end_acquisition(struct sr_dev_inst *sdi)
580 {
581         struct drv_context *drvc;
582         struct dev_context *devc;
583         struct sr_datafeed_packet packet;
584
585         drvc = sdi->driver->priv;
586         devc = sdi->priv;
587
588         if (devc->state == STATE_IDLE)
589                 return;
590
591         devc->state = STATE_IDLE;
592
593         /* Remove USB file descriptors from polling. */
594         usb_source_remove(drvc->sr_ctx);
595
596         packet.type = SR_DF_END;
597         sr_session_send(sdi, &packet);
598
599         lwla_free_acquisition_state(devc->acquisition);
600         devc->acquisition = NULL;
601
602         sdi->status = SR_ST_ACTIVE;
603 }
604
605 /* USB output transfer completion callback.
606  */
607 static void receive_transfer_out(struct libusb_transfer *transfer)
608 {
609         struct sr_dev_inst *sdi;
610         struct dev_context *devc;
611
612         sdi  = transfer->user_data;
613         devc = sdi->priv;
614
615         if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
616                 sr_err("Transfer to device failed: %d.", transfer->status);
617                 devc->transfer_error = TRUE;
618                 return;
619         }
620
621         if (devc->reg_write_pos < devc->reg_write_len) {
622                 issue_next_write_reg(sdi);
623         } else {
624                 switch (devc->state) {
625                 case STATE_START_CAPTURE:
626                         devc->state = STATE_STATUS_WAIT;
627                         break;
628                 case STATE_STATUS_REQUEST:
629                         devc->state = STATE_STATUS_RESPONSE;
630                         submit_transfer(devc, devc->acquisition->xfer_in);
631                         break;
632                 case STATE_STOP_CAPTURE:
633                         if (sdi->status == SR_ST_ACTIVE)
634                                 request_capture_length(sdi);
635                         else
636                                 end_acquisition(sdi);
637                         break;
638                 case STATE_LENGTH_REQUEST:
639                         devc->state = STATE_LENGTH_RESPONSE;
640                         submit_transfer(devc, devc->acquisition->xfer_in);
641                         break;
642                 case STATE_READ_PREPARE:
643                         request_read_mem(sdi);
644                         break;
645                 case STATE_READ_REQUEST:
646                         devc->state = STATE_READ_RESPONSE;
647                         submit_transfer(devc, devc->acquisition->xfer_in);
648                         break;
649                 case STATE_READ_END:
650                         end_acquisition(sdi);
651                         break;
652                 default:
653                         sr_err("Unexpected device state %d.", devc->state);
654                         break;
655                 }
656         }
657 }
658
659 /* USB input transfer completion callback.
660  */
661 static void receive_transfer_in(struct libusb_transfer *transfer)
662 {
663         struct sr_dev_inst *sdi;
664         struct dev_context *devc;
665         struct acquisition_state *acq;
666
667         sdi  = transfer->user_data;
668         devc = sdi->priv;
669         acq  = devc->acquisition;
670
671         if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
672                 sr_err("Transfer from device failed: %d.", transfer->status);
673                 devc->transfer_error = TRUE;
674                 return;
675         }
676
677         switch (devc->state) {
678         case STATE_STATUS_RESPONSE:
679                 process_capture_status(sdi);
680                 break;
681         case STATE_LENGTH_RESPONSE:
682                 process_capture_length(sdi);
683                 break;
684         case STATE_READ_RESPONSE:
685                 if (process_sample_data(sdi) == SR_OK
686                                 && acq->mem_addr_next < acq->mem_addr_stop
687                                 && acq->samples_done < acq->samples_max)
688                         request_read_mem(sdi);
689                 else
690                         issue_read_end(sdi);
691                 break;
692         default:
693                 sr_err("Unexpected device state %d.", devc->state);
694                 break;
695         }
696 }
697
698 /* Initialize the LWLA.  This downloads a bitstream into the FPGA
699  * and executes a simple device test sequence.
700  */
701 SR_PRIV int lwla_init_device(const struct sr_dev_inst *sdi)
702 {
703         struct dev_context *devc;
704         int ret;
705         uint32_t value;
706
707         devc = sdi->priv;
708
709         /* Select internal clock if it hasn't been set yet */
710         if (devc->selected_clock_source == CLOCK_SOURCE_NONE)
711                 devc->selected_clock_source = CLOCK_SOURCE_INT;
712
713         /* Force reload of bitstream */
714         devc->cur_clock_source = CLOCK_SOURCE_NONE;
715
716         ret = lwla_set_clock_source(sdi);
717
718         if (ret != SR_OK)
719                 return ret;
720
721         ret = lwla_write_reg(sdi->conn, REG_CMD_CTRL2, 100);
722         if (ret != SR_OK)
723                 return ret;
724
725         ret = lwla_read_reg(sdi->conn, REG_CMD_CTRL1, &value);
726         if (ret != SR_OK)
727                 return ret;
728         sr_info("Received test word 0x%08X back.", value);
729         if (value != 0x12345678)
730                 return SR_ERR;
731
732         ret = lwla_read_reg(sdi->conn, REG_CMD_CTRL4, &value);
733         if (ret != SR_OK)
734                 return ret;
735         sr_info("Received test word 0x%08X back.", value);
736         if (value != 0x12345678)
737                 return SR_ERR;
738
739         ret = lwla_read_reg(sdi->conn, REG_CMD_CTRL3, &value);
740         if (ret != SR_OK)
741                 return ret;
742         sr_info("Received test word 0x%08X back.", value);
743         if (value != 0x87654321)
744                 return SR_ERR;
745
746         return ret;
747 }
748
749 /* Select the LWLA clock source.  If the clock source changed from the
750  * previous setting, this will download a new bitstream to the FPGA.
751  */
752 SR_PRIV int lwla_set_clock_source(const struct sr_dev_inst *sdi)
753 {
754         struct dev_context *devc;
755         int ret;
756         enum clock_source selected;
757         size_t idx;
758
759         devc = sdi->priv;
760         selected = devc->selected_clock_source;
761
762         if (devc->cur_clock_source != selected) {
763                 devc->cur_clock_source = CLOCK_SOURCE_NONE;
764                 idx = selected;
765                 if (idx >= G_N_ELEMENTS(bitstream_map)) {
766                         sr_err("Clock source (%d) out of range", selected);
767                         return SR_ERR_BUG;
768                 }
769                 ret = lwla_send_bitstream(sdi->conn, bitstream_map[idx]);
770                 if (ret == SR_OK)
771                         devc->cur_clock_source = selected;
772                 return ret;
773         }
774         return SR_OK;
775 }
776
777 /* Configure the LWLA in preparation for an acquisition session.
778  */
779 SR_PRIV int lwla_setup_acquisition(const struct sr_dev_inst *sdi)
780 {
781         struct dev_context *devc;
782         struct sr_usb_dev_inst *usb;
783         struct acquisition_state *acq;
784         struct regval_pair regvals[7];
785         int ret;
786
787         devc = sdi->priv;
788         usb  = sdi->conn;
789         acq  = devc->acquisition;
790
791         /* By default, run virtually unlimited. */
792         acq->duration_max = (devc->limit_msec > 0)
793                 ? devc->limit_msec : MAX_LIMIT_MSEC;
794         acq->samples_max = (devc->limit_samples > 0)
795                 ? devc->limit_samples : MAX_LIMIT_SAMPLES;
796
797         switch (devc->cur_clock_source) {
798         case CLOCK_SOURCE_INT:
799                 if (devc->samplerate == 0)
800                         return SR_ERR_BUG;
801                 /* At 125 MHz, the clock divider is bypassed. */
802                 acq->bypass_clockdiv = (devc->samplerate > SR_MHZ(100));
803
804                 /* If only one of the limits is set, derive the other one. */
805                 if (devc->limit_msec == 0 && devc->limit_samples > 0)
806                         acq->duration_max = devc->limit_samples
807                                         * 1000 / devc->samplerate + 1;
808                 else if (devc->limit_samples == 0 && devc->limit_msec > 0)
809                         acq->samples_max = devc->limit_msec
810                                         * devc->samplerate / 1000;
811                 break;
812         case CLOCK_SOURCE_EXT_FALL:
813         case CLOCK_SOURCE_EXT_RISE:
814                 acq->bypass_clockdiv = TRUE;
815                 break;
816         default:
817                 sr_err("No valid clock source has been configured.");
818                 return SR_ERR;
819         }
820
821         regvals[0].reg = REG_MEM_CTRL2;
822         regvals[0].val = 2;
823
824         regvals[1].reg = REG_MEM_CTRL2;
825         regvals[1].val = 1;
826
827         regvals[2].reg = REG_CMD_CTRL2;
828         regvals[2].val = 10;
829
830         regvals[3].reg = REG_CMD_CTRL3;
831         regvals[3].val = 0x74;
832
833         regvals[4].reg = REG_CMD_CTRL4;
834         regvals[4].val = 0;
835
836         regvals[5].reg = REG_CMD_CTRL1;
837         regvals[5].val = 0;
838
839         regvals[6].reg = REG_DIV_BYPASS;
840         regvals[6].val = acq->bypass_clockdiv;
841
842         ret = lwla_write_regs(usb, regvals, G_N_ELEMENTS(regvals));
843         if (ret != SR_OK)
844                 return ret;
845
846         return capture_setup(sdi);
847 }
848
849 /* Start the capture operation on the LWLA device.  Beginning with this
850  * function, all USB transfers will be asynchronous until the end of the
851  * acquisition session.
852  */
853 SR_PRIV int lwla_start_acquisition(const struct sr_dev_inst *sdi)
854 {
855         struct dev_context *devc;
856         struct sr_usb_dev_inst *usb;
857         struct acquisition_state *acq;
858         struct regval_pair *regvals;
859
860         devc = sdi->priv;
861         usb  = sdi->conn;
862         acq  = devc->acquisition;
863
864         acq->duration_now = 0;
865
866         libusb_fill_bulk_transfer(acq->xfer_out, usb->devhdl, EP_COMMAND,
867                                   (unsigned char *)acq->xfer_buf_out, 0,
868                                   &receive_transfer_out,
869                                   (struct sr_dev_inst *)sdi, USB_TIMEOUT);
870
871         libusb_fill_bulk_transfer(acq->xfer_in, usb->devhdl, EP_REPLY,
872                                   (unsigned char *)acq->xfer_buf_in,
873                                   sizeof acq->xfer_buf_in,
874                                   &receive_transfer_in,
875                                   (struct sr_dev_inst *)sdi, USB_TIMEOUT);
876
877         regvals = devc->reg_write_seq;
878
879         regvals[0].reg = REG_CMD_CTRL2;
880         regvals[0].val = 10;
881
882         regvals[1].reg = REG_CMD_CTRL3;
883         regvals[1].val = 1;
884
885         regvals[2].reg = REG_CMD_CTRL4;
886         regvals[2].val = 0;
887
888         regvals[3].reg = REG_CMD_CTRL1;
889         regvals[3].val = 0;
890
891         devc->reg_write_pos = 0;
892         devc->reg_write_len = 4;
893
894         devc->state = STATE_START_CAPTURE;
895
896         return issue_next_write_reg(sdi);
897 }
898
899 /* Allocate an acquisition state object.
900  */
901 SR_PRIV struct acquisition_state *lwla_alloc_acquisition_state(void)
902 {
903         struct acquisition_state *acq;
904
905         acq = g_try_new0(struct acquisition_state, 1);
906         if (!acq) {
907                 sr_err("Acquisition state malloc failed.");
908                 return NULL;
909         }
910
911         acq->xfer_in = libusb_alloc_transfer(0);
912         if (!acq->xfer_in) {
913                 sr_err("Transfer malloc failed.");
914                 g_free(acq);
915                 return NULL;
916         }
917
918         acq->xfer_out = libusb_alloc_transfer(0);
919         if (!acq->xfer_out) {
920                 sr_err("Transfer malloc failed.");
921                 libusb_free_transfer(acq->xfer_in);
922                 g_free(acq);
923                 return NULL;
924         }
925
926         return acq;
927 }
928
929 /* Deallocate an acquisition state object.
930  */
931 SR_PRIV void lwla_free_acquisition_state(struct acquisition_state *acq)
932 {
933         if (acq) {
934                 libusb_free_transfer(acq->xfer_out);
935                 libusb_free_transfer(acq->xfer_in);
936                 g_free(acq);
937         }
938 }
939
940 /* USB I/O source callback.
941  */
942 SR_PRIV int lwla_receive_data(int fd, int revents, void *cb_data)
943 {
944         struct sr_dev_inst *sdi;
945         struct dev_context *devc;
946         struct drv_context *drvc;
947         struct timeval tv;
948         int ret;
949
950         (void)fd;
951
952         sdi  = cb_data;
953         devc = sdi->priv;
954         drvc = sdi->driver->priv;
955
956         if (!devc || !drvc)
957                 return FALSE;
958
959         /* No timeout: return immediately. */
960         tv.tv_sec  = 0;
961         tv.tv_usec = 0;
962
963         ret = libusb_handle_events_timeout_completed(drvc->sr_ctx->libusb_ctx,
964                                                      &tv, NULL);
965         if (ret != 0)
966                 sr_err("Event handling failed: %s.", libusb_error_name(ret));
967
968         /* If no event flags are set the timeout must have expired. */
969         if (revents == 0 && devc->state == STATE_STATUS_WAIT) {
970                 if (sdi->status == SR_ST_STOPPING)
971                         issue_stop_capture(sdi);
972                 else
973                         request_capture_status(sdi);
974         }
975
976         /* Check if an error occurred on a transfer. */
977         if (devc->transfer_error)
978                 end_acquisition(sdi);
979
980         return TRUE;
981 }