]> sigrok.org Git - libsigrok.git/blob - src/session.c
session: Compile USB-specific code only if available
[libsigrok.git] / src / session.c
1 /*
2  * This file is part of the libsigrok 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 <errno.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <glib.h>
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
28
29 /** @cond PRIVATE */
30 #define LOG_PREFIX "session"
31 /** @endcond */
32
33 /**
34  * @file
35  *
36  * Creating, using, or destroying libsigrok sessions.
37  */
38
39 /**
40  * @defgroup grp_session Session handling
41  *
42  * Creating, using, or destroying libsigrok sessions.
43  *
44  * @{
45  */
46
47 struct source {
48         int64_t timeout;        /* microseconds */
49         int64_t due;            /* microseconds */
50
51         sr_receive_data_callback cb;
52         void *cb_data;
53
54         /* This is used to keep track of the object (fd, pollfd or channel) which is
55          * being polled and will be used to match the source when removing it again.
56          */
57         gintptr poll_object;
58
59         /* Number of fds to poll for this source. This will be 0 for timer
60          * sources, 1 for normal I/O sources, and 1 or more for libusb I/O
61          * sources on Unix platforms.
62          */
63         int num_fds;
64
65         gboolean triggered;
66 };
67
68 struct datafeed_callback {
69         sr_datafeed_callback cb;
70         void *cb_data;
71 };
72
73 /**
74  * Create a new session.
75  *
76  * @param ctx         The context in which to create the new session.
77  * @param new_session This will contain a pointer to the newly created
78  *                    session if the return value is SR_OK, otherwise the value
79  *                    is undefined and should not be used. Must not be NULL.
80  *
81  * @retval SR_OK Success.
82  * @retval SR_ERR_ARG Invalid argument.
83  *
84  * @since 0.4.0
85  */
86 SR_API int sr_session_new(struct sr_context *ctx,
87                 struct sr_session **new_session)
88 {
89         struct sr_session *session;
90
91         if (!new_session)
92                 return SR_ERR_ARG;
93
94         session = g_malloc0(sizeof(struct sr_session));
95
96         session->ctx = ctx;
97
98         session->sources = g_array_new(FALSE, FALSE, sizeof(struct source));
99         session->pollfds = g_array_new(FALSE, FALSE, sizeof(GPollFD));
100
101         g_mutex_init(&session->stop_mutex);
102
103         *new_session = session;
104
105         return SR_OK;
106 }
107
108 /**
109  * Destroy a session.
110  * This frees up all memory used by the session.
111  *
112  * @param session The session to destroy. Must not be NULL.
113  *
114  * @retval SR_OK Success.
115  * @retval SR_ERR_ARG Invalid session passed.
116  *
117  * @since 0.4.0
118  */
119 SR_API int sr_session_destroy(struct sr_session *session)
120 {
121         if (!session) {
122                 sr_err("%s: session was NULL", __func__);
123                 return SR_ERR_ARG;
124         }
125
126         sr_session_dev_remove_all(session);
127         g_mutex_clear(&session->stop_mutex);
128         if (session->trigger)
129                 sr_trigger_free(session->trigger);
130
131         g_slist_free_full(session->owned_devs, (GDestroyNotify)sr_dev_inst_free);
132
133         g_array_unref(session->pollfds);
134         g_array_unref(session->sources);
135
136         g_free(session);
137
138         return SR_OK;
139 }
140
141 /**
142  * Remove all the devices from a session.
143  *
144  * The session itself (i.e., the struct sr_session) is not free'd and still
145  * exists after this function returns.
146  *
147  * @param session The session to use. Must not be NULL.
148  *
149  * @retval SR_OK Success.
150  * @retval SR_ERR_BUG Invalid session passed.
151  *
152  * @since 0.4.0
153  */
154 SR_API int sr_session_dev_remove_all(struct sr_session *session)
155 {
156         struct sr_dev_inst *sdi;
157         GSList *l;
158
159         if (!session) {
160                 sr_err("%s: session was NULL", __func__);
161                 return SR_ERR_ARG;
162         }
163
164         for (l = session->devs; l; l = l->next) {
165                 sdi = (struct sr_dev_inst *) l->data;
166                 sdi->session = NULL;
167         }
168
169         g_slist_free(session->devs);
170         session->devs = NULL;
171
172         return SR_OK;
173 }
174
175 /**
176  * Add a device instance to a session.
177  *
178  * @param session The session to add to. Must not be NULL.
179  * @param sdi The device instance to add to a session. Must not
180  *            be NULL. Also, sdi->driver and sdi->driver->dev_open must
181  *            not be NULL.
182  *
183  * @retval SR_OK Success.
184  * @retval SR_ERR_ARG Invalid argument.
185  *
186  * @since 0.4.0
187  */
188 SR_API int sr_session_dev_add(struct sr_session *session,
189                 struct sr_dev_inst *sdi)
190 {
191         int ret;
192
193         if (!sdi) {
194                 sr_err("%s: sdi was NULL", __func__);
195                 return SR_ERR_ARG;
196         }
197
198         if (!session) {
199                 sr_err("%s: session was NULL", __func__);
200                 return SR_ERR_ARG;
201         }
202
203         /* If sdi->session is not NULL, the device is already in this or
204          * another session. */
205         if (sdi->session) {
206                 sr_err("%s: already assigned to session", __func__);
207                 return SR_ERR_ARG;
208         }
209
210         /* If sdi->driver is NULL, this is a virtual device. */
211         if (!sdi->driver) {
212                 /* Just add the device, don't run dev_open(). */
213                 session->devs = g_slist_append(session->devs, (gpointer)sdi);
214                 sdi->session = session;
215                 return SR_OK;
216         }
217
218         /* sdi->driver is non-NULL (i.e. we have a real device). */
219         if (!sdi->driver->dev_open) {
220                 sr_err("%s: sdi->driver->dev_open was NULL", __func__);
221                 return SR_ERR_BUG;
222         }
223
224         session->devs = g_slist_append(session->devs, (gpointer)sdi);
225         sdi->session = session;
226
227         if (session->running) {
228                 /* Adding a device to a running session. Commit settings
229                  * and start acquisition on that device now. */
230                 if ((ret = sr_config_commit(sdi)) != SR_OK) {
231                         sr_err("Failed to commit device settings before "
232                                "starting acquisition in running session (%s)",
233                                sr_strerror(ret));
234                         return ret;
235                 }
236                 if ((ret = sdi->driver->dev_acquisition_start(sdi,
237                                                 (void *)sdi)) != SR_OK) {
238                         sr_err("Failed to start acquisition of device in "
239                                "running session (%s)", sr_strerror(ret));
240                         return ret;
241                 }
242         }
243
244         return SR_OK;
245 }
246
247 /**
248  * List all device instances attached to a session.
249  *
250  * @param session The session to use. Must not be NULL.
251  * @param devlist A pointer where the device instance list will be
252  *                stored on return. If no devices are in the session,
253  *                this will be NULL. Each element in the list points
254  *                to a struct sr_dev_inst *.
255  *                The list must be freed by the caller, but not the
256  *                elements pointed to.
257  *
258  * @retval SR_OK Success.
259  * @retval SR_ERR_ARG Invalid argument.
260  *
261  * @since 0.4.0
262  */
263 SR_API int sr_session_dev_list(struct sr_session *session, GSList **devlist)
264 {
265         if (!session)
266                 return SR_ERR_ARG;
267
268         if (!devlist)
269                 return SR_ERR_ARG;
270
271         *devlist = g_slist_copy(session->devs);
272
273         return SR_OK;
274 }
275
276 /**
277  * Remove all datafeed callbacks in a session.
278  *
279  * @param session The session to use. Must not be NULL.
280  *
281  * @retval SR_OK Success.
282  * @retval SR_ERR_ARG Invalid session passed.
283  *
284  * @since 0.4.0
285  */
286 SR_API int sr_session_datafeed_callback_remove_all(struct sr_session *session)
287 {
288         if (!session) {
289                 sr_err("%s: session was NULL", __func__);
290                 return SR_ERR_ARG;
291         }
292
293         g_slist_free_full(session->datafeed_callbacks, g_free);
294         session->datafeed_callbacks = NULL;
295
296         return SR_OK;
297 }
298
299 /**
300  * Add a datafeed callback to a session.
301  *
302  * @param session The session to use. Must not be NULL.
303  * @param cb Function to call when a chunk of data is received.
304  *           Must not be NULL.
305  * @param cb_data Opaque pointer passed in by the caller.
306  *
307  * @retval SR_OK Success.
308  * @retval SR_ERR_BUG No session exists.
309  *
310  * @since 0.3.0
311  */
312 SR_API int sr_session_datafeed_callback_add(struct sr_session *session,
313                 sr_datafeed_callback cb, void *cb_data)
314 {
315         struct datafeed_callback *cb_struct;
316
317         if (!session) {
318                 sr_err("%s: session was NULL", __func__);
319                 return SR_ERR_BUG;
320         }
321
322         if (!cb) {
323                 sr_err("%s: cb was NULL", __func__);
324                 return SR_ERR_ARG;
325         }
326
327         cb_struct = g_malloc0(sizeof(struct datafeed_callback));
328         cb_struct->cb = cb;
329         cb_struct->cb_data = cb_data;
330
331         session->datafeed_callbacks =
332             g_slist_append(session->datafeed_callbacks, cb_struct);
333
334         return SR_OK;
335 }
336
337 /**
338  * Get the trigger assigned to this session.
339  *
340  * @param session The session to use.
341  *
342  * @retval NULL Invalid (NULL) session was passed to the function.
343  * @retval other The trigger assigned to this session (can be NULL).
344  *
345  * @since 0.4.0
346  */
347 SR_API struct sr_trigger *sr_session_trigger_get(struct sr_session *session)
348 {
349         if (!session)
350                 return NULL;
351
352         return session->trigger;
353 }
354
355 /**
356  * Set the trigger of this session.
357  *
358  * @param session The session to use. Must not be NULL.
359  * @param trig The trigger to assign to this session. Can be NULL.
360  *
361  * @retval SR_OK Success.
362  * @retval SR_ERR_ARG Invalid argument.
363  *
364  * @since 0.4.0
365  */
366 SR_API int sr_session_trigger_set(struct sr_session *session, struct sr_trigger *trig)
367 {
368         if (!session)
369                 return SR_ERR_ARG;
370
371         session->trigger = trig;
372
373         return SR_OK;
374 }
375
376 static gboolean sr_session_check_aborted(struct sr_session *session)
377 {
378         gboolean stop;
379
380         g_mutex_lock(&session->stop_mutex);
381         stop = session->abort_session;
382         if (stop) {
383                 sr_session_stop_sync(session);
384                 /* But once is enough. */
385                 session->abort_session = FALSE;
386         }
387         g_mutex_unlock(&session->stop_mutex);
388
389         return stop;
390 }
391
392 /**
393  * Poll the session's event sources.
394  *
395  * @param session The session to use. Must not be NULL.
396  * @retval SR_OK Success.
397  * @retval SR_ERR Error occurred.
398  */
399 static int sr_session_iteration(struct sr_session *session)
400 {
401         int64_t start_time, stop_time, min_due, due;
402         int timeout_ms;
403         unsigned int i;
404         int k, fd_index;
405         int ret;
406         int fd;
407         int revents;
408         gboolean triggered, stopped;
409         struct source *source;
410         GPollFD *pollfd;
411         gintptr poll_object;
412 #if HAVE_LIBUSB_1_0
413         int64_t usb_timeout;
414         int64_t usb_due;
415         struct timeval tv;
416 #endif
417         if (session->sources->len == 0) {
418                 sr_session_check_aborted(session);
419                 return SR_OK;
420         }
421         start_time = g_get_monotonic_time();
422         min_due = INT64_MAX;
423
424         for (i = 0; i < session->sources->len; ++i) {
425                 source = &g_array_index(session->sources, struct source, i);
426                 if (source->due < min_due)
427                         min_due = source->due;
428                 source->triggered = FALSE;
429         }
430 #if HAVE_LIBUSB_1_0
431         usb_due = INT64_MAX;
432         if (session->ctx->usb_source_present) {
433                 ret = libusb_get_next_timeout(session->ctx->libusb_ctx, &tv);
434                 if (ret < 0) {
435                         sr_err("Error getting libusb timeout: %s",
436                                 libusb_error_name(ret));
437                         return SR_ERR;
438                 } else if (ret == 1) {
439                         usb_timeout = (int64_t)tv.tv_sec * G_USEC_PER_SEC
440                                         + tv.tv_usec;
441                         usb_due = start_time + usb_timeout;
442                         if (usb_due < min_due)
443                                 min_due = usb_due;
444
445                         sr_spew("poll: next USB timeout %g ms",
446                                 1e-3 * usb_timeout);
447                 }
448         }
449 #endif
450         if (min_due == INT64_MAX)
451                 timeout_ms = -1;
452         else if (min_due > start_time)
453                 timeout_ms = MIN((min_due - start_time + 999) / 1000, INT_MAX);
454         else
455                 timeout_ms = 0;
456
457         sr_spew("poll enter: %u sources, %u fds, %d ms timeout",
458                 session->sources->len, session->pollfds->len, timeout_ms);
459
460         ret = g_poll((GPollFD *)session->pollfds->data,
461                         session->pollfds->len, timeout_ms);
462 #ifdef G_OS_UNIX
463         if (ret < 0 && errno != EINTR) {
464                 sr_err("Error in poll: %s", g_strerror(errno));
465                 return SR_ERR;
466         }
467 #else
468         if (ret < 0) {
469                 sr_err("Error in poll: %d", ret);
470                 return SR_ERR;
471         }
472 #endif
473         stop_time = g_get_monotonic_time();
474
475         sr_spew("poll leave: %g ms elapsed, %d events",
476                 1e-3 * (stop_time - start_time), ret);
477
478         triggered = FALSE;
479         stopped = FALSE;
480         fd_index = 0;
481
482         for (i = 0; i < session->sources->len; ++i) {
483                 source = &g_array_index(session->sources, struct source, i);
484
485                 poll_object = source->poll_object;
486                 fd = (int)poll_object;
487                 revents = 0;
488
489                 for (k = 0; k < source->num_fds; ++k) {
490                         pollfd = &g_array_index(session->pollfds,
491                                         GPollFD, fd_index + k);
492                         fd = pollfd->fd;
493                         revents |= pollfd->revents;
494                 }
495                 fd_index += source->num_fds;
496
497                 if (source->triggered)
498                         continue; /* already handled */
499                 if (ret > 0 && revents == 0)
500                         continue; /* skip timeouts if any I/O event occurred */
501
502                 /* Make invalid to avoid confusion in case of multiple FDs. */
503                 if (source->num_fds > 1)
504                         fd = -1;
505                 if (ret <= 0)
506                         revents = 0;
507
508                 due = source->due;
509 #if HAVE_LIBUSB_1_0
510                 if (usb_due < due && poll_object
511                                 == (gintptr)session->ctx->libusb_ctx)
512                         due = usb_due;
513 #endif
514                 if (revents == 0 && stop_time < due)
515                         continue;
516                 /*
517                  * The source may be gone after the callback returns,
518                  * so access any data now that needs accessing.
519                  */
520                 if (source->timeout >= 0)
521                         source->due = stop_time + source->timeout;
522                 source->triggered = TRUE;
523                 triggered = TRUE;
524                 /*
525                  * Invoke the source's callback on an event or timeout.
526                  */
527                 sr_spew("callback for event source %" G_GINTPTR_FORMAT " with"
528                         " event mask 0x%.2X", poll_object, (unsigned)revents);
529                 if (!source->cb(fd, revents, source->cb_data)) {
530 #if HAVE_LIBUSB_1_0
531                         /* Hackish, to be cleaned up when porting to
532                          * the GLib main loop.
533                          */
534                         if (poll_object == (gintptr)session->ctx->libusb_ctx)
535                                 usb_source_remove(session, session->ctx);
536                         else
537 #endif
538                                 sr_session_source_remove_internal(session,
539                                                 poll_object);
540                 }
541                 /*
542                  * We want to take as little time as possible to stop
543                  * the session if we have been told to do so. Therefore,
544                  * we check the flag after processing every source, not
545                  * just once per main event loop.
546                  */
547                 if (!stopped)
548                         stopped = sr_session_check_aborted(session);
549
550                 /* Restart loop as the sources list may have changed. */
551                 fd_index = 0;
552                 i = 0;
553         }
554
555         /* Check for abort at least once per iteration. */
556         if (!triggered)
557                 sr_session_check_aborted(session);
558
559         return SR_OK;
560 }
561
562 static int verify_trigger(struct sr_trigger *trigger)
563 {
564         struct sr_trigger_stage *stage;
565         struct sr_trigger_match *match;
566         GSList *l, *m;
567
568         if (!trigger->stages) {
569                 sr_err("No trigger stages defined.");
570                 return SR_ERR;
571         }
572
573         sr_spew("Checking trigger:");
574         for (l = trigger->stages; l; l = l->next) {
575                 stage = l->data;
576                 if (!stage->matches) {
577                         sr_err("Stage %d has no matches defined.", stage->stage);
578                         return SR_ERR;
579                 }
580                 for (m = stage->matches; m; m = m->next) {
581                         match = m->data;
582                         if (!match->channel) {
583                                 sr_err("Stage %d match has no channel.", stage->stage);
584                                 return SR_ERR;
585                         }
586                         if (!match->match) {
587                                 sr_err("Stage %d match is not defined.", stage->stage);
588                                 return SR_ERR;
589                         }
590                         sr_spew("Stage %d match on channel %s, match %d", stage->stage,
591                                         match->channel->name, match->match);
592                 }
593         }
594
595         return SR_OK;
596 }
597
598 /**
599  * Start a session.
600  *
601  * @param session The session to use. Must not be NULL.
602  *
603  * @retval SR_OK Success.
604  * @retval SR_ERR_ARG Invalid session passed.
605  *
606  * @since 0.4.0
607  */
608 SR_API int sr_session_start(struct sr_session *session)
609 {
610         struct sr_dev_inst *sdi;
611         struct sr_channel *ch;
612         GSList *l, *c;
613         int enabled_channels, ret;
614
615         if (!session) {
616                 sr_err("%s: session was NULL", __func__);
617                 return SR_ERR_ARG;
618         }
619
620         if (!session->devs) {
621                 sr_err("%s: session->devs was NULL; a session "
622                        "cannot be started without devices.", __func__);
623                 return SR_ERR_ARG;
624         }
625
626         if (session->trigger && verify_trigger(session->trigger) != SR_OK)
627                 return SR_ERR;
628
629         sr_info("Starting.");
630
631         ret = SR_OK;
632         for (l = session->devs; l; l = l->next) {
633                 sdi = l->data;
634                 enabled_channels = 0;
635                 for (c = sdi->channels; c; c = c->next) {
636                         ch = c->data;
637                         if (ch->enabled) {
638                                 enabled_channels++;
639                                 break;
640                         }
641                 }
642                 if (enabled_channels == 0) {
643                         ret = SR_ERR;
644                         sr_err("%s using connection %s has no enabled channels!",
645                                         sdi->driver->name, sdi->connection_id);
646                         break;
647                 }
648
649                 if ((ret = sr_config_commit(sdi)) != SR_OK) {
650                         sr_err("Failed to commit device settings before "
651                                "starting acquisition (%s)", sr_strerror(ret));
652                         break;
653                 }
654                 if ((ret = sdi->driver->dev_acquisition_start(sdi, sdi)) != SR_OK) {
655                         sr_err("%s: could not start an acquisition "
656                                "(%s)", __func__, sr_strerror(ret));
657                         break;
658                 }
659         }
660
661         /* TODO: What if there are multiple devices? Which return code? */
662
663         return ret;
664 }
665
666 /**
667  * Run a session.
668  *
669  * @param session The session to use. Must not be NULL.
670  *
671  * @retval SR_OK Success.
672  * @retval SR_ERR_ARG Invalid session passed.
673  * @retval SR_ERR Error during event processing.
674  *
675  * @since 0.4.0
676  */
677 SR_API int sr_session_run(struct sr_session *session)
678 {
679         int ret;
680
681         if (!session) {
682                 sr_err("%s: session was NULL", __func__);
683                 return SR_ERR_ARG;
684         }
685
686         if (!session->devs) {
687                 /* TODO: Actually the case? */
688                 sr_err("%s: session->devs was NULL; a session "
689                        "cannot be run without devices.", __func__);
690                 return SR_ERR_ARG;
691         }
692         session->running = TRUE;
693
694         sr_info("Running.");
695
696         /* Poll event sources until none are left. */
697         while (session->sources->len > 0) {
698                 ret = sr_session_iteration(session);
699                 if (ret != SR_OK)
700                         return ret;
701         }
702         return SR_OK;
703 }
704
705 /**
706  * Stop a session.
707  *
708  * The session is stopped immediately, with all acquisition sessions stopped
709  * and hardware drivers cleaned up.
710  *
711  * This must be called from within the session thread, to prevent freeing
712  * resources that the session thread will try to use.
713  *
714  * @param session The session to use. Must not be NULL.
715  *
716  * @retval SR_OK Success.
717  * @retval SR_ERR_ARG Invalid session passed.
718  *
719  * @private
720  */
721 SR_PRIV int sr_session_stop_sync(struct sr_session *session)
722 {
723         struct sr_dev_inst *sdi;
724         GSList *l;
725
726         if (!session) {
727                 sr_err("%s: session was NULL", __func__);
728                 return SR_ERR_ARG;
729         }
730
731         sr_info("Stopping.");
732
733         for (l = session->devs; l; l = l->next) {
734                 sdi = l->data;
735                 if (sdi->driver) {
736                         if (sdi->driver->dev_acquisition_stop)
737                                 sdi->driver->dev_acquisition_stop(sdi, sdi);
738                 }
739         }
740         session->running = FALSE;
741
742         return SR_OK;
743 }
744
745 /**
746  * Stop a session.
747  *
748  * The session is stopped immediately, with all acquisition sessions being
749  * stopped and hardware drivers cleaned up.
750  *
751  * If the session is run in a separate thread, this function will not block
752  * until the session is finished executing. It is the caller's responsibility
753  * to wait for the session thread to return before assuming that the session is
754  * completely decommissioned.
755  *
756  * @param session The session to use. Must not be NULL.
757  *
758  * @retval SR_OK Success.
759  * @retval SR_ERR_ARG Invalid session passed.
760  *
761  * @since 0.4.0
762  */
763 SR_API int sr_session_stop(struct sr_session *session)
764 {
765         if (!session) {
766                 sr_err("%s: session was NULL", __func__);
767                 return SR_ERR_BUG;
768         }
769
770         g_mutex_lock(&session->stop_mutex);
771         session->abort_session = TRUE;
772         g_mutex_unlock(&session->stop_mutex);
773
774         return SR_OK;
775 }
776
777 /**
778  * Debug helper.
779  *
780  * @param packet The packet to show debugging information for.
781  */
782 static void datafeed_dump(const struct sr_datafeed_packet *packet)
783 {
784         const struct sr_datafeed_logic *logic;
785         const struct sr_datafeed_analog *analog;
786         const struct sr_datafeed_analog2 *analog2;
787
788         /* Please use the same order as in libsigrok.h. */
789         switch (packet->type) {
790         case SR_DF_HEADER:
791                 sr_dbg("bus: Received SR_DF_HEADER packet.");
792                 break;
793         case SR_DF_END:
794                 sr_dbg("bus: Received SR_DF_END packet.");
795                 break;
796         case SR_DF_META:
797                 sr_dbg("bus: Received SR_DF_META packet.");
798                 break;
799         case SR_DF_TRIGGER:
800                 sr_dbg("bus: Received SR_DF_TRIGGER packet.");
801                 break;
802         case SR_DF_LOGIC:
803                 logic = packet->payload;
804                 sr_dbg("bus: Received SR_DF_LOGIC packet (%" PRIu64 " bytes, "
805                        "unitsize = %d).", logic->length, logic->unitsize);
806                 break;
807         case SR_DF_ANALOG:
808                 analog = packet->payload;
809                 sr_dbg("bus: Received SR_DF_ANALOG packet (%d samples).",
810                        analog->num_samples);
811                 break;
812         case SR_DF_FRAME_BEGIN:
813                 sr_dbg("bus: Received SR_DF_FRAME_BEGIN packet.");
814                 break;
815         case SR_DF_FRAME_END:
816                 sr_dbg("bus: Received SR_DF_FRAME_END packet.");
817                 break;
818         case SR_DF_ANALOG2:
819                 analog2 = packet->payload;
820                 sr_dbg("bus: Received SR_DF_ANALOG2 packet (%d samples).",
821                        analog2->num_samples);
822                 break;
823         default:
824                 sr_dbg("bus: Received unknown packet type: %d.", packet->type);
825                 break;
826         }
827 }
828
829 /**
830  * Send a packet to whatever is listening on the datafeed bus.
831  *
832  * Hardware drivers use this to send a data packet to the frontend.
833  *
834  * @param sdi TODO.
835  * @param packet The datafeed packet to send to the session bus.
836  *
837  * @retval SR_OK Success.
838  * @retval SR_ERR_ARG Invalid argument.
839  *
840  * @private
841  */
842 SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi,
843                 const struct sr_datafeed_packet *packet)
844 {
845         GSList *l;
846         struct datafeed_callback *cb_struct;
847         struct sr_datafeed_packet *packet_in, *packet_out;
848         struct sr_transform *t;
849         int ret;
850
851         if (!sdi) {
852                 sr_err("%s: sdi was NULL", __func__);
853                 return SR_ERR_ARG;
854         }
855
856         if (!packet) {
857                 sr_err("%s: packet was NULL", __func__);
858                 return SR_ERR_ARG;
859         }
860
861         if (!sdi->session) {
862                 sr_err("%s: session was NULL", __func__);
863                 return SR_ERR_BUG;
864         }
865
866         /*
867          * Pass the packet to the first transform module. If that returns
868          * another packet (instead of NULL), pass that packet to the next
869          * transform module in the list, and so on.
870          */
871         packet_in = (struct sr_datafeed_packet *)packet;
872         for (l = sdi->session->transforms; l; l = l->next) {
873                 t = l->data;
874                 sr_spew("Running transform module '%s'.", t->module->id);
875                 ret = t->module->receive(t, packet_in, &packet_out);
876                 if (ret < 0) {
877                         sr_err("Error while running transform module: %d.", ret);
878                         return SR_ERR;
879                 }
880                 if (!packet_out) {
881                         /*
882                          * If any of the transforms don't return an output
883                          * packet, abort.
884                          */
885                         sr_spew("Transform module didn't return a packet, aborting.");
886                         return SR_OK;
887                 } else {
888                         /*
889                          * Use this transform module's output packet as input
890                          * for the next transform module.
891                          */
892                         packet_in = packet_out;
893                 }
894         }
895         packet = packet_in;
896
897         /*
898          * If the last transform did output a packet, pass it to all datafeed
899          * callbacks.
900          */
901         for (l = sdi->session->datafeed_callbacks; l; l = l->next) {
902                 if (sr_log_loglevel_get() >= SR_LOG_DBG)
903                         datafeed_dump(packet);
904                 cb_struct = l->data;
905                 cb_struct->cb(sdi, packet, cb_struct->cb_data);
906         }
907
908         return SR_OK;
909 }
910
911 /**
912  * Add an event source for a file descriptor.
913  *
914  * @param session The session to use. Must not be NULL.
915  * @param[in] timeout Max time in ms to wait before the callback is called,
916  *                    or -1 to wait indefinitely.
917  * @param cb Callback function to add. Must not be NULL.
918  * @param cb_data Data for the callback function. Can be NULL.
919  * @param poll_object Handle by which the source is identified
920  *
921  * @retval SR_OK Success.
922  * @retval SR_ERR_ARG Invalid argument.
923  * @retval SR_ERR An event source for @a poll_object is already installed.
924  */
925 SR_PRIV int sr_session_source_add_internal(struct sr_session *session,
926                 int timeout, sr_receive_data_callback cb, void *cb_data,
927                 gintptr poll_object)
928 {
929         struct source src;
930         unsigned int i;
931
932         /* Note: cb_data can be NULL, that's not a bug. */
933         if (!cb) {
934                 sr_err("%s: cb was NULL", __func__);
935                 return SR_ERR_ARG;
936         }
937         /* Make sure that poll_object is unique.
938          */
939         for (i = 0; i < session->sources->len; ++i) {
940                 if (g_array_index(session->sources, struct source, i)
941                                 .poll_object == poll_object) {
942                         sr_err("Event source %" G_GINTPTR_FORMAT
943                                 " already installed.", poll_object);
944                         return SR_ERR;
945                 }
946         }
947         sr_dbg("Installing event source %" G_GINTPTR_FORMAT
948                 " with %d ms timeout.", poll_object, timeout);
949         src.cb = cb;
950         src.cb_data = cb_data;
951         src.poll_object = poll_object;
952         src.num_fds = 0;
953         src.triggered = FALSE;
954
955         if (timeout >= 0) {
956                 src.timeout = INT64_C(1000) * timeout;
957                 src.due = g_get_monotonic_time() + src.timeout;
958         } else {
959                 src.timeout = -1;
960                 src.due = INT64_MAX;
961         }
962         g_array_append_val(session->sources, src);
963
964         return SR_OK;
965 }
966
967 SR_PRIV int sr_session_source_poll_add(struct sr_session *session,
968                 gintptr poll_object, gintptr fd, int events)
969 {
970         struct source *source;
971         GPollFD pollfd;
972         unsigned int i;
973         int fd_index, k;
974
975         source = NULL;
976         fd_index = 0;
977
978         /* Look up existing event source.
979          */
980         for (i = 0; i < session->sources->len; ++i) {
981                 source = &g_array_index(session->sources, struct source, i);
982                 if (source->poll_object == poll_object)
983                         break;
984                 fd_index += source->num_fds;
985         }
986         if (!source) {
987                 sr_err("Cannot add poll FD %" G_GINTPTR_FORMAT
988                         " to non-existing event source %" G_GINTPTR_FORMAT
989                         ".",  fd, poll_object);
990                 return SR_ERR;
991         }
992         /* Make sure the FD is unique.
993          */
994         for (k = 0; k < source->num_fds; ++k)
995                 if (g_array_index(session->pollfds, GPollFD, fd_index + k)
996                                 .fd == fd) {
997                         sr_err("Cannot add poll FD %" G_GINTPTR_FORMAT
998                                 " twice to event source %" G_GINTPTR_FORMAT
999                                 ".", fd, poll_object);
1000                         return SR_ERR;
1001                 }
1002
1003         pollfd.fd = fd;
1004         pollfd.events = events;
1005         pollfd.revents = 0;
1006
1007         g_array_insert_val(session->pollfds,
1008                 fd_index + source->num_fds, pollfd);
1009         ++source->num_fds;
1010
1011         sr_dbg("Added poll FD %" G_GINTPTR_FORMAT " with event mask 0x%.2X"
1012                 " to event source %" G_GINTPTR_FORMAT ".",
1013                 fd, (unsigned)events, poll_object);
1014
1015         return SR_OK;
1016 }
1017
1018 /**
1019  * Add an event source for a file descriptor.
1020  *
1021  * @param session The session to use. Must not be NULL.
1022  * @param fd The file descriptor, or a negative value to create a timer source.
1023  * @param events Events to check for.
1024  * @param timeout Max time in ms to wait before the callback is called,
1025  *                or -1 to wait indefinitely.
1026  * @param cb Callback function to add. Must not be NULL.
1027  * @param cb_data Data for the callback function. Can be NULL.
1028  *
1029  * @retval SR_OK Success.
1030  * @retval SR_ERR_ARG Invalid argument.
1031  *
1032  * @since 0.3.0
1033  */
1034 SR_API int sr_session_source_add(struct sr_session *session, int fd,
1035                 int events, int timeout, sr_receive_data_callback cb, void *cb_data)
1036 {
1037         int ret;
1038
1039         if (fd < 0 && timeout < 0) {
1040                 sr_err("Timer source without timeout would block indefinitely");
1041                 return SR_ERR_ARG;
1042         }
1043         ret = sr_session_source_add_internal(session, timeout, cb, cb_data, fd);
1044         if (ret != SR_OK || fd < 0)
1045                 return ret;
1046
1047         return sr_session_source_poll_add(session, fd, fd, events);
1048 }
1049
1050 /**
1051  * Add an event source for a GPollFD.
1052  *
1053  * @param session The session to use. Must not be NULL.
1054  * @param pollfd The GPollFD. Must not be NULL.
1055  * @param timeout Max time in ms to wait before the callback is called,
1056  *                or -1 to wait indefinitely.
1057  * @param cb Callback function to add. Must not be NULL.
1058  * @param cb_data Data for the callback function. Can be NULL.
1059  *
1060  * @retval SR_OK Success.
1061  * @retval SR_ERR_ARG Invalid argument.
1062  *
1063  * @since 0.3.0
1064  */
1065 SR_API int sr_session_source_add_pollfd(struct sr_session *session,
1066                 GPollFD *pollfd, int timeout, sr_receive_data_callback cb,
1067                 void *cb_data)
1068 {
1069         int ret;
1070
1071         if (!pollfd) {
1072                 sr_err("%s: pollfd was NULL", __func__);
1073                 return SR_ERR_ARG;
1074         }
1075         ret = sr_session_source_add_internal(session,
1076                         timeout, cb, cb_data, (gintptr)pollfd);
1077         if (ret != SR_OK)
1078                 return ret;
1079
1080         return sr_session_source_poll_add(session,
1081                         (gintptr)pollfd, pollfd->fd, pollfd->events);
1082 }
1083
1084 /**
1085  * Add an event source for a GIOChannel.
1086  *
1087  * @param session The session to use. Must not be NULL.
1088  * @param channel The GIOChannel.
1089  * @param events Events to poll on.
1090  * @param timeout Max time in ms to wait before the callback is called,
1091  *                or -1 to wait indefinitely.
1092  * @param cb Callback function to add. Must not be NULL.
1093  * @param cb_data Data for the callback function. Can be NULL.
1094  *
1095  * @retval SR_OK Success.
1096  * @retval SR_ERR_ARG Invalid argument.
1097  *
1098  * @since 0.3.0
1099  */
1100 SR_API int sr_session_source_add_channel(struct sr_session *session,
1101                 GIOChannel *channel, int events, int timeout,
1102                 sr_receive_data_callback cb, void *cb_data)
1103 {
1104         int ret;
1105
1106         ret = sr_session_source_add_internal(session,
1107                         timeout, cb, cb_data, (gintptr)channel);
1108         if (ret != SR_OK)
1109                 return ret;
1110 #ifdef G_OS_WIN32
1111         GPollFD p;
1112         g_io_channel_win32_make_pollfd(channel, events, &p);
1113
1114         return sr_session_source_poll_add(session,
1115                         (gintptr)channel, p.fd, p.events);
1116 #else
1117         return sr_session_source_poll_add(session, (gintptr)channel,
1118                         g_io_channel_unix_get_fd(channel), events);
1119 #endif
1120 }
1121
1122 /**
1123  * Remove the source identified by the specified poll object.
1124  *
1125  * @param session The session to use. Must not be NULL.
1126  * @param poll_object The channel for which the source should be removed.
1127  *
1128  * @retval SR_OK Success
1129  * @retval SR_ERR_BUG No event source for poll_object found.
1130  */
1131 SR_PRIV int sr_session_source_remove_internal(struct sr_session *session,
1132                 gintptr poll_object)
1133 {
1134         struct source *source;
1135         unsigned int i;
1136         int fd_index = 0;
1137
1138         for (i = 0; i < session->sources->len; ++i) {
1139                 source = &g_array_index(session->sources, struct source, i);
1140
1141                 if (source->poll_object == poll_object) {
1142                         if (source->num_fds > 0)
1143                                 g_array_remove_range(session->pollfds,
1144                                                 fd_index, source->num_fds);
1145                         g_array_remove_index(session->sources, i);
1146
1147                         sr_dbg("Removed event source %" G_GINTPTR_FORMAT ".",
1148                                 poll_object);
1149                         return SR_OK;
1150                 }
1151                 fd_index += source->num_fds;
1152         }
1153         /* Trying to remove an already removed event source is problematic
1154          * since the poll_object handle may have been reused in the meantime.
1155          */
1156         sr_warn("Cannot remove non-existing event source %"
1157                 G_GINTPTR_FORMAT ".", poll_object);
1158
1159         return SR_ERR_BUG;
1160 }
1161
1162 SR_PRIV int sr_session_source_poll_remove(struct sr_session *session,
1163                 gintptr poll_object, gintptr fd)
1164 {
1165         struct source *source;
1166         unsigned int i;
1167         int fd_index, k;
1168
1169         source = NULL;
1170         fd_index = 0;
1171
1172         /* Look up existing event source.
1173          */
1174         for (i = 0; i < session->sources->len; ++i) {
1175                 source = &g_array_index(session->sources, struct source, i);
1176                 if (source->poll_object == poll_object)
1177                         break;
1178                 fd_index += source->num_fds;
1179         }
1180         if (!source) {
1181                 sr_err("Cannot remove poll FD %" G_GINTPTR_FORMAT
1182                         " from non-existing event source %" G_GINTPTR_FORMAT
1183                         ".", fd, poll_object);
1184                 return SR_ERR;
1185         }
1186         /* Look up the FD in the poll set.
1187          */
1188         for (k = 0; k < source->num_fds; ++k)
1189                 if (g_array_index(session->pollfds, GPollFD, fd_index + k)
1190                                 .fd == fd) {
1191
1192                         g_array_remove_index(session->pollfds, fd_index + k);
1193                         --source->num_fds;
1194
1195                         sr_dbg("Removed poll FD %" G_GINTPTR_FORMAT
1196                                 " from event source %" G_GINTPTR_FORMAT ".",
1197                                 fd, poll_object);
1198                         return SR_OK;
1199                 }
1200
1201         sr_err("Cannot remove non-existing poll FD %" G_GINTPTR_FORMAT
1202                 " from event source %" G_GINTPTR_FORMAT ".",
1203                 fd, poll_object);
1204
1205         return SR_ERR;
1206 }
1207
1208 /**
1209  * Remove the source belonging to the specified file descriptor.
1210  *
1211  * @param session The session to use. Must not be NULL.
1212  * @param fd The file descriptor for which the source should be removed.
1213  *
1214  * @retval SR_OK Success
1215  * @retval SR_ERR_ARG Invalid argument
1216  * @retval SR_ERR_BUG Internal error.
1217  *
1218  * @since 0.3.0
1219  */
1220 SR_API int sr_session_source_remove(struct sr_session *session, int fd)
1221 {
1222         return sr_session_source_remove_internal(session, fd);
1223 }
1224
1225 /**
1226  * Remove the source belonging to the specified poll descriptor.
1227  *
1228  * @param session The session to use. Must not be NULL.
1229  * @param pollfd The poll descriptor for which the source should be removed.
1230  *               Must not be NULL.
1231  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
1232  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
1233  *         internal errors.
1234  *
1235  * @since 0.2.0
1236  */
1237 SR_API int sr_session_source_remove_pollfd(struct sr_session *session,
1238                 GPollFD *pollfd)
1239 {
1240         if (!pollfd) {
1241                 sr_err("%s: pollfd was NULL", __func__);
1242                 return SR_ERR_ARG;
1243         }
1244         return sr_session_source_remove_internal(session, (gintptr)pollfd);
1245 }
1246
1247 /**
1248  * Remove the source belonging to the specified channel.
1249  *
1250  * @param session The session to use. Must not be NULL.
1251  * @param channel The channel for which the source should be removed.
1252  *                Must not be NULL.
1253  * @retval SR_OK Success.
1254  * @retval SR_ERR_ARG Invalid argument.
1255  * @return SR_ERR_BUG Internal error.
1256  *
1257  * @since 0.2.0
1258  */
1259 SR_API int sr_session_source_remove_channel(struct sr_session *session,
1260                 GIOChannel *channel)
1261 {
1262         if (!channel) {
1263                 sr_err("%s: channel was NULL", __func__);
1264                 return SR_ERR_ARG;
1265         }
1266         return sr_session_source_remove_internal(session, (gintptr)channel);
1267 }
1268
1269 static void copy_src(struct sr_config *src, struct sr_datafeed_meta *meta_copy)
1270 {
1271         g_variant_ref(src->data);
1272         meta_copy->config = g_slist_append(meta_copy->config,
1273                                            g_memdup(src, sizeof(struct sr_config)));
1274 }
1275
1276 SR_PRIV int sr_packet_copy(const struct sr_datafeed_packet *packet,
1277                 struct sr_datafeed_packet **copy)
1278 {
1279         const struct sr_datafeed_meta *meta;
1280         struct sr_datafeed_meta *meta_copy;
1281         const struct sr_datafeed_logic *logic;
1282         struct sr_datafeed_logic *logic_copy;
1283         const struct sr_datafeed_analog *analog;
1284         struct sr_datafeed_analog *analog_copy;
1285         uint8_t *payload;
1286
1287         *copy = g_malloc0(sizeof(struct sr_datafeed_packet));
1288         (*copy)->type = packet->type;
1289
1290         switch (packet->type) {
1291         case SR_DF_TRIGGER:
1292         case SR_DF_END:
1293                 /* No payload. */
1294                 break;
1295         case SR_DF_HEADER:
1296                 payload = g_malloc(sizeof(struct sr_datafeed_header));
1297                 memcpy(payload, packet->payload, sizeof(struct sr_datafeed_header));
1298                 (*copy)->payload = payload;
1299                 break;
1300         case SR_DF_META:
1301                 meta = packet->payload;
1302                 meta_copy = g_malloc0(sizeof(struct sr_datafeed_meta));
1303                 g_slist_foreach(meta->config, (GFunc)copy_src, meta_copy->config);
1304                 (*copy)->payload = meta_copy;
1305                 break;
1306         case SR_DF_LOGIC:
1307                 logic = packet->payload;
1308                 logic_copy = g_malloc(sizeof(logic));
1309                 logic_copy->length = logic->length;
1310                 logic_copy->unitsize = logic->unitsize;
1311                 memcpy(logic_copy->data, logic->data, logic->length * logic->unitsize);
1312                 (*copy)->payload = logic_copy;
1313                 break;
1314         case SR_DF_ANALOG:
1315                 analog = packet->payload;
1316                 analog_copy = g_malloc(sizeof(analog));
1317                 analog_copy->channels = g_slist_copy(analog->channels);
1318                 analog_copy->num_samples = analog->num_samples;
1319                 analog_copy->mq = analog->mq;
1320                 analog_copy->unit = analog->unit;
1321                 analog_copy->mqflags = analog->mqflags;
1322                 memcpy(analog_copy->data, analog->data,
1323                                 analog->num_samples * sizeof(float));
1324                 (*copy)->payload = analog_copy;
1325                 break;
1326         default:
1327                 sr_err("Unknown packet type %d", packet->type);
1328                 return SR_ERR;
1329         }
1330
1331         return SR_OK;
1332 }
1333
1334 void sr_packet_free(struct sr_datafeed_packet *packet)
1335 {
1336         const struct sr_datafeed_meta *meta;
1337         const struct sr_datafeed_logic *logic;
1338         const struct sr_datafeed_analog *analog;
1339         struct sr_config *src;
1340         GSList *l;
1341
1342         switch (packet->type) {
1343         case SR_DF_TRIGGER:
1344         case SR_DF_END:
1345                 /* No payload. */
1346                 break;
1347         case SR_DF_HEADER:
1348                 /* Payload is a simple struct. */
1349                 g_free((void *)packet->payload);
1350                 break;
1351         case SR_DF_META:
1352                 meta = packet->payload;
1353                 for (l = meta->config; l; l = l->next) {
1354                         src = l->data;
1355                         g_variant_unref(src->data);
1356                         g_free(src);
1357                 }
1358                 g_slist_free(meta->config);
1359                 g_free((void *)packet->payload);
1360                 break;
1361         case SR_DF_LOGIC:
1362                 logic = packet->payload;
1363                 g_free(logic->data);
1364                 g_free((void *)packet->payload);
1365                 break;
1366         case SR_DF_ANALOG:
1367                 analog = packet->payload;
1368                 g_slist_free(analog->channels);
1369                 g_free(analog->data);
1370                 g_free((void *)packet->payload);
1371                 break;
1372         default:
1373                 sr_err("Unknown packet type %d", packet->type);
1374         }
1375         g_free(packet);
1376
1377 }
1378
1379 /** @} */