1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright (C) 2014 David Herrmann <dh.herrmann@gmail.com>
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
24 #include <libevdev/libevdev.h>
28 #include <systemd/sd-bus.h>
29 #include <systemd/sd-event.h>
34 #include "idev-internal.h"
36 #include "udev-util.h"
39 typedef struct idev_evdev idev_evdev;
40 typedef struct unmanaged_evdev unmanaged_evdev;
41 typedef struct managed_evdev managed_evdev;
45 struct libevdev *evdev;
47 sd_event_source *fd_src;
48 sd_event_source *idle_src;
50 bool unsync : 1; /* not in-sync with kernel */
51 bool resync : 1; /* re-syncing with kernel */
55 struct unmanaged_evdev {
60 struct managed_evdev {
63 sd_bus_slot *slot_take_device;
65 bool requested : 1; /* TakeDevice() was sent */
66 bool acquired : 1; /* TakeDevice() was successful */
69 #define idev_evdev_from_element(_e) container_of((_e), idev_evdev, element)
70 #define unmanaged_evdev_from_element(_e) \
71 container_of(idev_evdev_from_element(_e), unmanaged_evdev, evdev)
72 #define managed_evdev_from_element(_e) \
73 container_of(idev_evdev_from_element(_e), managed_evdev, evdev)
75 #define IDEV_EVDEV_INIT(_vtable, _session) ((idev_evdev){ \
76 .element = IDEV_ELEMENT_INIT((_vtable), (_session)), \
80 #define IDEV_EVDEV_NAME_MAX (8 + DECIMAL_STR_MAX(unsigned) * 2)
82 static const idev_element_vtable unmanaged_evdev_vtable;
83 static const idev_element_vtable managed_evdev_vtable;
85 static int idev_evdev_resume(idev_evdev *evdev, int dev_fd);
86 static void idev_evdev_pause(idev_evdev *evdev, bool release);
89 * Virtual Evdev Element
90 * The virtual evdev element is the base class of all other evdev elements. It
91 * uses libevdev to access the kernel evdev API. It supports asynchronous
92 * access revocation, re-syncing if events got dropped and more.
93 * This element cannot be used by itself. There must be a wrapper around it
94 * which opens a file-descriptor and passes it to the virtual evdev element.
97 static void idev_evdev_name(char *out, dev_t devnum) {
98 /* @out must be at least of size IDEV_EVDEV_NAME_MAX */
99 sprintf(out, "evdev/%u:%u", major(devnum), minor(devnum));
102 static int idev_evdev_feed_resync(idev_evdev *evdev) {
104 .type = IDEV_DATA_RESYNC,
105 .resync = evdev->resync,
108 return idev_element_feed(&evdev->element, &data);
111 static int idev_evdev_feed_evdev(idev_evdev *evdev, struct input_event *event) {
113 .type = IDEV_DATA_EVDEV,
114 .resync = evdev->resync,
120 return idev_element_feed(&evdev->element, &data);
123 static void idev_evdev_hup(idev_evdev *evdev) {
125 * On HUP, we close the current fd via idev_evdev_pause(). This drops
126 * the event-sources from the main-loop and effectively puts the
127 * element asleep. If the HUP is part of a hotplug-event, a following
128 * udev-notification will destroy the element. Otherwise, the HUP is
129 * either result of access-revokation or a serious error.
130 * For unmanaged devices, we should never receive HUP (except for
131 * unplug-events). But if we do, something went seriously wrong and we
132 * shouldn't try to be clever.
133 * Instead, we simply stay asleep and wait for the device to be
134 * disabled and then re-enabled (or closed and re-opened). This will
135 * re-open the device node and restart the device.
136 * For managed devices, a HUP usually means our device-access was
137 * revoked. In that case, we simply put the device asleep and wait for
138 * logind to notify us once the device is alive again. logind also
139 * passes us a new fd. Hence, we don't have to re-enable the device.
141 * Long story short: The only thing we have to do here, is close() the
142 * file-descriptor and remove it from the main-loop. Everything else is
143 * handled via additional events we receive.
146 idev_evdev_pause(evdev, true);
149 static int idev_evdev_io(idev_evdev *evdev) {
150 idev_element *e = &evdev->element;
151 struct input_event ev;
156 * Read input-events via libevdev until the input-queue is drained. In
157 * case we're disabled, don't do anything. The input-queue might
158 * overflow, but we don't care as we have to resync after wake-up,
160 * TODO: libevdev should give us a hint how many events to read. We
161 * really want to avoid starvation, so we shouldn't read forever in
162 * case we cannot keep up with the kernel.
163 * TODO: Make sure libevdev always reports SYN_DROPPED to us, regardless
164 * whether any event was synced afterwards.
167 flags = LIBEVDEV_READ_FLAG_NORMAL;
170 /* immediately resync, even if in sync right now */
171 evdev->unsync = false;
172 evdev->resync = false;
173 flags = LIBEVDEV_READ_FLAG_NORMAL;
174 r = libevdev_next_event(evdev->evdev, flags | LIBEVDEV_READ_FLAG_FORCE_SYNC, &ev);
175 if (r < 0 && r != -EAGAIN) {
178 } else if (r != LIBEVDEV_READ_STATUS_SYNC) {
179 log_debug("idev-evdev: %s/%s: cannot force resync: %d",
180 e->session->name, e->name, r);
183 r = libevdev_next_event(evdev->evdev, flags, &ev);
186 if (evdev->resync && r == -EAGAIN) {
188 evdev->resync = false;
189 flags = LIBEVDEV_READ_FLAG_NORMAL;
190 } else if (r == -EAGAIN) {
191 /* no data available */
196 } else if (r == LIBEVDEV_READ_STATUS_SYNC) {
199 r = idev_evdev_feed_evdev(evdev, &ev);
206 evdev->resync = true;
207 flags = LIBEVDEV_READ_FLAG_SYNC;
208 r = idev_evdev_feed_resync(evdev);
216 r = idev_evdev_feed_evdev(evdev, &ev);
225 log_debug_errno(error, "idev-evdev: %s/%s: error on data event: %m",
226 e->session->name, e->name);
230 idev_evdev_hup(evdev);
231 return 0; /* idev_evdev_hup() handles the error so discard it */
234 static int idev_evdev_event_fn(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
235 idev_evdev *evdev = userdata;
237 /* fetch data as long as EPOLLIN is signalled */
238 if (revents & EPOLLIN)
239 return idev_evdev_io(evdev);
241 if (revents & (EPOLLHUP | EPOLLERR))
242 idev_evdev_hup(evdev);
247 static int idev_evdev_idle_fn(sd_event_source *s, void *userdata) {
248 idev_evdev *evdev = userdata;
251 * The idle-event is raised whenever we have to re-sync the libevdev
252 * state from the kernel. We simply call into idev_evdev_io() which
253 * flushes the state and re-syncs it if @unsync is set.
254 * State has to be synced whenever our view of the kernel device is
255 * out of date. This is the case when we open the device, if the
256 * kernel's receive buffer overflows, or on other exceptional
257 * situations. Events during re-syncs must be forwarded to the upper
258 * layers so they can update their view of the device. However, such
259 * events must only be handled passively, as they might be out-of-order
260 * and/or re-ordered. Therefore, we mark them as 'sync' events.
266 return idev_evdev_io(evdev);
269 static void idev_evdev_destroy(idev_evdev *evdev) {
271 assert(evdev->fd < 0);
273 libevdev_free(evdev->evdev);
277 static void idev_evdev_enable(idev_evdev *evdev) {
279 assert(evdev->fd_src);
280 assert(evdev->idle_src);
284 if (evdev->fd < 0 || evdev->element.n_open < 1 || !evdev->element.enabled)
287 evdev->running = true;
288 sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_ON);
289 sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_ONESHOT);
292 static void idev_evdev_disable(idev_evdev *evdev) {
294 assert(evdev->fd_src);
295 assert(evdev->idle_src);
300 evdev->running = false;
301 idev_evdev_feed_resync(evdev);
302 sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_OFF);
303 sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_OFF);
306 static int idev_evdev_resume(idev_evdev *evdev, int dev_fd) {
307 idev_element *e = &evdev->element;
308 _cleanup_close_ int fd = dev_fd;
311 if (fd < 0 || evdev->fd == fd) {
313 idev_evdev_enable(evdev);
317 idev_evdev_pause(evdev, true);
318 log_debug("idev-evdev: %s/%s: resume", e->session->name, e->name);
320 r = fd_nonblock(fd, true);
324 r = fd_cloexec(fd, true);
328 flags = fcntl(fd, F_GETFL, 0);
333 if (flags == O_WRONLY)
336 evdev->element.readable = true;
337 evdev->element.writable = !(flags & O_RDONLY);
340 * TODO: We *MUST* re-sync the device so we get a delta of the changed
341 * state while we didn't read events from the device. This works just
342 * fine with libevdev_change_fd(), however, libevdev_new_from_fd() (or
343 * libevdev_set_fd()) don't pass us events for the initial device
344 * state. So even if we force a re-sync, we will not get the delta for
345 * the initial device state.
346 * We really need to fix libevdev to support that!
349 r = libevdev_change_fd(evdev->evdev, fd);
351 r = libevdev_new_from_fd(fd, &evdev->evdev);
356 r = sd_event_add_io(e->session->context->event,
359 EPOLLHUP | EPOLLERR | EPOLLIN,
365 r = sd_event_add_defer(e->session->context->event,
370 evdev->fd_src = sd_event_source_unref(evdev->fd_src);
374 sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_OFF);
375 sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_OFF);
377 evdev->unsync = true;
381 idev_evdev_enable(evdev);
385 static void idev_evdev_pause(idev_evdev *evdev, bool release) {
386 idev_element *e = &evdev->element;
391 log_debug("idev-evdev: %s/%s: pause", e->session->name, e->name);
393 idev_evdev_disable(evdev);
395 evdev->idle_src = sd_event_source_unref(evdev->idle_src);
396 evdev->fd_src = sd_event_source_unref(evdev->fd_src);
397 evdev->fd = safe_close(evdev->fd);
402 * Unmanaged Evdev Element
403 * The unmanaged evdev element opens the evdev node for a given input device
404 * directly (/dev/input/eventX) and thus needs sufficient privileges. It opens
405 * the device only if we really require it and releases it as soon as we're
406 * disabled or closed.
407 * The unmanaged element can be used in all situations where you have direct
408 * access to input device nodes. Unlike managed evdev elements, it can be used
409 * outside of user sessions and in emergency situations where logind is not
413 static void unmanaged_evdev_resume(idev_element *e) {
414 unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
418 * Unmanaged devices can be acquired on-demand. Therefore, don't
419 * acquire it unless someone opened the device *and* we're enabled.
421 if (e->n_open < 1 || !e->enabled)
426 fd = open(eu->devnode, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
428 if (errno != EACCES && errno != EPERM) {
429 log_debug_errno(errno, "idev-evdev: %s/%s: cannot open node %s: %m",
430 e->session->name, e->name, eu->devnode);
434 fd = open(eu->devnode, O_RDONLY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
436 log_debug_errno(errno, "idev-evdev: %s/%s: cannot open node %s: %m",
437 e->session->name, e->name, eu->devnode);
449 r = idev_evdev_resume(&eu->evdev, fd);
451 log_debug_errno(r, "idev-evdev: %s/%s: cannot resume: %m",
452 e->session->name, e->name);
455 static void unmanaged_evdev_pause(idev_element *e) {
456 unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
459 * Release the device if the device is disabled or there is no-one who
460 * opened it. This guarantees we stay only available if we're opened
464 idev_evdev_pause(&eu->evdev, true);
467 static int unmanaged_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
468 _cleanup_(idev_element_freep) idev_element *e = NULL;
469 char name[IDEV_EVDEV_NAME_MAX];
475 assert_return(s, -EINVAL);
476 assert_return(ud, -EINVAL);
478 devnode = udev_device_get_devnode(ud);
479 devnum = udev_device_get_devnum(ud);
480 if (!devnode || devnum == 0)
483 idev_evdev_name(name, devnum);
485 eu = new0(unmanaged_evdev, 1);
489 e = &eu->evdev.element;
490 eu->evdev = IDEV_EVDEV_INIT(&unmanaged_evdev_vtable, s);
492 eu->devnode = strdup(devnode);
496 r = idev_element_add(e, name);
506 static void unmanaged_evdev_free(idev_element *e) {
507 unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
509 idev_evdev_destroy(&eu->evdev);
514 static const idev_element_vtable unmanaged_evdev_vtable = {
515 .free = unmanaged_evdev_free,
516 .enable = unmanaged_evdev_resume,
517 .disable = unmanaged_evdev_pause,
518 .open = unmanaged_evdev_resume,
519 .close = unmanaged_evdev_pause,
523 * Managed Evdev Element
524 * The managed evdev element uses systemd-logind to acquire evdev devices. This
525 * means, we do not open the device node /dev/input/eventX directly. Instead,
526 * logind passes us a file-descriptor whenever our session is activated. Thus,
527 * we don't need access to the device node directly.
528 * Furthermore, whenever the session is put asleep, logind revokes the
529 * file-descriptor so we loose access to the device.
530 * Managed evdev elements should be preferred over unmanaged elements whenever
531 * you run inside a user session with exclusive device access.
534 static int managed_evdev_take_device_fn(sd_bus *bus,
535 sd_bus_message *reply,
537 sd_bus_error *ret_error) {
538 managed_evdev *em = userdata;
539 idev_element *e = &em->evdev.element;
540 idev_session *s = e->session;
543 em->slot_take_device = sd_bus_slot_unref(em->slot_take_device);
545 if (sd_bus_message_is_method_error(reply, NULL)) {
546 const sd_bus_error *error = sd_bus_message_get_error(reply);
548 log_debug("idev-evdev: %s/%s: TakeDevice failed: %s: %s",
549 s->name, e->name, error->name, error->message);
555 r = sd_bus_message_read(reply, "hb", &fd, &paused);
557 log_debug("idev-evdev: %s/%s: erroneous TakeDevice reply", s->name, e->name);
561 /* If the device is paused, ignore it; we will get the next fd via
562 * ResumeDevice signals. */
566 fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
568 log_debug_errno(errno, "idev-evdev: %s/%s: cannot duplicate evdev fd: %m", s->name, e->name);
572 r = idev_evdev_resume(&em->evdev, fd);
574 log_debug_errno(r, "idev-evdev: %s/%s: cannot resume: %m",
580 static void managed_evdev_enable(idev_element *e) {
581 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
582 managed_evdev *em = managed_evdev_from_element(e);
583 idev_session *s = e->session;
584 idev_context *c = s->context;
588 * Acquiring managed devices is heavy, so do it only once we're
589 * enabled *and* opened by someone.
591 if (e->n_open < 1 || !e->enabled)
594 /* bail out if already pending */
598 r = sd_bus_message_new_method_call(c->sysbus,
600 "org.freedesktop.login1",
602 "org.freedesktop.login1.Session",
607 r = sd_bus_message_append(m, "uu", major(em->devnum), minor(em->devnum));
611 r = sd_bus_call_async(c->sysbus,
612 &em->slot_take_device,
614 managed_evdev_take_device_fn,
620 em->requested = true;
624 log_debug_errno(r, "idev-evdev: %s/%s: cannot send TakeDevice request: %m",
628 static void managed_evdev_disable(idev_element *e) {
629 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
630 managed_evdev *em = managed_evdev_from_element(e);
631 idev_session *s = e->session;
632 idev_context *c = s->context;
636 * Releasing managed devices is heavy. Once acquired, we get
637 * notifications for sleep/wake-up events, so there's no reason to
638 * release it if disabled but opened. However, if a device is closed,
639 * we release it immediately as we don't care for sleep/wake-up events
640 * then (even if we're actually enabled).
643 idev_evdev_pause(&em->evdev, false);
645 if (e->n_open > 0 || !em->requested)
649 * If TakeDevice() is pending or was successful, make sure to
650 * release the device again. We don't care for return-values,
651 * so send it without waiting or callbacks.
652 * If a failed TakeDevice() is pending, but someone else took
653 * the device on the same bus-connection, we might incorrectly
654 * release their device. This is an unlikely race, though.
655 * Furthermore, you really shouldn't have two users of the
656 * controller-API on the same session, on the same devices, *AND* on
657 * the same bus-connection. So we don't care for that race..
660 idev_evdev_pause(&em->evdev, true);
661 em->requested = false;
663 if (!em->acquired && !em->slot_take_device)
666 em->slot_take_device = sd_bus_slot_unref(em->slot_take_device);
667 em->acquired = false;
669 r = sd_bus_message_new_method_call(c->sysbus,
671 "org.freedesktop.login1",
673 "org.freedesktop.login1.Session",
676 r = sd_bus_message_append(m, "uu", major(em->devnum), minor(em->devnum));
678 r = sd_bus_send(c->sysbus, m, NULL);
681 if (r < 0 && r != -ENOTCONN)
682 log_debug_errno(r, "idev-evdev: %s/%s: cannot send ReleaseDevice: %m",
686 static void managed_evdev_resume(idev_element *e, int fd) {
687 managed_evdev *em = managed_evdev_from_element(e);
688 idev_session *s = e->session;
692 * We get ResumeDevice signals whenever logind resumed a previously
693 * paused device. The arguments contain the major/minor number of the
694 * related device and a new file-descriptor for the freshly opened
695 * device-node. We take the file-descriptor and immediately resume the
699 fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
701 log_debug_errno(errno, "idev-evdev: %s/%s: cannot duplicate evdev fd: %m",
706 r = idev_evdev_resume(&em->evdev, fd);
708 log_debug_errno(r, "idev-evdev: %s/%s: cannot resume: %m",
714 static void managed_evdev_pause(idev_element *e, const char *mode) {
715 managed_evdev *em = managed_evdev_from_element(e);
716 idev_session *s = e->session;
717 idev_context *c = s->context;
721 * We get PauseDevice() signals from logind whenever a device we
722 * requested was, or is about to be, paused. Arguments are major/minor
723 * number of the device and the mode of the operation.
724 * We treat it as asynchronous access-revocation (as if we got HUP on
725 * the device fd). Note that we might have already treated the HUP
726 * event via EPOLLHUP, whichever comes first.
728 * @mode can be one of the following:
729 * "pause": The device is about to be paused. We must react
730 * immediately and respond with PauseDeviceComplete(). Once
731 * we replied, logind will pause the device. Note that
732 * logind might apply any kind of timeout and force pause
733 * the device if we don't respond in a timely manner. In
734 * this case, we will receive a second PauseDevice event
735 * with @mode set to "force" (or similar).
736 * "force": The device was disabled forecfully by logind. Access is
737 * already revoked. This is just an asynchronous
738 * notification so we can put the device asleep (in case
739 * we didn't already notice the access revocation).
740 * "gone": This is like "force" but is sent if the device was
741 * paused due to a device-removal event.
743 * We always handle PauseDevice signals as "force" as we properly
744 * support asynchronous access revocation, anyway. But in case logind
745 * sent mode "pause", we also call PauseDeviceComplete() to immediately
746 * acknowledge the request.
749 idev_evdev_pause(&em->evdev, true);
751 if (streq(mode, "pause")) {
752 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
755 * Sending PauseDeviceComplete() is racy if logind triggers the
756 * timeout. That is, if we take too long and logind pauses the
757 * device by sending a forced PauseDevice, our
758 * PauseDeviceComplete call will be stray. That's fine, though.
759 * logind ignores such stray calls. Only if logind also sent a
760 * further PauseDevice() signal, it might match our call
761 * incorrectly to the newer PauseDevice(). That's fine, too, as
762 * we handle that event asynchronously, anyway. Therefore,
763 * whatever happens, we're fine. Yay!
766 r = sd_bus_message_new_method_call(c->sysbus,
768 "org.freedesktop.login1",
770 "org.freedesktop.login1.Session",
771 "PauseDeviceComplete");
773 r = sd_bus_message_append(m, "uu", major(em->devnum), minor(em->devnum));
775 r = sd_bus_send(c->sysbus, m, NULL);
779 log_debug_errno(r, "idev-evdev: %s/%s: cannot send PauseDeviceComplete: %m",
784 static int managed_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
785 _cleanup_(idev_element_freep) idev_element *e = NULL;
786 char name[IDEV_EVDEV_NAME_MAX];
791 assert_return(s, -EINVAL);
792 assert_return(s->managed, -EINVAL);
793 assert_return(s->context->sysbus, -EINVAL);
794 assert_return(ud, -EINVAL);
796 devnum = udev_device_get_devnum(ud);
800 idev_evdev_name(name, devnum);
802 em = new0(managed_evdev, 1);
806 e = &em->evdev.element;
807 em->evdev = IDEV_EVDEV_INIT(&managed_evdev_vtable, s);
810 r = idev_element_add(e, name);
820 static void managed_evdev_free(idev_element *e) {
821 managed_evdev *em = managed_evdev_from_element(e);
823 idev_evdev_destroy(&em->evdev);
827 static const idev_element_vtable managed_evdev_vtable = {
828 .free = managed_evdev_free,
829 .enable = managed_evdev_enable,
830 .disable = managed_evdev_disable,
831 .open = managed_evdev_enable,
832 .close = managed_evdev_disable,
833 .resume = managed_evdev_resume,
834 .pause = managed_evdev_pause,
838 * Generic Constructor
839 * Instead of relying on the caller to choose between managed and unmanaged
840 * evdev devices, the idev_evdev_new() constructor does that for you (by
841 * looking at s->managed).
844 bool idev_is_evdev(idev_element *e) {
845 return e && (e->vtable == &unmanaged_evdev_vtable ||
846 e->vtable == &managed_evdev_vtable);
849 idev_element *idev_find_evdev(idev_session *s, dev_t devnum) {
850 char name[IDEV_EVDEV_NAME_MAX];
852 assert_return(s, NULL);
853 assert_return(devnum != 0, NULL);
855 idev_evdev_name(name, devnum);
856 return idev_find_element(s, name);
859 int idev_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
860 assert_return(s, -EINVAL);
861 assert_return(ud, -EINVAL);
863 return s->managed ? managed_evdev_new(out, s, ud) : unmanaged_evdev_new(out, s, ud);