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