]> sigrok.org Git - libsigrok.git/blob - src/session.c
session: Remove irrelevant logging.
[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 <stdio.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <string.h>
24 #include <glib.h>
25 #include "libsigrok.h"
26 #include "libsigrok-internal.h"
27
28 /** @cond PRIVATE */
29 #define LOG_PREFIX "session"
30 /** @endcond */
31
32 /**
33  * @file
34  *
35  * Creating, using, or destroying libsigrok sessions.
36  */
37
38 /**
39  * @defgroup grp_session Session handling
40  *
41  * Creating, using, or destroying libsigrok sessions.
42  *
43  * @{
44  */
45
46 struct source {
47         int timeout;
48         sr_receive_data_callback cb;
49         void *cb_data;
50
51         /* This is used to keep track of the object (fd, pollfd or channel) which is
52          * being polled and will be used to match the source when removing it again.
53          */
54         gintptr poll_object;
55 };
56
57 struct datafeed_callback {
58         sr_datafeed_callback cb;
59         void *cb_data;
60 };
61
62 /**
63  * Create a new session.
64  *
65  * @param new_session This will contain a pointer to the newly created
66  *                    session if the return value is SR_OK, otherwise the value
67  *                    is undefined and should not be used. Must not be NULL.
68  *
69  * @retval SR_OK Success.
70  * @retval SR_ERR_ARG Invalid argument.
71  *
72  * @since 0.4.0
73  */
74 SR_API int sr_session_new(struct sr_session **new_session)
75 {
76         struct sr_session *session;
77
78         if (!new_session)
79                 return SR_ERR_ARG;
80
81         session = g_malloc0(sizeof(struct sr_session));
82
83         session->source_timeout = -1;
84         session->running = FALSE;
85         session->abort_session = FALSE;
86         g_mutex_init(&session->stop_mutex);
87
88         *new_session = session;
89
90         return SR_OK;
91 }
92
93 /**
94  * Destroy a session.
95  * This frees up all memory used by the session.
96  *
97  * @param session The session to destroy. Must not be NULL.
98  *
99  * @retval SR_OK Success.
100  * @retval SR_ERR_ARG Invalid session passed.
101  *
102  * @since 0.4.0
103  */
104 SR_API int sr_session_destroy(struct sr_session *session)
105 {
106         if (!session) {
107                 sr_err("%s: session was NULL", __func__);
108                 return SR_ERR_ARG;
109         }
110
111         sr_session_dev_remove_all(session);
112         g_mutex_clear(&session->stop_mutex);
113         if (session->trigger)
114                 sr_trigger_free(session->trigger);
115
116         g_free(session);
117
118         return SR_OK;
119 }
120
121 /**
122  * Remove all the devices from a session.
123  *
124  * The session itself (i.e., the struct sr_session) is not free'd and still
125  * exists after this function returns.
126  *
127  * @param session The session to use. Must not be NULL.
128  *
129  * @retval SR_OK Success.
130  * @retval SR_ERR_BUG Invalid session passed.
131  *
132  * @since 0.4.0
133  */
134 SR_API int sr_session_dev_remove_all(struct sr_session *session)
135 {
136         struct sr_dev_inst *sdi;
137         GSList *l;
138
139         if (!session) {
140                 sr_err("%s: session was NULL", __func__);
141                 return SR_ERR_ARG;
142         }
143
144         for (l = session->devs; l; l = l->next) {
145                 sdi = (struct sr_dev_inst *) l->data;
146                 sdi->session = NULL;
147         }
148
149         g_slist_free(session->devs);
150         session->devs = NULL;
151
152         return SR_OK;
153 }
154
155 /**
156  * Add a device instance to a session.
157  *
158  * @param session The session to add to. Must not be NULL.
159  * @param sdi The device instance to add to a session. Must not
160  *            be NULL. Also, sdi->driver and sdi->driver->dev_open must
161  *            not be NULL.
162  *
163  * @retval SR_OK Success.
164  * @retval SR_ERR_ARG Invalid argument.
165  *
166  * @since 0.4.0
167  */
168 SR_API int sr_session_dev_add(struct sr_session *session,
169                 struct sr_dev_inst *sdi)
170 {
171         int ret;
172
173         if (!sdi) {
174                 sr_err("%s: sdi was NULL", __func__);
175                 return SR_ERR_ARG;
176         }
177
178         if (!session) {
179                 sr_err("%s: session was NULL", __func__);
180                 return SR_ERR_ARG;
181         }
182
183         /* If sdi->session is not NULL, the device is already in this or
184          * another session. */
185         if (sdi->session) {
186                 sr_err("%s: already assigned to session", __func__);
187                 return SR_ERR_ARG;
188         }
189
190         /* If sdi->driver is NULL, this is a virtual device. */
191         if (!sdi->driver) {
192                 /* Just add the device, don't run dev_open(). */
193                 session->devs = g_slist_append(session->devs, (gpointer)sdi);
194                 sdi->session = session;
195                 return SR_OK;
196         }
197
198         /* sdi->driver is non-NULL (i.e. we have a real device). */
199         if (!sdi->driver->dev_open) {
200                 sr_err("%s: sdi->driver->dev_open was NULL", __func__);
201                 return SR_ERR_BUG;
202         }
203
204         session->devs = g_slist_append(session->devs, (gpointer)sdi);
205         sdi->session = session;
206
207         if (session->running) {
208                 /* Adding a device to a running session. Commit settings
209                  * and start acquisition on that device now. */
210                 if ((ret = sr_config_commit(sdi)) != SR_OK) {
211                         sr_err("Failed to commit device settings before "
212                                "starting acquisition in running session (%s)",
213                                sr_strerror(ret));
214                         return ret;
215                 }
216                 if ((ret = sdi->driver->dev_acquisition_start(sdi,
217                                                 (void *)sdi)) != SR_OK) {
218                         sr_err("Failed to start acquisition of device in "
219                                "running session (%s)", sr_strerror(ret));
220                         return ret;
221                 }
222         }
223
224         return SR_OK;
225 }
226
227 /**
228  * List all device instances attached to a session.
229  *
230  * @param session The session to use. Must not be NULL.
231  * @param devlist A pointer where the device instance list will be
232  *                stored on return. If no devices are in the session,
233  *                this will be NULL. Each element in the list points
234  *                to a struct sr_dev_inst *.
235  *                The list must be freed by the caller, but not the
236  *                elements pointed to.
237  *
238  * @retval SR_OK Success.
239  * @retval SR_ERR_ARG Invalid argument.
240  *
241  * @since 0.4.0
242  */
243 SR_API int sr_session_dev_list(struct sr_session *session, GSList **devlist)
244 {
245         if (!session)
246                 return SR_ERR_ARG;
247
248         if (!devlist)
249                 return SR_ERR_ARG;
250
251         *devlist = g_slist_copy(session->devs);
252
253         return SR_OK;
254 }
255
256 /**
257  * Remove all datafeed callbacks in a session.
258  *
259  * @param session The session to use. Must not be NULL.
260  *
261  * @retval SR_OK Success.
262  * @retval SR_ERR_ARG Invalid session passed.
263  *
264  * @since 0.4.0
265  */
266 SR_API int sr_session_datafeed_callback_remove_all(struct sr_session *session)
267 {
268         if (!session) {
269                 sr_err("%s: session was NULL", __func__);
270                 return SR_ERR_ARG;
271         }
272
273         g_slist_free_full(session->datafeed_callbacks, g_free);
274         session->datafeed_callbacks = NULL;
275
276         return SR_OK;
277 }
278
279 /**
280  * Add a datafeed callback to a session.
281  *
282  * @param session The session to use. Must not be NULL.
283  * @param cb Function to call when a chunk of data is received.
284  *           Must not be NULL.
285  * @param cb_data Opaque pointer passed in by the caller.
286  *
287  * @retval SR_OK Success.
288  * @retval SR_ERR_BUG No session exists.
289  *
290  * @since 0.3.0
291  */
292 SR_API int sr_session_datafeed_callback_add(struct sr_session *session,
293                 sr_datafeed_callback cb, void *cb_data)
294 {
295         struct datafeed_callback *cb_struct;
296
297         if (!session) {
298                 sr_err("%s: session was NULL", __func__);
299                 return SR_ERR_BUG;
300         }
301
302         if (!cb) {
303                 sr_err("%s: cb was NULL", __func__);
304                 return SR_ERR_ARG;
305         }
306
307         if (!(cb_struct = g_try_malloc0(sizeof(struct datafeed_callback))))
308                 return SR_ERR_MALLOC;
309
310         cb_struct->cb = cb;
311         cb_struct->cb_data = cb_data;
312
313         session->datafeed_callbacks =
314             g_slist_append(session->datafeed_callbacks, cb_struct);
315
316         return SR_OK;
317 }
318
319 SR_API struct sr_trigger *sr_session_trigger_get(struct sr_session *session)
320 {
321         return session->trigger;
322 }
323
324 SR_API int sr_session_trigger_set(struct sr_session *session, struct sr_trigger *trig)
325 {
326         session->trigger = trig;
327
328         return SR_OK;
329 }
330
331 /**
332  * Call every device in the current session's callback.
333  *
334  * For sessions not driven by select loops such as sr_session_run(),
335  * but driven by another scheduler, this can be used to poll the devices
336  * from within that scheduler.
337  *
338  * @param session The session to use. Must not be NULL.
339  * @param block If TRUE, this call will wait for any of the session's
340  *              sources to fire an event on the file descriptors, or
341  *              any of their timeouts to activate. In other words, this
342  *              can be used as a select loop.
343  *              If FALSE, all sources have their callback run, regardless
344  *              of file descriptor or timeout status.
345  *
346  * @retval SR_OK Success.
347  * @retval SR_ERR Error occured.
348  */
349 static int sr_session_iteration(struct sr_session *session, gboolean block)
350 {
351         unsigned int i;
352         int ret;
353
354         ret = g_poll(session->pollfds, session->num_sources,
355                         block ? session->source_timeout : 0);
356         for (i = 0; i < session->num_sources; i++) {
357                 if (session->pollfds[i].revents > 0 || (ret == 0
358                         && session->source_timeout == session->sources[i].timeout)) {
359                         /*
360                          * Invoke the source's callback on an event,
361                          * or if the poll timed out and this source
362                          * asked for that timeout.
363                          */
364                         if (!session->sources[i].cb(session->pollfds[i].fd,
365                                         session->pollfds[i].revents,
366                                         session->sources[i].cb_data))
367                                 sr_session_source_remove(session,
368                                                 session->sources[i].poll_object);
369                 }
370                 /*
371                  * We want to take as little time as possible to stop
372                  * the session if we have been told to do so. Therefore,
373                  * we check the flag after processing every source, not
374                  * just once per main event loop.
375                  */
376                 g_mutex_lock(&session->stop_mutex);
377                 if (session->abort_session) {
378                         sr_session_stop_sync(session);
379                         /* But once is enough. */
380                         session->abort_session = FALSE;
381                 }
382                 g_mutex_unlock(&session->stop_mutex);
383         }
384
385         return SR_OK;
386 }
387
388
389 static int verify_trigger(struct sr_trigger *trigger)
390 {
391         struct sr_trigger_stage *stage;
392         struct sr_trigger_match *match;
393         GSList *l, *m;
394
395         if (!trigger->stages) {
396                 sr_err("No trigger stages defined.");
397                 return SR_ERR;
398         }
399
400         sr_spew("Checking trigger:");
401         for (l = trigger->stages; l; l = l->next) {
402                 stage = l->data;
403                 if (!stage->matches) {
404                         sr_err("Stage %d has no matches defined.", stage->stage);
405                         return SR_ERR;
406                 }
407                 for (m = stage->matches; m; m = m->next) {
408                         match = m->data;
409                         if (!match->channel) {
410                                 sr_err("Stage %d match has no channel.", stage->stage);
411                                 return SR_ERR;
412                         }
413                         if (!match->match) {
414                                 sr_err("Stage %d match is not defined.", stage->stage);
415                                 return SR_ERR;
416                         }
417                         sr_spew("Stage %d match on channel %s, match %d", stage->stage,
418                                         match->channel->name, match->match);
419                 }
420         }
421
422         return SR_OK;
423 }
424 /**
425  * Start a session.
426  *
427  * @param session The session to use. Must not be NULL.
428  *
429  * @retval SR_OK Success.
430  * @retval SR_ERR_ARG Invalid session passed.
431  *
432  * @since 0.4.0
433  */
434 SR_API int sr_session_start(struct sr_session *session)
435 {
436         struct sr_dev_inst *sdi;
437         GSList *l;
438         int ret;
439
440         if (!session) {
441                 sr_err("%s: session was NULL", __func__);
442                 return SR_ERR_ARG;
443         }
444
445         if (!session->devs) {
446                 sr_err("%s: session->devs was NULL; a session "
447                        "cannot be started without devices.", __func__);
448                 return SR_ERR_ARG;
449         }
450
451         if (session->trigger && verify_trigger(session->trigger) != SR_OK)
452                 return SR_ERR;
453
454         sr_info("Starting.");
455
456         ret = SR_OK;
457         for (l = session->devs; l; l = l->next) {
458                 sdi = l->data;
459                 if ((ret = sr_config_commit(sdi)) != SR_OK) {
460                         sr_err("Failed to commit device settings before "
461                                "starting acquisition (%s)", sr_strerror(ret));
462                         break;
463                 }
464                 if ((ret = sdi->driver->dev_acquisition_start(sdi, sdi)) != SR_OK) {
465                         sr_err("%s: could not start an acquisition "
466                                "(%s)", __func__, sr_strerror(ret));
467                         break;
468                 }
469         }
470
471         /* TODO: What if there are multiple devices? Which return code? */
472
473         return ret;
474 }
475
476 /**
477  * Run a session.
478  *
479  * @param session The session to use. Must not be NULL.
480  *
481  * @retval SR_OK Success.
482  * @retval SR_ERR_ARG Invalid session passed.
483  *
484  * @since 0.4.0
485  */
486 SR_API int sr_session_run(struct sr_session *session)
487 {
488         if (!session) {
489                 sr_err("%s: session was NULL", __func__);
490                 return SR_ERR_ARG;
491         }
492
493         if (!session->devs) {
494                 /* TODO: Actually the case? */
495                 sr_err("%s: session->devs was NULL; a session "
496                        "cannot be run without devices.", __func__);
497                 return SR_ERR_ARG;
498         }
499         session->running = TRUE;
500
501         sr_info("Running.");
502
503         /* Do we have real sources? */
504         if (session->num_sources == 1 && session->pollfds[0].fd == -1) {
505                 /* Dummy source, freewheel over it. */
506                 while (session->num_sources)
507                         session->sources[0].cb(-1, 0, session->sources[0].cb_data);
508         } else {
509                 /* Real sources, use g_poll() main loop. */
510                 while (session->num_sources)
511                         sr_session_iteration(session, TRUE);
512         }
513
514         return SR_OK;
515 }
516
517 /**
518  * Stop a session.
519  *
520  * The session is stopped immediately, with all acquisition sessions stopped
521  * and hardware drivers cleaned up.
522  *
523  * This must be called from within the session thread, to prevent freeing
524  * resources that the session thread will try to use.
525  *
526  * @param session The session to use. Must not be NULL.
527  *
528  * @retval SR_OK Success.
529  * @retval SR_ERR_ARG Invalid session passed.
530  *
531  * @private
532  */
533 SR_PRIV int sr_session_stop_sync(struct sr_session *session)
534 {
535         struct sr_dev_inst *sdi;
536         GSList *l;
537
538         if (!session) {
539                 sr_err("%s: session was NULL", __func__);
540                 return SR_ERR_ARG;
541         }
542
543         sr_info("Stopping.");
544
545         for (l = session->devs; l; l = l->next) {
546                 sdi = l->data;
547                 if (sdi->driver) {
548                         if (sdi->driver->dev_acquisition_stop)
549                                 sdi->driver->dev_acquisition_stop(sdi, sdi);
550                 }
551         }
552         session->running = FALSE;
553
554         return SR_OK;
555 }
556
557 /**
558  * Stop a session.
559  *
560  * The session is stopped immediately, with all acquisition sessions being
561  * stopped and hardware drivers cleaned up.
562  *
563  * If the session is run in a separate thread, this function will not block
564  * until the session is finished executing. It is the caller's responsibility
565  * to wait for the session thread to return before assuming that the session is
566  * completely decommissioned.
567  *
568  * @param session The session to use. Must not be NULL.
569  *
570  * @retval SR_OK Success.
571  * @retval SR_ERR_ARG Invalid session passed.
572  *
573  * @since 0.4.0
574  */
575 SR_API int sr_session_stop(struct sr_session *session)
576 {
577         if (!session) {
578                 sr_err("%s: session was NULL", __func__);
579                 return SR_ERR_BUG;
580         }
581
582         g_mutex_lock(&session->stop_mutex);
583         session->abort_session = TRUE;
584         g_mutex_unlock(&session->stop_mutex);
585
586         return SR_OK;
587 }
588
589 /**
590  * Debug helper.
591  *
592  * @param packet The packet to show debugging information for.
593  */
594 static void datafeed_dump(const struct sr_datafeed_packet *packet)
595 {
596         const struct sr_datafeed_logic *logic;
597         const struct sr_datafeed_analog *analog;
598
599         switch (packet->type) {
600         case SR_DF_HEADER:
601                 sr_dbg("bus: Received SR_DF_HEADER packet.");
602                 break;
603         case SR_DF_TRIGGER:
604                 sr_dbg("bus: Received SR_DF_TRIGGER packet.");
605                 break;
606         case SR_DF_META:
607                 sr_dbg("bus: Received SR_DF_META packet.");
608                 break;
609         case SR_DF_LOGIC:
610                 logic = packet->payload;
611                 sr_dbg("bus: Received SR_DF_LOGIC packet (%" PRIu64 " bytes, "
612                        "unitsize = %d).", logic->length, logic->unitsize);
613                 break;
614         case SR_DF_ANALOG:
615                 analog = packet->payload;
616                 sr_dbg("bus: Received SR_DF_ANALOG packet (%d samples).",
617                        analog->num_samples);
618                 break;
619         case SR_DF_END:
620                 sr_dbg("bus: Received SR_DF_END packet.");
621                 break;
622         case SR_DF_FRAME_BEGIN:
623                 sr_dbg("bus: Received SR_DF_FRAME_BEGIN packet.");
624                 break;
625         case SR_DF_FRAME_END:
626                 sr_dbg("bus: Received SR_DF_FRAME_END packet.");
627                 break;
628         default:
629                 sr_dbg("bus: Received unknown packet type: %d.", packet->type);
630                 break;
631         }
632 }
633
634 /**
635  * Send a packet to whatever is listening on the datafeed bus.
636  *
637  * Hardware drivers use this to send a data packet to the frontend.
638  *
639  * @param sdi TODO.
640  * @param packet The datafeed packet to send to the session bus.
641  *
642  * @retval SR_OK Success.
643  * @retval SR_ERR_ARG Invalid argument.
644  *
645  * @private
646  */
647 SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi,
648                             const struct sr_datafeed_packet *packet)
649 {
650         GSList *l;
651         struct datafeed_callback *cb_struct;
652
653         if (!sdi) {
654                 sr_err("%s: sdi was NULL", __func__);
655                 return SR_ERR_ARG;
656         }
657
658         if (!packet) {
659                 sr_err("%s: packet was NULL", __func__);
660                 return SR_ERR_ARG;
661         }
662
663         for (l = sdi->session->datafeed_callbacks; l; l = l->next) {
664                 if (sr_log_loglevel_get() >= SR_LOG_DBG)
665                         datafeed_dump(packet);
666                 cb_struct = l->data;
667                 cb_struct->cb(sdi, packet, cb_struct->cb_data);
668         }
669
670         return SR_OK;
671 }
672
673 /**
674  * Add an event source for a file descriptor.
675  *
676  * @param session The session to use. Must not be NULL.
677  * @param pollfd The GPollFD.
678  * @param[in] timeout Max time to wait before the callback is called,
679  *              ignored if 0.
680  * @param cb Callback function to add. Must not be NULL.
681  * @param cb_data Data for the callback function. Can be NULL.
682  * @param poll_object TODO.
683  *
684  * @retval SR_OK Success.
685  * @retval SR_ERR_ARG Invalid argument.
686  * @retval SR_ERR_MALLOC Memory allocation error.
687  */
688 static int _sr_session_source_add(struct sr_session *session, GPollFD *pollfd,
689                 int timeout, sr_receive_data_callback cb, void *cb_data, gintptr poll_object)
690 {
691         struct source *new_sources, *s;
692         GPollFD *new_pollfds;
693
694         if (!cb) {
695                 sr_err("%s: cb was NULL", __func__);
696                 return SR_ERR_ARG;
697         }
698
699         /* Note: cb_data can be NULL, that's not a bug. */
700
701         new_pollfds = g_try_realloc(session->pollfds,
702                         sizeof(GPollFD) * (session->num_sources + 1));
703         if (!new_pollfds) {
704                 sr_err("%s: new_pollfds malloc failed", __func__);
705                 return SR_ERR_MALLOC;
706         }
707
708         new_sources = g_try_realloc(session->sources, sizeof(struct source) *
709                         (session->num_sources + 1));
710         if (!new_sources) {
711                 sr_err("%s: new_sources malloc failed", __func__);
712                 return SR_ERR_MALLOC;
713         }
714
715         new_pollfds[session->num_sources] = *pollfd;
716         s = &new_sources[session->num_sources++];
717         s->timeout = timeout;
718         s->cb = cb;
719         s->cb_data = cb_data;
720         s->poll_object = poll_object;
721         session->pollfds = new_pollfds;
722         session->sources = new_sources;
723
724         if (timeout != session->source_timeout && timeout > 0
725             && (session->source_timeout == -1 || timeout < session->source_timeout))
726                 session->source_timeout = timeout;
727
728         return SR_OK;
729 }
730
731 /**
732  * Add an event source for a file descriptor.
733  *
734  * @param session The session to use. Must not be NULL.
735  * @param fd The file descriptor.
736  * @param events Events to check for.
737  * @param timeout Max time to wait before the callback is called, ignored if 0.
738  * @param cb Callback function to add. Must not be NULL.
739  * @param cb_data Data for the callback function. Can be NULL.
740  *
741  * @retval SR_OK Success.
742  * @retval SR_ERR_ARG Invalid argument.
743  * @retval SR_ERR_MALLOC Memory allocation error.
744  *
745  * @since 0.3.0
746  */
747 SR_API int sr_session_source_add(struct sr_session *session, int fd,
748                 int events, int timeout, sr_receive_data_callback cb, void *cb_data)
749 {
750         GPollFD p;
751
752         p.fd = fd;
753         p.events = events;
754
755         return _sr_session_source_add(session, &p, timeout, cb, cb_data, (gintptr)fd);
756 }
757
758 /**
759  * Add an event source for a GPollFD.
760  *
761  * @param session The session to use. Must not be NULL.
762  * @param pollfd The GPollFD.
763  * @param timeout Max time to wait before the callback is called, ignored if 0.
764  * @param cb Callback function to add. Must not be NULL.
765  * @param cb_data Data for the callback function. Can be NULL.
766  *
767  * @retval SR_OK Success.
768  * @retval SR_ERR_ARG Invalid argument.
769  * @retval SR_ERR_MALLOC Memory allocation error.
770  *
771  * @since 0.3.0
772  */
773 SR_API int sr_session_source_add_pollfd(struct sr_session *session,
774                 GPollFD *pollfd, int timeout, sr_receive_data_callback cb,
775                 void *cb_data)
776 {
777         return _sr_session_source_add(session, pollfd, timeout, cb,
778                                       cb_data, (gintptr)pollfd);
779 }
780
781 /**
782  * Add an event source for a GIOChannel.
783  *
784  * @param session The session to use. Must not be NULL.
785  * @param channel The GIOChannel.
786  * @param events Events to poll on.
787  * @param timeout Max time to wait before the callback is called, ignored if 0.
788  * @param cb Callback function to add. Must not be NULL.
789  * @param cb_data Data for the callback function. Can be NULL.
790  *
791  * @retval SR_OK Success.
792  * @retval SR_ERR_ARG Invalid argument.
793  * @retval SR_ERR_MALLOC Memory allocation error.
794  *
795  * @since 0.3.0
796  */
797 SR_API int sr_session_source_add_channel(struct sr_session *session,
798                 GIOChannel *channel, int events, int timeout,
799                 sr_receive_data_callback cb, void *cb_data)
800 {
801         GPollFD p;
802
803 #ifdef _WIN32
804         g_io_channel_win32_make_pollfd(channel, events, &p);
805 #else
806         p.fd = g_io_channel_unix_get_fd(channel);
807         p.events = events;
808 #endif
809
810         return _sr_session_source_add(session, &p, timeout, cb, cb_data, (gintptr)channel);
811 }
812
813 /**
814  * Remove the source belonging to the specified channel.
815  *
816  * @todo Add more error checks and logging.
817  *
818  * @param session The session to use. Must not be NULL.
819  * @param poll_object The channel for which the source should be removed.
820  *
821  * @retval SR_OK Success
822  * @retval SR_ERR_ARG Invalid arguments
823  * @retval SR_ERR_MALLOC Memory allocation error
824  * @retval SR_ERR_BUG Internal error
825  */
826 static int _sr_session_source_remove(struct sr_session *session, gintptr poll_object)
827 {
828         struct source *new_sources;
829         GPollFD *new_pollfds;
830         unsigned int old;
831
832         if (!session->sources || !session->num_sources) {
833                 sr_err("%s: sources was NULL", __func__);
834                 return SR_ERR_BUG;
835         }
836
837         for (old = 0; old < session->num_sources; old++) {
838                 if (session->sources[old].poll_object == poll_object)
839                         break;
840         }
841
842         /* fd not found, nothing to do */
843         if (old == session->num_sources)
844                 return SR_OK;
845
846         session->num_sources -= 1;
847
848         if (old != session->num_sources) {
849                 memmove(&session->pollfds[old], &session->pollfds[old+1],
850                         (session->num_sources - old) * sizeof(GPollFD));
851                 memmove(&session->sources[old], &session->sources[old+1],
852                         (session->num_sources - old) * sizeof(struct source));
853         }
854
855         new_pollfds = g_try_realloc(session->pollfds, sizeof(GPollFD) * session->num_sources);
856         if (!new_pollfds && session->num_sources > 0) {
857                 sr_err("%s: new_pollfds malloc failed", __func__);
858                 return SR_ERR_MALLOC;
859         }
860
861         new_sources = g_try_realloc(session->sources, sizeof(struct source) * session->num_sources);
862         if (!new_sources && session->num_sources > 0) {
863                 sr_err("%s: new_sources malloc failed", __func__);
864                 return SR_ERR_MALLOC;
865         }
866
867         session->pollfds = new_pollfds;
868         session->sources = new_sources;
869
870         return SR_OK;
871 }
872
873 /**
874  * Remove the source belonging to the specified file descriptor.
875  *
876  * @param session The session to use. Must not be NULL.
877  * @param fd The file descriptor for which the source should be removed.
878  *
879  * @retval SR_OK Success
880  * @retval SR_ERR_ARG Invalid argument
881  * @retval SR_ERR_MALLOC Memory allocation error.
882  * @retval SR_ERR_BUG Internal error.
883  *
884  * @since 0.3.0
885  */
886 SR_API int sr_session_source_remove(struct sr_session *session, int fd)
887 {
888         return _sr_session_source_remove(session, (gintptr)fd);
889 }
890
891 /**
892  * Remove the source belonging to the specified poll descriptor.
893  *
894  * @param session The session to use. Must not be NULL.
895  * @param pollfd The poll descriptor for which the source should be removed.
896  *
897  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
898  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
899  *         internal errors.
900  *
901  * @since 0.2.0
902  */
903 SR_API int sr_session_source_remove_pollfd(struct sr_session *session,
904                 GPollFD *pollfd)
905 {
906         return _sr_session_source_remove(session, (gintptr)pollfd);
907 }
908
909 /**
910  * Remove the source belonging to the specified channel.
911  *
912  * @param session The session to use. Must not be NULL.
913  * @param channel The channel for which the source should be removed.
914  *
915  * @retval SR_OK Success.
916  * @retval SR_ERR_ARG Invalid argument.
917  * @retval SR_ERR_MALLOC Memory allocation error.
918  * @return SR_ERR_BUG Internal error.
919  *
920  * @since 0.2.0
921  */
922 SR_API int sr_session_source_remove_channel(struct sr_session *session,
923                 GIOChannel *channel)
924 {
925         return _sr_session_source_remove(session, (gintptr)channel);
926 }
927
928 /** @} */