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