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