]> sigrok.org Git - libsigrok.git/blob - hardware/openbench-logic-sniffer/ols.c
4f78ba5b4c7f84063b588ff8b9f988f4b32b4725
[libsigrok.git] / hardware / openbench-logic-sniffer / ols.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2010 Bert Vermeulen <bert@biot.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 <stdio.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #ifdef _WIN32
28 #include <windows.h>
29 #else
30 #include <termios.h>
31 #endif
32 #include <string.h>
33 #include <sys/time.h>
34 #include <inttypes.h>
35 #ifdef _WIN32
36 /* TODO */
37 #else
38 #include <arpa/inet.h>
39 #endif
40 #include <glib.h>
41 #include "sigrok.h"
42 #include "sigrok-internal.h"
43 #include "ols.h"
44
45 #ifdef _WIN32
46 #define O_NONBLOCK FIONBIO
47 #endif
48
49 static int capabilities[] = {
50         SR_HWCAP_LOGIC_ANALYZER,
51         SR_HWCAP_SAMPLERATE,
52         SR_HWCAP_CAPTURE_RATIO,
53         SR_HWCAP_LIMIT_SAMPLES,
54         SR_HWCAP_RLE,
55         0,
56 };
57
58 /* default supported samplerates, can be overridden by device metadata */
59 static struct sr_samplerates samplerates = {
60         SR_HZ(10),
61         SR_MHZ(200),
62         SR_HZ(1),
63         NULL,
64 };
65
66 /* List of struct sr_serial_device_instance */
67 static GSList *device_instances = NULL;
68
69 static int send_shortcommand(int fd, uint8_t command)
70 {
71         char buf[1];
72
73         sr_dbg("ols: sending cmd 0x%.2x", command);
74         buf[0] = command;
75         if (serial_write(fd, buf, 1) != 1)
76                 return SR_ERR;
77
78         return SR_OK;
79 }
80
81 static int send_longcommand(int fd, uint8_t command, uint32_t data)
82 {
83         char buf[5];
84
85         sr_dbg("ols: sending cmd 0x%.2x data 0x%.8x", command, data);
86         buf[0] = command;
87         buf[1] = (data & 0xff000000) >> 24;
88         buf[2] = (data & 0xff0000) >> 16;
89         buf[3] = (data & 0xff00) >> 8;
90         buf[4] = data & 0xff;
91         if (serial_write(fd, buf, 5) != 5)
92                 return SR_ERR;
93
94         return SR_OK;
95 }
96
97 static int configure_probes(struct ols_device *ols, GSList *probes)
98 {
99         struct sr_probe *probe;
100         GSList *l;
101         int probe_bit, stage, i;
102         char *tc;
103
104         ols->probe_mask = 0;
105         for (i = 0; i < NUM_TRIGGER_STAGES; i++) {
106                 ols->trigger_mask[i] = 0;
107                 ols->trigger_value[i] = 0;
108         }
109
110         ols->num_stages = 0;
111         for (l = probes; l; l = l->next) {
112                 probe = (struct sr_probe *)l->data;
113                 if (!probe->enabled)
114                         continue;
115
116                 /*
117                  * Set up the probe mask for later configuration into the
118                  * flag register.
119                  */
120                 probe_bit = 1 << (probe->index - 1);
121                 ols->probe_mask |= probe_bit;
122
123                 if (!probe->trigger)
124                         continue;
125
126                 /* Configure trigger mask and value. */
127                 stage = 0;
128                 for (tc = probe->trigger; tc && *tc; tc++) {
129                         ols->trigger_mask[stage] |= probe_bit;
130                         if (*tc == '1')
131                                 ols->trigger_value[stage] |= probe_bit;
132                         stage++;
133                         if (stage > 3)
134                                 /*
135                                  * TODO: Only supporting parallel mode, with
136                                  * up to 4 stages.
137                                  */
138                                 return SR_ERR;
139                 }
140                 if (stage > ols->num_stages)
141                         ols->num_stages = stage;
142         }
143
144         return SR_OK;
145 }
146
147 static uint32_t reverse16(uint32_t in)
148 {
149         uint32_t out;
150
151         out = (in & 0xff) << 8;
152         out |= (in & 0xff00) >> 8;
153         out |= (in & 0xff0000) << 8;
154         out |= (in & 0xff000000) >> 8;
155
156         return out;
157 }
158
159 static uint32_t reverse32(uint32_t in)
160 {
161         uint32_t out;
162
163         out = (in & 0xff) << 24;
164         out |= (in & 0xff00) << 8;
165         out |= (in & 0xff0000) >> 8;
166         out |= (in & 0xff000000) >> 24;
167
168         return out;
169 }
170
171 static struct ols_device *ols_device_new(void)
172 {
173         struct ols_device *ols;
174
175         /* TODO: Is 'ols' ever g_free()'d? */
176         if (!(ols = g_try_malloc0(sizeof(struct ols_device)))) {
177                 sr_err("ols: %s: ols malloc failed", __func__);
178                 return NULL;
179         }
180
181         ols->trigger_at = -1;
182         ols->probe_mask = 0xffffffff;
183         ols->cur_samplerate = SR_KHZ(200);
184         ols->period_ps = 5000000;
185
186         return ols;
187 }
188
189 static struct sr_device_instance *get_metadata(int fd)
190 {
191         struct sr_device_instance *sdi;
192         struct ols_device *ols;
193         uint32_t tmp_int;
194         uint8_t key, type, token;
195         GString *tmp_str, *devicename, *version;
196         gchar tmp_c;
197
198         sdi = sr_device_instance_new(0, SR_ST_INACTIVE, NULL, NULL, NULL);
199         ols = ols_device_new();
200         sdi->priv = ols;
201
202         devicename = g_string_new("");
203         version = g_string_new("");
204
205         key = 0xff;
206         while (key) {
207                 if (serial_read(fd, &key, 1) != 1 || key == 0x00)
208                         break;
209                 type = key >> 5;
210                 token = key & 0x1f;
211                 switch (type) {
212                 case 0:
213                         /* NULL-terminated string */
214                         tmp_str = g_string_new("");
215                         while (serial_read(fd, &tmp_c, 1) == 1 && tmp_c != '\0')
216                                 g_string_append_c(tmp_str, tmp_c);
217                         sr_dbg("ols: got metadata key 0x%.2x value '%s'",
218                                key, tmp_str->str);
219                         switch (token) {
220                         case 0x01:
221                                 /* Device name */
222                                 devicename = g_string_append(devicename, tmp_str->str);
223                                 break;
224                         case 0x02:
225                                 /* FPGA firmware version */
226                                 if (version->len)
227                                         g_string_append(version, ", ");
228                                 g_string_append(version, "FPGA version ");
229                                 g_string_append(version, tmp_str->str);
230                                 break;
231                         case 0x03:
232                                 /* Ancillary version */
233                                 if (version->len)
234                                         g_string_append(version, ", ");
235                                 g_string_append(version, "Ancillary version ");
236                                 g_string_append(version, tmp_str->str);
237                                 break;
238                         default:
239                                 sr_info("ols: unknown token 0x%.2x: '%s'",
240                                         token, tmp_str->str);
241                                 break;
242                         }
243                         g_string_free(tmp_str, TRUE);
244                         break;
245                 case 1:
246                         /* 32-bit unsigned integer */
247                         if (serial_read(fd, &tmp_int, 4) != 4)
248                                 break;
249                         tmp_int = reverse32(tmp_int);
250                         sr_dbg("ols: got metadata key 0x%.2x value 0x%.8x",
251                                key, tmp_int);
252                         switch (token) {
253                         case 0x00:
254                                 /* Number of usable probes */
255                                 ols->num_probes = tmp_int;
256                                 break;
257                         case 0x01:
258                                 /* Amount of sample memory available (bytes) */
259                                 ols->max_samples = tmp_int;
260                                 break;
261                         case 0x02:
262                                 /* Amount of dynamic memory available (bytes) */
263                                 /* what is this for? */
264                                 break;
265                         case 0x03:
266                                 /* Maximum sample rate (hz) */
267                                 ols->max_samplerate = tmp_int;
268                                 break;
269                         case 0x04:
270                                 /* protocol version */
271                                 ols->protocol_version = tmp_int;
272                                 break;
273                         default:
274                                 sr_info("ols: unknown token 0x%.2x: 0x%.8x",
275                                         token, tmp_int);
276                                 break;
277                         }
278                         break;
279                 case 2:
280                         /* 8-bit unsigned integer */
281                         if (serial_read(fd, &tmp_c, 1) != 1)
282                                 break;
283                         sr_dbg("ols: got metadata key 0x%.2x value 0x%.2x",
284                                key, tmp_c);
285                         switch (token) {
286                         case 0x00:
287                                 /* Number of usable probes */
288                                 ols->num_probes = tmp_c;
289                                 break;
290                         case 0x01:
291                                 /* protocol version */
292                                 ols->protocol_version = tmp_c;
293                                 break;
294                         default:
295                                 sr_info("ols: unknown token 0x%.2x: 0x%.2x",
296                                         token, tmp_c);
297                                 break;
298                         }
299                         break;
300                 default:
301                         /* unknown type */
302                         break;
303                 }
304         }
305
306         sdi->model = devicename->str;
307         sdi->version = version->str;
308         g_string_free(devicename, FALSE);
309         g_string_free(version, FALSE);
310
311         return sdi;
312 }
313
314 static int hw_init(const char *deviceinfo)
315 {
316         struct sr_device_instance *sdi;
317         struct ols_device *ols;
318         GSList *ports, *l;
319         GPollFD *fds, probefd;
320         int devcnt, final_devcnt, num_ports, fd, ret, i;
321         char buf[8], **device_names, **serial_params;
322
323         final_devcnt = 0;
324
325         if (deviceinfo)
326                 ports = g_slist_append(NULL, strdup(deviceinfo));
327         else
328                 /* No specific device given, so scan all serial ports. */
329                 ports = list_serial_ports();
330
331         num_ports = g_slist_length(ports);
332
333         if (!(fds = g_try_malloc0(num_ports * sizeof(GPollFD)))) {
334                 sr_err("ols: %s: fds malloc failed", __func__);
335                 goto hw_init_free_ports; /* TODO: SR_ERR_MALLOC. */
336         }
337
338         if (!(device_names = g_try_malloc(num_ports * sizeof(char *)))) {
339                 sr_err("ols: %s: device_names malloc failed", __func__);
340                 goto hw_init_free_fds; /* TODO: SR_ERR_MALLOC. */
341         }
342
343         if (!(serial_params = g_try_malloc(num_ports * sizeof(char *)))) {
344                 sr_err("ols: %s: serial_params malloc failed", __func__);
345                 goto hw_init_free_device_names; /* TODO: SR_ERR_MALLOC. */
346         }
347
348         devcnt = 0;
349         for (l = ports; l; l = l->next) {
350                 /* The discovery procedure is like this: first send the Reset
351                  * command (0x00) 5 times, since the device could be anywhere
352                  * in a 5-byte command. Then send the ID command (0x02).
353                  * If the device responds with 4 bytes ("OLS1" or "SLA1"), we
354                  * have a match.
355                  *
356                  * Since it may take the device a while to respond at 115Kb/s,
357                  * we do all the sending first, then wait for all of them to
358                  * respond with g_poll().
359                  */
360                 sr_info("ols: probing %s...", (char *)l->data);
361                 fd = serial_open(l->data, O_RDWR | O_NONBLOCK);
362                 if (fd != -1) {
363                         serial_params[devcnt] = serial_backup_params(fd);
364                         serial_set_params(fd, 115200, 8, 0, 1, 2);
365                         ret = SR_OK;
366                         for (i = 0; i < 5; i++) {
367                                 if ((ret = send_shortcommand(fd,
368                                         CMD_RESET)) != SR_OK) {
369                                         /* Serial port is not writable. */
370                                         break;
371                                 }
372                         }
373                         if (ret != SR_OK) {
374                                 serial_restore_params(fd,
375                                         serial_params[devcnt]);
376                                 serial_close(fd);
377                                 continue;
378                         }
379                         send_shortcommand(fd, CMD_ID);
380                         fds[devcnt].fd = fd;
381                         fds[devcnt].events = G_IO_IN;
382                         device_names[devcnt] = strdup(l->data);
383                         devcnt++;
384                 }
385                 free(l->data);
386         }
387
388         /* 2ms isn't enough for reliable transfer with pl2303, let's try 10 */
389         usleep(10000);
390
391         g_poll(fds, devcnt, 1);
392
393         for (i = 0; i < devcnt; i++) {
394                 if (fds[i].revents != G_IO_IN)
395                         continue;
396                 if (serial_read(fds[i].fd, buf, 4) != 4)
397                         continue;
398                 if (strncmp(buf, "1SLO", 4) && strncmp(buf, "1ALS", 4))
399                         continue;
400
401                 /* definitely using the OLS protocol, check if it supports
402                  * the metadata command
403                  */
404                 send_shortcommand(fds[i].fd, CMD_METADATA);
405                 probefd.fd = fds[i].fd;
406                 probefd.events = G_IO_IN;
407                 if (g_poll(&probefd, 1, 10) > 0) {
408                         /* got metadata */
409                         sdi = get_metadata(fds[i].fd);
410                         sdi->index = final_devcnt;
411                 } else {
412                         /* not an OLS -- some other board that uses the sump protocol */
413                         sdi = sr_device_instance_new(final_devcnt, SR_ST_INACTIVE,
414                                         "Sump", "Logic Analyzer", "v1.0");
415                         ols = ols_device_new();
416                         ols->num_probes = 32;
417                         sdi->priv = ols;
418                 }
419                 sdi->serial = sr_serial_device_instance_new(device_names[i], -1);
420                 device_instances = g_slist_append(device_instances, sdi);
421                 final_devcnt++;
422                 serial_close(fds[i].fd);
423                 fds[i].fd = 0;
424         }
425
426         /* clean up after all the probing */
427         for (i = 0; i < devcnt; i++) {
428                 if (fds[i].fd != 0) {
429                         serial_restore_params(fds[i].fd, serial_params[i]);
430                         serial_close(fds[i].fd);
431                 }
432                 free(serial_params[i]);
433                 free(device_names[i]);
434         }
435
436         g_free(serial_params);
437 hw_init_free_device_names:
438         g_free(device_names);
439 hw_init_free_fds:
440         g_free(fds);
441 hw_init_free_ports:
442         g_slist_free(ports);
443
444         return final_devcnt;
445 }
446
447 static int hw_opendev(int device_index)
448 {
449         struct sr_device_instance *sdi;
450
451         if (!(sdi = sr_get_device_instance(device_instances, device_index)))
452                 return SR_ERR;
453
454         sdi->serial->fd = serial_open(sdi->serial->port, O_RDWR);
455         if (sdi->serial->fd == -1)
456                 return SR_ERR;
457
458         sdi->status = SR_ST_ACTIVE;
459
460         return SR_OK;
461 }
462
463 static int hw_closedev(int device_index)
464 {
465         struct sr_device_instance *sdi;
466
467         if (!(sdi = sr_get_device_instance(device_instances, device_index))) {
468                 sr_err("ols: %s: sdi was NULL", __func__);
469                 return SR_ERR; /* TODO: SR_ERR_ARG? */
470         }
471
472         /* TODO */
473         if (sdi->serial->fd != -1) {
474                 serial_close(sdi->serial->fd);
475                 sdi->serial->fd = -1;
476                 sdi->status = SR_ST_INACTIVE;
477         }
478
479         return SR_OK;
480 }
481
482 static void hw_cleanup(void)
483 {
484         GSList *l;
485         struct sr_device_instance *sdi;
486
487         /* Properly close and free all devices. */
488         for (l = device_instances; l; l = l->next) {
489                 sdi = l->data;
490                 if (sdi->serial->fd != -1)
491                         serial_close(sdi->serial->fd);
492                 sr_device_instance_free(sdi);
493         }
494         g_slist_free(device_instances);
495         device_instances = NULL;
496 }
497
498 static void *hw_get_device_info(int device_index, int device_info_id)
499 {
500         struct sr_device_instance *sdi;
501         struct ols_device *ols;
502         void *info;
503
504         if (!(sdi = sr_get_device_instance(device_instances, device_index)))
505                 return NULL;
506         ols = sdi->priv;
507
508         info = NULL;
509         switch (device_info_id) {
510         case SR_DI_INSTANCE:
511                 info = sdi;
512                 break;
513         case SR_DI_NUM_PROBES:
514                 info = GINT_TO_POINTER(NUM_PROBES);
515                 break;
516         case SR_DI_SAMPLERATES:
517                 info = &samplerates;
518                 break;
519         case SR_DI_TRIGGER_TYPES:
520                 info = (char *)TRIGGER_TYPES;
521                 break;
522         case SR_DI_CUR_SAMPLERATE:
523                 info = &ols->cur_samplerate;
524                 break;
525         }
526
527         return info;
528 }
529
530 static int hw_get_status(int device_index)
531 {
532         struct sr_device_instance *sdi;
533
534         if (!(sdi = sr_get_device_instance(device_instances, device_index)))
535                 return SR_ST_NOT_FOUND;
536
537         return sdi->status;
538 }
539
540 static int *hw_get_capabilities(void)
541 {
542         return capabilities;
543 }
544
545 static int set_configuration_samplerate(struct sr_device_instance *sdi,
546                                         uint64_t samplerate)
547 {
548         struct ols_device *ols;
549
550         ols = sdi->priv;
551         if (ols->max_samplerate) {
552                 if (samplerate > ols->max_samplerate)
553                         return SR_ERR_SAMPLERATE;
554         } else if (samplerate < samplerates.low || samplerate > samplerates.high)
555                 return SR_ERR_SAMPLERATE;
556
557         if (samplerate > CLOCK_RATE) {
558                 ols->flag_reg |= FLAG_DEMUX;
559                 ols->cur_samplerate_divider = (CLOCK_RATE * 2 / samplerate) - 1;
560         } else {
561                 ols->flag_reg &= ~FLAG_DEMUX;
562                 ols->cur_samplerate_divider = (CLOCK_RATE / samplerate) - 1;
563         }
564
565         /* Calculate actual samplerate used and complain if it is different
566          * from the requested.
567          */
568         ols->cur_samplerate = CLOCK_RATE / (ols->cur_samplerate_divider + 1);
569         if(ols->flag_reg & FLAG_DEMUX)
570                 ols->cur_samplerate *= 2;
571         ols->period_ps = 1000000000000 / ols->cur_samplerate;
572         if(ols->cur_samplerate != samplerate)
573                 sr_warn("ols: can't match samplerate %" PRIu64 ", using %" PRIu64, 
574                         samplerate, ols->cur_samplerate);
575
576         return SR_OK;
577 }
578
579 static int hw_set_configuration(int device_index, int capability, void *value)
580 {
581         struct sr_device_instance *sdi;
582         struct ols_device *ols;
583         int ret;
584         uint64_t *tmp_u64;
585
586         if (!(sdi = sr_get_device_instance(device_instances, device_index)))
587                 return SR_ERR;
588         ols = sdi->priv;
589
590         if (sdi->status != SR_ST_ACTIVE)
591                 return SR_ERR;
592
593         switch (capability) {
594         case SR_HWCAP_SAMPLERATE:
595                 tmp_u64 = value;
596                 ret = set_configuration_samplerate(sdi, *tmp_u64);
597                 break;
598         case SR_HWCAP_PROBECONFIG:
599                 ret = configure_probes(ols, (GSList *) value);
600                 break;
601         case SR_HWCAP_LIMIT_SAMPLES:
602                 tmp_u64 = value;
603                 if (*tmp_u64 < MIN_NUM_SAMPLES)
604                         return SR_ERR;
605                 if (*tmp_u64 > ols->max_samples)
606                         sr_warn("ols: sample limit exceeds hw max");
607                 ols->limit_samples = *tmp_u64;
608                 sr_info("ols: sample limit %" PRIu64, ols->limit_samples);
609                 ret = SR_OK;
610                 break;
611         case SR_HWCAP_CAPTURE_RATIO:
612                 tmp_u64 = value;
613                 ols->capture_ratio = *tmp_u64;
614                 if (ols->capture_ratio < 0 || ols->capture_ratio > 100) {
615                         ols->capture_ratio = 0;
616                         ret = SR_ERR;
617                 } else
618                         ret = SR_OK;
619                 break;
620         case SR_HWCAP_RLE:
621                 if (GPOINTER_TO_INT(value)) {
622                         sr_info("ols: enabling RLE");
623                         ols->flag_reg |= FLAG_RLE;
624                 }
625                 ret = SR_OK;
626                 break;
627         default:
628                 ret = SR_ERR;
629         }
630
631         return ret;
632 }
633
634 static int receive_data(int fd, int revents, void *session_data)
635 {
636         struct sr_datafeed_packet packet;
637         struct sr_datafeed_logic logic;
638         struct sr_device_instance *sdi;
639         struct ols_device *ols;
640         GSList *l;
641         int num_channels, offset, i, j;
642         unsigned char byte;
643
644         /* find this device's ols_device struct by its fd */
645         ols = NULL;
646         for (l = device_instances; l; l = l->next) {
647                 sdi = l->data;
648                 if (sdi->serial->fd == fd) {
649                         ols = sdi->priv;
650                         break;
651                 }
652         }
653         if (!ols)
654                 /* shouldn't happen */
655                 return TRUE;
656
657         if (ols->num_transfers++ == 0) {
658                 /*
659                  * First time round, means the device started sending data,
660                  * and will not stop until done. If it stops sending for
661                  * longer than it takes to send a byte, that means it's
662                  * finished. We'll double that to 30ms to be sure...
663                  */
664                 sr_source_remove(fd);
665                 sr_source_add(fd, G_IO_IN, 30, receive_data, session_data);
666                 ols->raw_sample_buf = g_try_malloc(ols->limit_samples * 4);
667                 if (!ols->raw_sample_buf) {
668                         sr_err("ols: %s: ols->raw_sample_buf malloc failed",
669                                __func__);
670                         return FALSE;
671                 }
672                 /* fill with 1010... for debugging */
673                 memset(ols->raw_sample_buf, 0x82, ols->limit_samples * 4);
674         }
675
676         num_channels = 0;
677         for (i = 0x20; i > 0x02; i /= 2) {
678                 if ((ols->flag_reg & i) == 0)
679                         num_channels++;
680         }
681
682         if (revents == G_IO_IN) {
683                 if (serial_read(fd, &byte, 1) != 1)
684                         return FALSE;
685
686                 /* Ignore it if we've read enough. */
687                 if (ols->num_samples >= ols->limit_samples)
688                         return TRUE;
689
690                 ols->sample[ols->num_bytes++] = byte;
691                 sr_dbg("ols: received byte 0x%.2x", byte);
692                 if (ols->num_bytes == num_channels) {
693                         /* Got a full sample. */
694                         sr_dbg("ols: received sample 0x%.*x",
695                                ols->num_bytes * 2, *(int *)ols->sample);
696                         if (ols->flag_reg & FLAG_RLE) {
697                                 /*
698                                  * In RLE mode -1 should never come in as a
699                                  * sample, because bit 31 is the "count" flag.
700                                  */
701                                 if (ols->sample[ols->num_bytes - 1] & 0x80) {
702                                         ols->sample[ols->num_bytes - 1] &= 0x7f;
703                                         /*
704                                          * FIXME: This will only work on
705                                          * little-endian systems.
706                                          */
707                                         ols->rle_count = *(int *)(ols->sample);
708                                         sr_dbg("ols: RLE count = %d", ols->rle_count);
709                                         ols->num_bytes = 0;
710                                         return TRUE;
711                                 }
712                         }
713                         ols->num_samples += ols->rle_count + 1;
714                         if (ols->num_samples > ols->limit_samples) {
715                                 /* Save us from overrunning the buffer. */
716                                 ols->rle_count -= ols->num_samples - ols->limit_samples;
717                                 ols->num_samples = ols->limit_samples;
718                         }
719
720                         if (num_channels < 4) {
721                                 /*
722                                  * Some channel groups may have been turned
723                                  * off, to speed up transfer between the
724                                  * hardware and the PC. Expand that here before
725                                  * submitting it over the session bus --
726                                  * whatever is listening on the bus will be
727                                  * expecting a full 32-bit sample, based on
728                                  * the number of probes.
729                                  */
730                                 j = 0;
731                                 memset(ols->tmp_sample, 0, 4);
732                                 for (i = 0; i < 4; i++) {
733                                         if (((ols->flag_reg >> 2) & (1 << i)) == 0) {
734                                                 /*
735                                                  * This channel group was
736                                                  * enabled, copy from received
737                                                  * sample.
738                                                  */
739                                                 ols->tmp_sample[i] = ols->sample[j++];
740                                         }
741                                 }
742                                 memcpy(ols->sample, ols->tmp_sample, 4);
743                                 sr_dbg("ols: full sample 0x%.8x", *(int *)ols->sample);
744                         }
745
746                         /* the OLS sends its sample buffer backwards.
747                          * store it in reverse order here, so we can dump
748                          * this on the session bus later.
749                          */
750                         offset = (ols->limit_samples - ols->num_samples) * 4;
751                         for (i = 0; i <= ols->rle_count; i++) {
752                                 memcpy(ols->raw_sample_buf + offset + (i * 4),
753                                        ols->sample, 4);
754                         }
755                         memset(ols->sample, 0, 4);
756                         ols->num_bytes = 0;
757                         ols->rle_count = 0;
758                 }
759         } else {
760                 /*
761                  * This is the main loop telling us a timeout was reached, or
762                  * we've acquired all the samples we asked for -- we're done.
763                  * Send the (properly-ordered) buffer to the frontend.
764                  */
765                 if (ols->trigger_at != -1) {
766                         /* a trigger was set up, so we need to tell the frontend
767                          * about it.
768                          */
769                         if (ols->trigger_at > 0) {
770                                 /* there are pre-trigger samples, send those first */
771                                 packet.type = SR_DF_LOGIC;
772                                 packet.timeoffset = 0;
773                                 packet.duration = ols->trigger_at * ols->period_ps;
774                                 packet.payload = &logic;
775                                 logic.length = ols->trigger_at * 4;
776                                 logic.unitsize = 4;
777                                 logic.data = ols->raw_sample_buf +
778                                         (ols->limit_samples - ols->num_samples) * 4;
779                                 sr_session_bus(session_data, &packet);
780                         }
781
782                         /* send the trigger */
783                         packet.type = SR_DF_TRIGGER;
784                         packet.timeoffset = ols->trigger_at * ols->period_ps;
785                         packet.duration = 0;
786                         sr_session_bus(session_data, &packet);
787
788                         /* send post-trigger samples */
789                         packet.type = SR_DF_LOGIC;
790                         packet.timeoffset = ols->trigger_at * ols->period_ps;
791                         packet.duration = (ols->num_samples - ols->trigger_at) * ols->period_ps;
792                         packet.payload = &logic;
793                         logic.length = (ols->num_samples * 4) - (ols->trigger_at * 4);
794                         logic.unitsize = 4;
795                         logic.data = ols->raw_sample_buf + ols->trigger_at * 4 +
796                                 (ols->limit_samples - ols->num_samples) * 4;
797                         sr_session_bus(session_data, &packet);
798                 } else {
799                         /* no trigger was used */
800                         packet.type = SR_DF_LOGIC;
801                         packet.timeoffset = 0;
802                         packet.duration = ols->num_samples * ols->period_ps;
803                         packet.payload = &logic;
804                         logic.length = ols->num_samples * 4;
805                         logic.unitsize = 4;
806                         logic.data = ols->raw_sample_buf +
807                                 (ols->limit_samples - ols->num_samples) * 4;
808                         sr_session_bus(session_data, &packet);
809                 }
810                 g_free(ols->raw_sample_buf);
811
812                 serial_flush(fd);
813                 serial_close(fd);
814                 packet.type = SR_DF_END;
815                 packet.timeoffset = ols->num_samples * ols->period_ps;
816                 packet.duration = 0;
817                 sr_session_bus(session_data, &packet);
818         }
819
820         return TRUE;
821 }
822
823 static int hw_start_acquisition(int device_index, gpointer session_data)
824 {
825         struct sr_datafeed_packet *packet;
826         struct sr_datafeed_header *header;
827         struct sr_device_instance *sdi;
828         struct ols_device *ols;
829         uint32_t trigger_config[4];
830         uint32_t data;
831         uint16_t readcount, delaycount;
832         uint8_t changrp_mask;
833         int num_channels;
834         int i;
835
836         if (!(sdi = sr_get_device_instance(device_instances, device_index)))
837                 return SR_ERR;
838
839         ols = sdi->priv;
840
841         if (sdi->status != SR_ST_ACTIVE)
842                 return SR_ERR;
843
844         /*
845          * Enable/disable channel groups in the flag register according to the
846          * probe mask. Calculate this here, because num_channels is needed
847          * to limit readcount.
848          */
849         changrp_mask = 0;
850         num_channels = 0;
851         for (i = 0; i < 4; i++) {
852                 if (ols->probe_mask & (0xff << (i * 8))) {
853                         changrp_mask |= (1 << i);
854                         num_channels++;
855                 }
856         }
857
858         /*
859          * Limit readcount to prevent reading past the end of the hardware
860          * buffer.
861          */
862         readcount = MIN(ols->max_samples / num_channels, ols->limit_samples) / 4;
863
864         memset(trigger_config, 0, 16);
865         trigger_config[ols->num_stages - 1] |= 0x08;
866         if (ols->trigger_mask[0]) {
867                 delaycount = readcount * (1 - ols->capture_ratio / 100.0);
868                 ols->trigger_at = (readcount - delaycount) * 4 - ols->num_stages;
869
870                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_MASK_0,
871                         reverse32(ols->trigger_mask[0])) != SR_OK)
872                         return SR_ERR;
873                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_VALUE_0,
874                         reverse32(ols->trigger_value[0])) != SR_OK)
875                         return SR_ERR;
876                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_CONFIG_0,
877                         trigger_config[0]) != SR_OK)
878                         return SR_ERR;
879
880                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_MASK_1,
881                         reverse32(ols->trigger_mask[1])) != SR_OK)
882                         return SR_ERR;
883                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_VALUE_1,
884                         reverse32(ols->trigger_value[1])) != SR_OK)
885                         return SR_ERR;
886                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_CONFIG_1,
887                         trigger_config[1]) != SR_OK)
888                         return SR_ERR;
889
890                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_MASK_2,
891                         reverse32(ols->trigger_mask[2])) != SR_OK)
892                         return SR_ERR;
893                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_VALUE_2,
894                         reverse32(ols->trigger_value[2])) != SR_OK)
895                         return SR_ERR;
896                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_CONFIG_2,
897                         trigger_config[2]) != SR_OK)
898                         return SR_ERR;
899
900                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_MASK_3,
901                         reverse32(ols->trigger_mask[3])) != SR_OK)
902                         return SR_ERR;
903                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_VALUE_3,
904                         reverse32(ols->trigger_value[3])) != SR_OK)
905                         return SR_ERR;
906                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_CONFIG_3,
907                         trigger_config[3]) != SR_OK)
908                         return SR_ERR;
909         } else {
910                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_MASK_0,
911                                 ols->trigger_mask[0]) != SR_OK)
912                         return SR_ERR;
913                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_VALUE_0,
914                                 ols->trigger_value[0]) != SR_OK)
915                         return SR_ERR;
916                 if (send_longcommand(sdi->serial->fd, CMD_SET_TRIGGER_CONFIG_0,
917                      0x00000008) != SR_OK)
918                         return SR_ERR;
919                 delaycount = readcount;
920         }
921
922         sr_info("ols: setting samplerate to %" PRIu64 " Hz (divider %u, "
923                 "demux %s)", ols->cur_samplerate, ols->cur_samplerate_divider,
924                 ols->flag_reg & FLAG_DEMUX ? "on" : "off");
925         if (send_longcommand(sdi->serial->fd, CMD_SET_DIVIDER,
926                         reverse32(ols->cur_samplerate_divider)) != SR_OK)
927                 return SR_ERR;
928
929         /* Send sample limit and pre/post-trigger capture ratio. */
930         data = ((readcount - 1) & 0xffff) << 16;
931         data |= (delaycount - 1) & 0xffff;
932         if (send_longcommand(sdi->serial->fd, CMD_CAPTURE_SIZE, reverse16(data)) != SR_OK)
933                 return SR_ERR;
934
935         /* The flag register wants them here, and 1 means "disable channel". */
936         ols->flag_reg |= ~(changrp_mask << 2) & 0x3c;
937         ols->flag_reg |= FLAG_FILTER;
938         ols->rle_count = 0;
939         data = (ols->flag_reg << 24) | ((ols->flag_reg << 8) & 0xff0000);
940         if (send_longcommand(sdi->serial->fd, CMD_SET_FLAGS, data) != SR_OK)
941                 return SR_ERR;
942
943         /* Start acquisition on the device. */
944         if (send_shortcommand(sdi->serial->fd, CMD_RUN) != SR_OK)
945                 return SR_ERR;
946
947         sr_source_add(sdi->serial->fd, G_IO_IN, -1, receive_data,
948                       session_data);
949
950         if (!(packet = g_try_malloc(sizeof(struct sr_datafeed_packet)))) {
951                 sr_err("ols: %s: packet malloc failed", __func__);
952                 return SR_ERR_MALLOC;
953         }
954
955         if (!(header = g_try_malloc(sizeof(struct sr_datafeed_header)))) {
956                 sr_err("ols: %s: header malloc failed", __func__);
957                 g_free(packet);
958                 return SR_ERR_MALLOC;
959         }
960
961         /* Send header packet to the session bus. */
962         packet->type = SR_DF_HEADER;
963         packet->payload = (unsigned char *)header;
964         header->feed_version = 1;
965         gettimeofday(&header->starttime, NULL);
966         header->samplerate = ols->cur_samplerate;
967         header->num_logic_probes = NUM_PROBES;
968         header->num_analog_probes = 0;
969         sr_session_bus(session_data, packet);
970
971         g_free(header);
972         g_free(packet);
973
974         return SR_OK;
975 }
976
977 static void hw_stop_acquisition(int device_index, gpointer session_device_id)
978 {
979         struct sr_datafeed_packet packet;
980
981         /* Avoid compiler warnings. */
982         (void)device_index;
983
984         packet.type = SR_DF_END;
985         sr_session_bus(session_device_id, &packet);
986 }
987
988 struct sr_device_plugin ols_plugin_info = {
989         .name = "ols",
990         .longname = "Openbench Logic Sniffer",
991         .api_version = 1,
992         .init = hw_init,
993         .cleanup = hw_cleanup,
994         .opendev = hw_opendev,
995         .closedev = hw_closedev,
996         .get_device_info = hw_get_device_info,
997         .get_status = hw_get_status,
998         .get_capabilities = hw_get_capabilities,
999         .set_configuration = hw_set_configuration,
1000         .start_acquisition = hw_start_acquisition,
1001         .stop_acquisition = hw_stop_acquisition,
1002 };