]> sigrok.org Git - libsigrok.git/blob - src/hardware/sysclk-lwla/protocol.c
20cf10f9c5fabc81b2cf9329e8babc778ae3a6e4
[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 #include "lwla.h"
24
25 /* Submit an already filled-in USB transfer.
26  */
27 static int submit_transfer(struct dev_context *devc,
28                            struct libusb_transfer *xfer)
29 {
30         int ret;
31
32         ret = libusb_submit_transfer(xfer);
33
34         if (ret != 0) {
35                 sr_err("Submit transfer failed: %s.", libusb_error_name(ret));
36                 devc->transfer_error = TRUE;
37                 return SR_ERR;
38         }
39
40         return SR_OK;
41 }
42
43 /* Set up transfer for the next register in a write sequence.
44  */
45 static void next_reg_write(struct acquisition_state *acq)
46 {
47         struct regval *regval;
48
49         regval = &acq->reg_sequence[acq->reg_seq_pos];
50
51         acq->xfer_buf_out[0] = LWLA_WORD(CMD_WRITE_REG);
52         acq->xfer_buf_out[1] = LWLA_WORD(regval->reg);
53         acq->xfer_buf_out[2] = LWLA_WORD_0(regval->val);
54         acq->xfer_buf_out[3] = LWLA_WORD_1(regval->val);
55
56         acq->xfer_out->length = 4 * sizeof(acq->xfer_buf_out[0]);
57 }
58
59 /* Set up transfer for the next register in a read sequence.
60  */
61 static void next_reg_read(struct acquisition_state *acq)
62 {
63         unsigned int addr;
64
65         addr = acq->reg_sequence[acq->reg_seq_pos].reg;
66
67         acq->xfer_buf_out[0] = LWLA_WORD(CMD_READ_REG);
68         acq->xfer_buf_out[1] = LWLA_WORD(addr);
69
70         acq->xfer_out->length = 2 * sizeof(acq->xfer_buf_out[0]);
71 }
72
73 /* Decode the response to a register read request.
74  */
75 static int read_reg_response(struct acquisition_state *acq)
76 {
77         uint32_t value;
78
79         if (acq->xfer_in->actual_length != 4) {
80                 sr_err("Received size %d doesn't match expected size 4.",
81                        acq->xfer_in->actual_length);
82                 return SR_ERR;
83         }
84         value = LWLA_TO_UINT32(acq->xfer_buf_in[0]);
85         acq->reg_sequence[acq->reg_seq_pos].val = value;
86
87         return SR_OK;
88 }
89
90 /* Enter a new state and submit the corresponding request to the device.
91  */
92 static int submit_request(const struct sr_dev_inst *sdi,
93                           enum protocol_state state)
94 {
95         struct dev_context *devc;
96         struct acquisition_state *acq;
97         int ret;
98
99         devc = sdi->priv;
100         acq  = devc->acquisition;
101
102         devc->state = state;
103
104         acq->xfer_out->length = 0;
105         acq->reg_seq_pos = 0;
106         acq->reg_seq_len = 0;
107
108         /* Perform the model-specific action for the new state. */
109         ret = (*devc->model->prepare_request)(sdi);
110
111         if (ret != SR_OK) {
112                 devc->transfer_error = TRUE;
113                 return ret;
114         }
115
116         if (acq->reg_seq_pos < acq->reg_seq_len) {
117                 if ((state & STATE_EXPECT_RESPONSE) != 0)
118                         next_reg_read(acq);
119                 else
120                         next_reg_write(acq);
121         }
122
123         return submit_transfer(devc, acq->xfer_out);
124 }
125
126 /* Evaluate and act on the response to a capture status request.
127  */
128 static void handle_status_response(const struct sr_dev_inst *sdi)
129 {
130         struct dev_context *devc;
131         struct acquisition_state *acq;
132         unsigned int old_status;
133
134         devc = sdi->priv;
135         acq  = devc->acquisition;
136         old_status = acq->status;
137
138         if ((*devc->model->handle_response)(sdi) != SR_OK) {
139                 devc->transfer_error = TRUE;
140                 return;
141         }
142         devc->state = STATE_STATUS_WAIT;
143
144         sr_spew("Captured %u words, %" PRIu64 " ms, status 0x%02X.",
145                 acq->mem_addr_fill, acq->duration_now, acq->status);
146
147         if ((~old_status & acq->status & STATUS_TRIGGERED) != 0)
148                 sr_info("Capture triggered.");
149
150         if (acq->duration_now >= acq->duration_max) {
151                 sr_dbg("Time limit reached, stopping capture.");
152                 submit_request(sdi, STATE_STOP_CAPTURE);
153         } else if ((acq->status & STATUS_TRIGGERED) == 0) {
154                 sr_spew("Waiting for trigger.");
155         } else if ((acq->status & STATUS_MEM_AVAIL) == 0) {
156                 sr_dbg("Capture memory filled.");
157                 submit_request(sdi, STATE_LENGTH_REQUEST);
158         } else if ((acq->status & STATUS_CAPTURING) != 0) {
159                 sr_spew("Sampling in progress.");
160         }
161 }
162
163 /* Evaluate and act on the response to a capture length request.
164  */
165 static void handle_length_response(const struct sr_dev_inst *sdi)
166 {
167         struct dev_context *devc;
168         struct acquisition_state *acq;
169
170         devc = sdi->priv;
171         acq  = devc->acquisition;
172
173         if ((*devc->model->handle_response)(sdi) != SR_OK) {
174                 devc->transfer_error = TRUE;
175                 return;
176         }
177         acq->rle = RLE_STATE_DATA;
178         acq->sample = 0;
179         acq->run_len = 0;
180         acq->samples_done = 0;
181         acq->mem_addr_done = acq->mem_addr_next;
182         acq->out_index = 0;
183
184         if (acq->mem_addr_next >= acq->mem_addr_stop) {
185                 submit_request(sdi, STATE_READ_FINISH);
186                 return;
187         }
188         sr_dbg("%u words in capture buffer.",
189                acq->mem_addr_stop - acq->mem_addr_next);
190
191         submit_request(sdi, STATE_READ_PREPARE);
192 }
193
194 /* Evaluate and act on the response to a capture memory read request.
195  */
196 static void handle_read_response(const struct sr_dev_inst *sdi)
197 {
198         struct dev_context *devc;
199         struct acquisition_state *acq;
200         struct sr_datafeed_packet packet;
201         struct sr_datafeed_logic logic;
202         unsigned int end_addr;
203
204         devc = sdi->priv;
205         acq  = devc->acquisition;
206
207         /* Prepare session packet. */
208         packet.type    = SR_DF_LOGIC;
209         packet.payload = &logic;
210         logic.unitsize = (devc->model->num_channels + 7) / 8;
211         logic.data     = acq->out_packet;
212
213         end_addr = MIN(acq->mem_addr_next, acq->mem_addr_stop);
214         acq->in_index = 0;
215
216         /*
217          * Repeatedly call the model-specific read response handler until
218          * all data received in the transfer has been accounted for.
219          */
220         while (!devc->cancel_requested
221                         && (acq->run_len > 0 || acq->mem_addr_done < end_addr)
222                         && acq->samples_done < acq->samples_max) {
223
224                 if ((*devc->model->handle_response)(sdi) != SR_OK) {
225                         devc->transfer_error = TRUE;
226                         return;
227                 }
228                 if (acq->out_index * logic.unitsize >= PACKET_SIZE) {
229                         /* Send off full logic packet. */
230                         logic.length = acq->out_index * logic.unitsize;
231                         sr_session_send(sdi, &packet);
232                         acq->out_index = 0;
233                 }
234         }
235
236         if (!devc->cancel_requested
237                         && acq->samples_done < acq->samples_max
238                         && acq->mem_addr_next < acq->mem_addr_stop) {
239                 /* Request the next block. */
240                 submit_request(sdi, STATE_READ_REQUEST);
241                 return;
242         }
243
244         /* Send partially filled packet as it is the last one. */
245         if (!devc->cancel_requested && acq->out_index > 0) {
246                 logic.length = acq->out_index * logic.unitsize;
247                 sr_session_send(sdi, &packet);
248                 acq->out_index = 0;
249         }
250         submit_request(sdi, STATE_READ_FINISH);
251 }
252
253 /* Destroy and unset the acquisition state record.
254  */
255 static void clear_acquisition_state(const struct sr_dev_inst *sdi)
256 {
257         struct dev_context *devc;
258         struct acquisition_state *acq;
259
260         devc = sdi->priv;
261         acq  = devc->acquisition;
262
263         devc->acquisition = NULL;
264
265         if (acq) {
266                 libusb_free_transfer(acq->xfer_out);
267                 libusb_free_transfer(acq->xfer_in);
268                 g_free(acq);
269         }
270 }
271
272 /* USB I/O source callback.
273  */
274 static int transfer_event(int fd, int revents, void *cb_data)
275 {
276         const struct sr_dev_inst *sdi;
277         struct dev_context *devc;
278         struct drv_context *drvc;
279         struct timeval tv;
280         struct sr_datafeed_packet packet;
281         int ret;
282
283         (void)fd;
284
285         sdi  = cb_data;
286         devc = sdi->priv;
287         drvc = sdi->driver->context;
288
289         if (!devc || !drvc)
290                 return G_SOURCE_REMOVE;
291
292         /* Handle pending USB events without blocking. */
293         tv.tv_sec  = 0;
294         tv.tv_usec = 0;
295         ret = libusb_handle_events_timeout_completed(drvc->sr_ctx->libusb_ctx,
296                                                      &tv, NULL);
297         if (ret != 0) {
298                 sr_err("Event handling failed: %s.", libusb_error_name(ret));
299                 devc->transfer_error = TRUE;
300         }
301
302         if (!devc->transfer_error && devc->state == STATE_STATUS_WAIT) {
303                 if (devc->cancel_requested)
304                         submit_request(sdi, STATE_STOP_CAPTURE);
305                 else if (revents == 0) /* status poll timeout */
306                         submit_request(sdi, STATE_STATUS_REQUEST);
307         }
308
309         /* Stop processing events if an error occurred on a transfer. */
310         if (devc->transfer_error)
311                 devc->state = STATE_IDLE;
312
313         if (devc->state != STATE_IDLE)
314                 return G_SOURCE_CONTINUE;
315
316         sr_info("Acquisition stopped.");
317
318         /* We are done, clean up and send end packet to session bus. */
319         clear_acquisition_state(sdi);
320
321         packet.type = SR_DF_END;
322         packet.payload = NULL;
323         sr_session_send(sdi, &packet);
324
325         return G_SOURCE_REMOVE;
326 }
327
328 /* USB output transfer completion callback.
329  */
330 static void LIBUSB_CALL transfer_out_completed(struct libusb_transfer *transfer)
331 {
332         const struct sr_dev_inst *sdi;
333         struct dev_context *devc;
334         struct acquisition_state *acq;
335
336         sdi  = transfer->user_data;
337         devc = sdi->priv;
338         acq  = devc->acquisition;
339
340         if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
341                 sr_err("Transfer to device failed (state %d): %s.",
342                        devc->state, libusb_error_name(transfer->status));
343                 devc->transfer_error = TRUE;
344                 return;
345         }
346
347         /* If this was a read request, wait for the response. */
348         if ((devc->state & STATE_EXPECT_RESPONSE) != 0) {
349                 submit_transfer(devc, acq->xfer_in);
350                 return;
351         }
352         if (acq->reg_seq_pos < acq->reg_seq_len)
353                 acq->reg_seq_pos++; /* register write completed */
354
355         /* Repeat until all queued registers have been written. */
356         if (acq->reg_seq_pos < acq->reg_seq_len && !devc->cancel_requested) {
357                 next_reg_write(acq);
358                 submit_transfer(devc, acq->xfer_out);
359                 return;
360         }
361
362         switch (devc->state) {
363         case STATE_START_CAPTURE:
364                 sr_info("Acquisition started.");
365
366                 if (!devc->cancel_requested)
367                         devc->state = STATE_STATUS_WAIT;
368                 else
369                         submit_request(sdi, STATE_STOP_CAPTURE);
370                 break;
371         case STATE_STOP_CAPTURE:
372                 if (!devc->cancel_requested)
373                         submit_request(sdi, STATE_LENGTH_REQUEST);
374                 else
375                         devc->state = STATE_IDLE;
376                 break;
377         case STATE_READ_PREPARE:
378                 if (acq->mem_addr_next < acq->mem_addr_stop && !devc->cancel_requested)
379                         submit_request(sdi, STATE_READ_REQUEST);
380                 else
381                         submit_request(sdi, STATE_READ_FINISH);
382                 break;
383         case STATE_READ_FINISH:
384                 devc->state = STATE_IDLE;
385                 break;
386         default:
387                 sr_err("Unexpected device state %d.", devc->state);
388                 devc->transfer_error = TRUE;
389                 break;
390         }
391 }
392
393 /* USB input transfer completion callback.
394  */
395 static void LIBUSB_CALL transfer_in_completed(struct libusb_transfer *transfer)
396 {
397         const struct sr_dev_inst *sdi;
398         struct dev_context *devc;
399         struct acquisition_state *acq;
400
401         sdi  = transfer->user_data;
402         devc = sdi->priv;
403         acq  = devc->acquisition;
404
405         if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
406                 sr_err("Transfer from device failed (state %d): %s.",
407                        devc->state, libusb_error_name(transfer->status));
408                 devc->transfer_error = TRUE;
409                 return;
410         }
411         if ((devc->state & STATE_EXPECT_RESPONSE) == 0) {
412                 sr_err("Unexpected completion of input transfer (state %d).",
413                        devc->state);
414                 devc->transfer_error = TRUE;
415                 return;
416         }
417
418         if (acq->reg_seq_pos < acq->reg_seq_len && !devc->cancel_requested) {
419                 /* Complete register read sequence. */
420                 if (read_reg_response(acq) != SR_OK) {
421                         devc->transfer_error = TRUE;
422                         return;
423                 }
424                 /* Repeat until all queued registers have been read. */
425                 if (++acq->reg_seq_pos < acq->reg_seq_len) {
426                         next_reg_read(acq);
427                         submit_transfer(devc, acq->xfer_out);
428                         return;
429                 }
430         }
431
432         switch (devc->state) {
433         case STATE_STATUS_REQUEST:
434                 if (devc->cancel_requested)
435                         submit_request(sdi, STATE_STOP_CAPTURE);
436                 else
437                         handle_status_response(sdi);
438                 break;
439         case STATE_LENGTH_REQUEST:
440                 if (devc->cancel_requested)
441                         submit_request(sdi, STATE_READ_FINISH);
442                 else
443                         handle_length_response(sdi);
444                 break;
445         case STATE_READ_REQUEST:
446                 handle_read_response(sdi);
447                 break;
448         default:
449                 sr_err("Unexpected device state %d.", devc->state);
450                 devc->transfer_error = TRUE;
451                 break;
452         }
453 }
454
455 /* Set up the acquisition state record.
456  */
457 static int init_acquisition_state(const struct sr_dev_inst *sdi)
458 {
459         struct dev_context *devc;
460         struct sr_usb_dev_inst *usb;
461         struct acquisition_state *acq;
462
463         devc = sdi->priv;
464         usb  = sdi->conn;
465
466         if (devc->acquisition) {
467                 sr_err("Acquisition still in progress?");
468                 return SR_ERR;
469         }
470         if (devc->cfg_clock_source == CLOCK_INTERNAL && devc->samplerate == 0) {
471                 sr_err("Samplerate not set.");
472                 return SR_ERR;
473         }
474
475         acq = g_try_malloc0(sizeof(struct acquisition_state));
476         if (!acq)
477                 return SR_ERR_MALLOC;
478
479         acq->xfer_in = libusb_alloc_transfer(0);
480         if (!acq->xfer_in) {
481                 g_free(acq);
482                 return SR_ERR_MALLOC;
483         }
484         acq->xfer_out = libusb_alloc_transfer(0);
485         if (!acq->xfer_out) {
486                 libusb_free_transfer(acq->xfer_in);
487                 g_free(acq);
488                 return SR_ERR_MALLOC;
489         }
490
491         libusb_fill_bulk_transfer(acq->xfer_out, usb->devhdl, EP_COMMAND,
492                                   (unsigned char *)acq->xfer_buf_out, 0,
493                                   &transfer_out_completed,
494                                   (struct sr_dev_inst *)sdi, USB_TIMEOUT_MS);
495
496         libusb_fill_bulk_transfer(acq->xfer_in, usb->devhdl, EP_REPLY,
497                                   (unsigned char *)acq->xfer_buf_in,
498                                   sizeof(acq->xfer_buf_in),
499                                   &transfer_in_completed,
500                                   (struct sr_dev_inst *)sdi, USB_TIMEOUT_MS);
501
502         if (devc->limit_msec > 0) {
503                 acq->duration_max = devc->limit_msec;
504                 sr_info("Acquisition time limit %" PRIu64 " ms.",
505                         devc->limit_msec);
506         } else
507                 acq->duration_max = MAX_LIMIT_MSEC;
508
509         if (devc->limit_samples > 0) {
510                 acq->samples_max = devc->limit_samples;
511                 sr_info("Acquisition sample count limit %" PRIu64 ".",
512                         devc->limit_samples);
513         } else
514                 acq->samples_max = MAX_LIMIT_SAMPLES;
515
516         if (devc->cfg_clock_source == CLOCK_INTERNAL) {
517                 sr_info("Internal clock, samplerate %" PRIu64 ".",
518                         devc->samplerate);
519                 /* Ramp up clock speed to enable samplerates above 100 MS/s. */
520                 acq->clock_boost = (devc->samplerate > SR_MHZ(100));
521
522                 /* If only one of the limits is set, derive the other one. */
523                 if (devc->limit_msec == 0 && devc->limit_samples > 0)
524                         acq->duration_max = devc->limit_samples
525                                         * 1000 / devc->samplerate + 1;
526                 else if (devc->limit_samples == 0 && devc->limit_msec > 0)
527                         acq->samples_max = devc->limit_msec
528                                         * devc->samplerate / 1000;
529         } else {
530                 acq->clock_boost = TRUE;
531
532                 if (devc->cfg_clock_edge == EDGE_POSITIVE)
533                         sr_info("External clock, rising edge.");
534                 else
535                         sr_info("External clock, falling edge.");
536         }
537
538         acq->rle_enabled = devc->cfg_rle;
539         devc->acquisition = acq;
540
541         return SR_OK;
542 }
543
544 SR_PRIV int lwla_start_acquisition(const struct sr_dev_inst *sdi)
545 {
546         struct drv_context *drvc;
547         struct dev_context *devc;
548         int ret;
549         const int poll_interval_ms = 100;
550
551         drvc = sdi->driver->context;
552         devc = sdi->priv;
553
554         if (devc->state != STATE_IDLE) {
555                 sr_err("Not in idle state, cannot start acquisition.");
556                 return SR_ERR;
557         }
558         devc->cancel_requested = FALSE;
559         devc->transfer_error = FALSE;
560
561         ret = init_acquisition_state(sdi);
562         if (ret != SR_OK)
563                 return ret;
564
565         ret = (*devc->model->setup_acquisition)(sdi);
566         if (ret != SR_OK) {
567                 sr_err("Failed to set up device for acquisition.");
568                 clear_acquisition_state(sdi);
569                 return ret;
570         }
571         /* Register event source for asynchronous USB I/O. */
572         ret = usb_source_add(sdi->session, drvc->sr_ctx, poll_interval_ms,
573                              &transfer_event, (struct sr_dev_inst *)sdi);
574         if (ret != SR_OK) {
575                 clear_acquisition_state(sdi);
576                 return ret;
577         }
578         ret = submit_request(sdi, STATE_START_CAPTURE);
579
580         if (ret == SR_OK) {
581                 /* Send header packet to the session bus. */
582                 ret = std_session_send_df_header(sdi, LOG_PREFIX);
583         }
584         if (ret != SR_OK) {
585                 usb_source_remove(sdi->session, drvc->sr_ctx);
586                 clear_acquisition_state(sdi);
587         }
588
589         return ret;
590 }