summaryrefslogtreecommitdiff
path: root/src/uterm_monitor.c
blob: c6e0a6ddfdf2f354ea1ad3b2f02a3d70098b5a2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
/*
 * uterm - Linux User-Space Terminal
 *
 * Copyright (c) 2011-2012 David Herrmann <dh.herrmann@googlemail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * System Monitor
 * This uses systemd's login monitor to watch the system for new seats. When
 * udev reports new devices, this automatically assigns the device to the right
 * seat. Devices that are not associated to seats are ignored. If a device
 * changes seats it is automatically removed and added again.
 */

#include <errno.h>
#include <fcntl.h>
#include <libudev.h>
#include <linux/fb.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "shl_dlist.h"
#include "shl_log.h"
#include "shl_misc.h"
#include "uterm_monitor.h"
#include "uterm_systemd_internal.h"

#define LOG_SUBSYSTEM "monitor"

struct uterm_monitor_dev {
	struct shl_dlist list;
	struct uterm_monitor_seat *seat;
	unsigned int type;
	unsigned int flags;
	char *node;
	void *data;
};

struct uterm_monitor_seat {
	struct shl_dlist list;
	struct uterm_monitor *mon;
	char *name;
	void *data;
	struct shl_dlist devices;
};

struct uterm_monitor {
	unsigned long ref;
	struct ev_eloop *eloop;
	uterm_monitor_cb cb;
	void *data;

	struct uterm_sd *sd;
	struct ev_fd *sd_mon_fd;

	struct udev *udev;
	struct udev_monitor *umon;
	struct ev_fd *umon_fd;

	struct shl_dlist seats;
};

static void monitor_new_seat(struct uterm_monitor *mon, const char *name);
static void monitor_free_seat(struct uterm_monitor_seat *seat);

static void monitor_refresh_seats(struct uterm_monitor *mon)
{
	char **seats;
	int num, i;
	struct shl_dlist *iter, *tmp;
	struct uterm_monitor_seat *seat;

	/* Use only seat0 if multi-seat support is not available */
	if (!mon->sd) {
		if (shl_dlist_empty(&mon->seats))
			monitor_new_seat(mon, "seat0");
		return;
	}

	num = uterm_sd_get_seats(mon->sd, &seats);
	if (num < 0) {
		log_warn("cannot read seat information from systemd: %d", num);
		return;
	}

	/* Remove all seats that are no longer present */
	shl_dlist_for_each_safe(iter, tmp, &mon->seats) {
		seat = shl_dlist_entry(iter, struct uterm_monitor_seat,
						list);
		for (i = 0; i < num; ++i) {
			if (!strcmp(seats[i], seat->name))
				break;
		}

		if (i < num) {
			free(seats[i]);
			seats[i] = NULL;
		} else {
			monitor_free_seat(seat);
		}
	}

	/* Add all new seats */
	for (i = 0; i < num; ++i) {
		if (seats[i]) {
			monitor_new_seat(mon, seats[i]);
			free(seats[i]);
		}
	}

	free(seats);
}

static void monitor_sd_event(struct ev_fd *fd,
			     int mask,
			     void *data)
{
	struct uterm_monitor *mon = data;

	if (mask & (EV_HUP | EV_ERR)) {
		log_warn("systemd login monitor closed unexpectedly");
		return;
	}

	if (mon->sd) {
		uterm_sd_flush(mon->sd);
		ev_eloop_flush_fd(mon->eloop, mon->sd_mon_fd);
	}
	monitor_refresh_seats(mon);
}

static void monitor_sd_poll(struct uterm_monitor *mon)
{
	monitor_sd_event(mon->sd_mon_fd, EV_READABLE, mon);
}

static int monitor_sd_init(struct uterm_monitor *mon)
{
	int ret, sfd;

	ret = uterm_sd_new(&mon->sd);
	if (ret == -EOPNOTSUPP)
		return 0;
	else if (ret)
		return ret;

	sfd = uterm_sd_get_fd(mon->sd);
	if (sfd < 0) {
		log_err("cannot get systemd login monitor fd");
		ret = -EFAULT;
		goto err_sd;
	}

	ret = ev_eloop_new_fd(mon->eloop, &mon->sd_mon_fd, sfd, EV_READABLE,
			      monitor_sd_event, mon);
	if (ret)
		goto err_sd;

	return 0;

err_sd:
	uterm_sd_free(mon->sd);
	return ret;
}

static void monitor_sd_deinit(struct uterm_monitor *mon)
{
	if (!mon->sd)
		return;

	ev_eloop_rm_fd(mon->sd_mon_fd);
	uterm_sd_free(mon->sd);
}

static void seat_new_dev(struct uterm_monitor_seat *seat,
				unsigned int type,
				unsigned int flags,
				const char *node)
{
	struct uterm_monitor_dev *dev;
	struct uterm_monitor_event ev;

	dev = malloc(sizeof(*dev));
	if (!dev)
		return;
	memset(dev, 0, sizeof(*dev));
	dev->seat = seat;
	dev->type = type;
	dev->flags = flags;

	dev->node = strdup(node);
	if (!dev->node)
		goto err_free;

	shl_dlist_link(&seat->devices, &dev->list);

	memset(&ev, 0, sizeof(ev));
	ev.type = UTERM_MONITOR_NEW_DEV;
	ev.seat = dev->seat;
	ev.seat_name = dev->seat->name;
	ev.seat_data = dev->seat->data;
	ev.dev = dev;
	ev.dev_type = dev->type;
	ev.dev_flags = dev->flags;
	ev.dev_node = dev->node;
	ev.dev_data = dev->data;
	dev->seat->mon->cb(dev->seat->mon, &ev, dev->seat->mon->data);

	log_debug("new device %s on %s", node, seat->name);
	return;

err_free:
	free(dev);
}

static void seat_free_dev(struct uterm_monitor_dev *dev)
{
	struct uterm_monitor_event ev;

	log_debug("free device %s on %s", dev->node, dev->seat->name);

	shl_dlist_unlink(&dev->list);

	memset(&ev, 0, sizeof(ev));
	ev.type = UTERM_MONITOR_FREE_DEV;
	ev.seat = dev->seat;
	ev.seat_name = dev->seat->name;
	ev.seat_data = dev->seat->data;
	ev.dev = dev;
	ev.dev_type = dev->type;
	ev.dev_flags = dev->flags;
	ev.dev_node = dev->node;
	ev.dev_data = dev->data;
	dev->seat->mon->cb(dev->seat->mon, &ev, dev->seat->mon->data);

	free(dev->node);
	free(dev);
}

static struct uterm_monitor_dev *monitor_find_dev(struct uterm_monitor *mon,
						struct udev_device *dev)
{
	const char *node;
	struct shl_dlist *iter, *iter2;
	struct uterm_monitor_seat *seat;
	struct uterm_monitor_dev *sdev;

	node = udev_device_get_devnode(dev);
	if (!node)
		return NULL;

	shl_dlist_for_each(iter, &mon->seats) {
		seat = shl_dlist_entry(iter, struct uterm_monitor_seat,
						list);
		shl_dlist_for_each(iter2, &seat->devices) {
			sdev = shl_dlist_entry(iter2,
						struct uterm_monitor_dev,
						list);
			if (!strcmp(node, sdev->node))
				return sdev;
		}
	}

	return NULL;
}

static void monitor_new_seat(struct uterm_monitor *mon, const char *name)
{
	struct uterm_monitor_seat *seat;
	struct uterm_monitor_event ev;

	seat = malloc(sizeof(*seat));
	if (!seat)
		return;
	memset(seat, 0, sizeof(*seat));
	seat->mon = mon;
	shl_dlist_init(&seat->devices);

	seat->name = strdup(name);
	if (!seat->name)
		goto err_free;

	shl_dlist_link(&mon->seats, &seat->list);

	memset(&ev, 0, sizeof(ev));
	ev.type = UTERM_MONITOR_NEW_SEAT;
	ev.seat = seat;
	ev.seat_name = seat->name;
	ev.seat_data = seat->data;
	seat->mon->cb(seat->mon, &ev, seat->mon->data);

	log_debug("new seat %s", name);
	return;

err_free:
	free(seat);
}

static void monitor_free_seat(struct uterm_monitor_seat *seat)
{
	struct uterm_monitor_event ev;
	struct uterm_monitor_dev *dev;

	log_debug("free seat %s", seat->name);

	while (seat->devices.next != &seat->devices) {
		dev = shl_dlist_entry(seat->devices.next,
						struct uterm_monitor_dev,
						list);
		seat_free_dev(dev);
	}

	shl_dlist_unlink(&seat->list);

	memset(&ev, 0, sizeof(ev));
	ev.type = UTERM_MONITOR_FREE_SEAT;
	ev.seat = seat;
	ev.seat_name = seat->name;
	ev.seat_data = seat->data;
	seat->mon->cb(seat->mon, &ev, seat->mon->data);

	free(seat->name);
	free(seat);
}

static int get_card_id(struct udev_device *dev)
{
	const char *name;
	char *end;
	int devnum;

	name = udev_device_get_sysname(dev);
	if (!name)
		return -ENODEV;
	if (strncmp(name, "card", 4) || !name[4])
		return -ENODEV;

	devnum = strtol(&name[4], &end, 10);
	if (devnum < 0 || *end)
		return -ENODEV;

	return devnum;
}

static int get_fb_id(struct udev_device *dev)
{
	const char *name;
	char *end;
	int devnum;

	name = udev_device_get_sysname(dev);
	if (!name)
		return -ENODEV;
	if (strncmp(name, "fb", 2) || !name[2])
		return -ENODEV;

	devnum = strtol(&name[2], &end, 10);
	if (devnum < 0 || *end)
		return -ENODEV;

	return devnum;
}

/*
 * UTERM_MONITOR_DRM_BACKED:
 * Nearly all DRM drivers do also create fbdev nodes which refer to the same
 * hardware as the DRM devices. So we shouldn't advertise these fbdev nodes as
 * real devices. Otherwise, the user might use these and the DRM devices
 * simultaneously, thinking that they deal with two different hardware devices.
 * We also report that it is a drm-device if we actually cannot verify that it
 * is not some DRM device.
 *
 * UTERM_MONITOR_AUX:
 * Auxiliary devices are devices that are not the main GPU but rather some kind
 * of hotpluggable helpers that provide additional display controllers. This is
 * some kind of whitelist that tells the application that this GPU can safely be
 * used as additional GPU together with but also independent of the primary GPU.
 *
 * UTERM_MONITOR_PRIMARY:
 * A primary GPU is the main GPU in the system which is used to display boot
 * graphics. Older systems used to have them hardwired, but especially embedded
 * systems tend to no longer have primary GPUs so this flag cannot be guaranteed
 * to be set for all systems.
 * Hence, this flag shouldn't be used by default but rather as fallback if the
 * user selects "primary GPU only" flag or similar.
 */

static unsigned int get_fbdev_flags(struct uterm_monitor *mon, const char *node)
{
	int fd, ret, len;
	struct fb_fix_screeninfo finfo;
	unsigned int flags = UTERM_MONITOR_DRM_BACKED;

	fd = open(node, O_RDWR | O_CLOEXEC);
	if (fd < 0) {
		log_warning("cannot open fbdev node %s for drm-device verification (%d): %m",
			    node, errno);
		return flags;
	}

	ret = ioctl(fd, FBIOGET_FSCREENINFO, &finfo);
	if (ret) {
		log_warning("cannot retrieve finfo from fbdev node %s for drm-device verification (%d): %m",
			    node, errno);
		goto out_close;
	}

	/* TODO: we really need some reliable flag here that tells us that we
	 * are dealing with a DRM device indirectly. Checking for "drmfb" suffix
	 * seems fine, but that may be just luck.
	 * If this turns out to not work reliably, we can also fall back to
	 * checking whether the parent udev device node does also provide a DRM
	 * device. */
	len = strlen(finfo.id);
	if ((len < 5 || strcmp(&finfo.id[len - 5], "drmfb")) &&
	    strcmp(finfo.id, "nouveaufb") &&
	    strcmp(finfo.id, "psbfb"))
		flags &= ~UTERM_MONITOR_DRM_BACKED;

	if (!strcmp(finfo.id, "udlfb"))
		flags |= UTERM_MONITOR_AUX;
	else if (!strcmp(finfo.id, "VESA VGA"))
		flags |= UTERM_MONITOR_PRIMARY;

out_close:
	close(fd);
	return flags;
}

static bool is_drm_primary(struct uterm_monitor *mon, struct udev_device *dev,
			   const char *node)
{
	struct udev_device *pci;
	const char *id;

	pci = udev_device_get_parent_with_subsystem_devtype(dev, "pci", NULL);
	if (pci) {
		id = udev_device_get_sysattr_value(pci, "boot_vga");
		if (id && !strcmp(id, "1")) {
			log_debug("DRM device %s is primary PCI GPU", node);
			return true;
		}
	}

	return false;
}

/*
 * DRM doesn't provide public uapi headers but instead provides the ABI via
 * libdrm... GREAT! That means we either need a build-time dependency to libdrm
 * or we copy the parts we use in here. As we only need the VERSION ioctl, we
 * simply copy it from drm.h.
 */

struct uterm_drm_version {
	int version_major;	  /**< Major version */
	int version_minor;	  /**< Minor version */
	int version_patchlevel;	  /**< Patch level */
	size_t name_len;	  /**< Length of name buffer */
	char *name;	  /**< Name of driver */
	size_t date_len;	  /**< Length of date buffer */
	char *date;	  /**< User-space buffer to hold date */
	size_t desc_len;	  /**< Length of desc buffer */
	char *desc;	  /**< User-space buffer to hold desc */
};
#define UTERM_DRM_IOCTL_VERSION _IOWR('d', 0x00, struct uterm_drm_version)

static inline char *get_drm_name(int fd)
{
	struct uterm_drm_version v;
	unsigned int len;
	int ret;

	memset(&v, 0, sizeof(v));
	ret = ioctl(fd, UTERM_DRM_IOCTL_VERSION, &v);
	if (ret < 0)
		return NULL;

	if (!v.name_len)
		return NULL;

	len = v.name_len;
	v.name = malloc(len + 1);
	if (!v.name)
		return NULL;

	ret = ioctl(fd, UTERM_DRM_IOCTL_VERSION, &v);
	if (ret < 0) {
		free(v.name);
		return NULL;
	}

	v.name[len] = 0;
	return v.name;
}

static bool is_drm_usb(struct uterm_monitor *mon, const char *node, int fd)
{
	char *name;
	bool res;

	name = get_drm_name(fd);
	if (!name) {
		log_warning("cannot get driver name for DRM device %s (%d): %m",
			    node, errno);
		return false;
	}

	if (!strcmp(name, "udl"))
		res = true;
	else
		res = false;

	log_debug("DRM device %s uses driver %s", node, name);
	free(name);
	return res;
}

static unsigned int get_drm_flags(struct uterm_monitor *mon,
				  struct udev_device *dev, const char *node)
{
	int fd;
	unsigned int flags = 0;

	fd = open(node, O_RDWR | O_CLOEXEC);
	if (fd < 0) {
		log_warning("cannot open DRM device %s for primary-detection (%d): %m",
			    node, errno);
		return flags;
	}

	if (is_drm_primary(mon, dev, node))
		flags |= UTERM_MONITOR_PRIMARY;
	if (is_drm_usb(mon, node, fd))
		flags |= UTERM_MONITOR_AUX;

	close(fd);
	return flags;
}

static void monitor_udev_add(struct uterm_monitor *mon,
				struct udev_device *dev)
{
	const char *sname, *subs, *node, *name, *sysname;
	struct shl_dlist *iter;
	struct uterm_monitor_seat *seat;
	unsigned int type, flags;
	int id;
	struct udev_device *p;

	name = udev_device_get_syspath(dev);
	if (!name) {
		log_debug("cannot get syspath of udev device");
		return;
	}

	if (monitor_find_dev(mon, dev)) {
		log_debug("adding already available device %s", name);
		return;
	}

	node = udev_device_get_devnode(dev);
	if (!node)
		return;

	subs = udev_device_get_subsystem(dev);
	if (!subs) {
		log_debug("adding device with invalid subsystem %s", name);
		return;
	}

	if (!strcmp(subs, "drm")) {
		if (mon->sd && udev_device_has_tag(dev, "seat") != 1) {
			log_debug("adding non-seat'ed device %s", name);
			return;
		}
		id = get_card_id(dev);
		if (id < 0) {
			log_debug("adding drm sub-device %s", name);
			return;
		}
		sname = udev_device_get_property_value(dev, "ID_SEAT");
		type = UTERM_MONITOR_DRM;
		flags = get_drm_flags(mon, dev, node);
	} else if (!strcmp(subs, "graphics")) {
		if (mon->sd && udev_device_has_tag(dev, "seat") != 1) {
			log_debug("adding non-seat'ed device %s", name);
			return;
		}
		id = get_fb_id(dev);
		if (id < 0) {
			log_debug("adding fbdev sub-device %s", name);
			return;
		}
		sname = udev_device_get_property_value(dev, "ID_SEAT");
		type = UTERM_MONITOR_FBDEV;
		flags = get_fbdev_flags(mon, node);
	} else if (!strcmp(subs, "input")) {
		sysname = udev_device_get_sysname(dev);
		if (!sysname || strncmp(sysname, "event", 5)) {
			log_debug("adding unsupported input dev %s", name);
			return;
		}
		p = udev_device_get_parent_with_subsystem_devtype(dev,
								"input", NULL);
		if (!p) {
			log_debug("adding device without parent %s", name);
			return;
		}
		if (mon->sd && udev_device_has_tag(p, "seat") != 1) {
			log_debug("adding non-seat'ed device %s", name);
			return;
		}
		sname = udev_device_get_property_value(p, "ID_SEAT");
		type = UTERM_MONITOR_INPUT;
		flags = 0;
	} else {
		log_debug("adding device with unknown subsystem %s (%s)",
				subs, name);
		return;
	}

	if (!sname)
		sname = "seat0";

	/* find correct seat */
	shl_dlist_for_each(iter, &mon->seats) {
		seat = shl_dlist_entry(iter, struct uterm_monitor_seat,
						list);
		if (!strcmp(sname, seat->name))
			break;
	}

	if (iter == &mon->seats) {
		log_debug("adding device for unknown seat %s (%s)",
				sname, name);
		return;
	}

	seat_new_dev(seat, type, flags, node);
}

static void monitor_udev_remove(struct uterm_monitor *mon,
				struct udev_device *dev)
{
	struct uterm_monitor_dev *sdev;

	sdev = monitor_find_dev(mon, dev);
	if (!sdev) {
		log_debug("removing unknown device");
		return;
	}

	seat_free_dev(sdev);
}

static void monitor_udev_change(struct uterm_monitor *mon,
				struct udev_device *dev)
{
	const char *sname, *val;
	struct uterm_monitor_dev *sdev;
	struct uterm_monitor_event ev;

	sdev = monitor_find_dev(mon, dev);
	if (sdev) {
		sname = udev_device_get_property_value(dev, "ID_SEAT");
		if (!sname)
			sname = "seat0";
		if (strcmp(sname, sdev->seat->name)) {
			/* device switched seats; remove and add it again */
			seat_free_dev(sdev);
			monitor_udev_add(mon, dev);
			return;
		}

		/* DRM devices send hotplug events; catch them here */
		val = udev_device_get_property_value(dev, "HOTPLUG");
		if (val && !strcmp(val, "1")) {
			memset(&ev, 0, sizeof(ev));
			ev.type = UTERM_MONITOR_HOTPLUG_DEV;
			ev.seat = sdev->seat;
			ev.seat_name = sdev->seat->name;
			ev.seat_data = sdev->seat->data;
			ev.dev = sdev;
			ev.dev_type = sdev->type;
			ev.dev_node = sdev->node;
			ev.dev_data = sdev->data;
			sdev->seat->mon->cb(sdev->seat->mon, &ev,
						sdev->seat->mon->data);
		}
	} else {
		/* Unknown device; maybe it switched into a known seat? Try
		 * adding it as new device. If that fails, we ignore it */
		monitor_udev_add(mon, dev);
	}
}

static void monitor_udev_event(struct ev_fd *fd,
				int mask,
				void *data)
{
	struct uterm_monitor *mon = data;
	struct udev_device *dev;
	const char *action;

	if (mask & (EV_HUP | EV_ERR)) {
		log_warn("udev monitor closed unexpectedly");
		return;
	}

	/*
	 * If there is a pending sd_event in the current epoll-queue and our
	 * udev event is called first, we must make sure to first execute the
	 * sd_event. Otherwise, our udev event might introduce new seats that
	 * will be initialized later and we loose devices.
	 * monitor_sd_event() flushes the sd-fd so we will never refresh seat
	 * values twice in a single epoll-loop.
	 */
	monitor_sd_poll(mon);

	while (true) {
		/* we use non-blocking udev monitor so ignore errors */
		dev = udev_monitor_receive_device(mon->umon);
		if (!dev)
			return;

		action = udev_device_get_action(dev);
		if (action) {
			if (!strcmp(action, "add"))
				monitor_udev_add(mon, dev);
			else if (!strcmp(action, "remove"))
				monitor_udev_remove(mon, dev);
			else if (!strcmp(action, "change"))
				monitor_udev_change(mon, dev);
		}

		udev_device_unref(dev);
	}
}

SHL_EXPORT
int uterm_monitor_new(struct uterm_monitor **out,
			struct ev_eloop *eloop,
			uterm_monitor_cb cb,
			void *data)
{
	struct uterm_monitor *mon;
	int ret, ufd, set;

	if (!out || !eloop || !cb)
		return -EINVAL;

	mon = malloc(sizeof(*mon));
	if (!mon)
		return -EINVAL;
	memset(mon, 0, sizeof(*mon));
	mon->ref = 1;
	mon->eloop = eloop;
	mon->cb = cb;
	mon->data = data;
	shl_dlist_init(&mon->seats);

	ret = monitor_sd_init(mon);
	if (ret)
		goto err_free;

	mon->udev = udev_new();
	if (!mon->udev) {
		log_err("cannot create udev object");
		ret = -EFAULT;
		goto err_sd;
	}

	mon->umon = udev_monitor_new_from_netlink(mon->udev, "udev");
	if (!mon->umon) {
		log_err("cannot create udev monitor");
		ret = -EFAULT;
		goto err_udev;
	}

	ret = udev_monitor_filter_add_match_subsystem_devtype(mon->umon,
							"drm", "drm_minor");
	if (ret) {
		errno = -ret;
		log_err("cannot add udev filter (%d): %m", ret);
		ret = -EFAULT;
		goto err_umon;
	}

	ret = udev_monitor_filter_add_match_subsystem_devtype(mon->umon,
							"graphics", NULL);
	if (ret) {
		errno = -ret;
		log_err("cannot add udev filter (%d): %m", ret);
		ret = -EFAULT;
		goto err_umon;
	}

	ret = udev_monitor_filter_add_match_subsystem_devtype(mon->umon,
							"input", NULL);
	if (ret) {
		errno = -ret;
		log_err("cannot add udev filter (%d): %m", ret);
		ret = -EFAULT;
		goto err_umon;
	}

	ret = udev_monitor_enable_receiving(mon->umon);
	if (ret) {
		errno = -ret;
		log_err("cannot start udev monitor (%d): %m", ret);
		ret = -EFAULT;
		goto err_umon;
	}

	ufd = udev_monitor_get_fd(mon->umon);
	if (ufd < 0) {
		log_err("cannot get udev monitor fd");
		ret = -EFAULT;
		goto err_umon;
	}

	set = fcntl(ufd, F_GETFL);
	if (set < 0) {
		log_err("cannot get udev monitor fd flags");
		ret = -EFAULT;
		goto err_umon;
	}

	set |= O_NONBLOCK;
	ret = fcntl(ufd, F_SETFL, set);
	if (ret != 0) {
		log_err("cannot set udev monitor fd flags");
		ret = -EFAULT;
		goto err_umon;
	}

	ret = ev_eloop_new_fd(mon->eloop, &mon->umon_fd, ufd, EV_READABLE,
				monitor_udev_event, mon);
	if (ret)
		goto err_umon;

	ev_eloop_ref(mon->eloop);
	*out = mon;
	return 0;

err_umon:
	udev_monitor_unref(mon->umon);
err_udev:
	udev_unref(mon->udev);
err_sd:
	monitor_sd_deinit(mon);
err_free:
	free(mon);
	return ret;
}

SHL_EXPORT
void uterm_monitor_ref(struct uterm_monitor *mon)
{
	if (!mon || !mon->ref)
		return;

	++mon->ref;
}

SHL_EXPORT
void uterm_monitor_unref(struct uterm_monitor *mon)
{
	struct uterm_monitor_seat *seat;

	if (!mon || !mon->ref || --mon->ref)
		return;

	while (mon->seats.next != &mon->seats) {
		seat = shl_dlist_entry(mon->seats.next,
						struct uterm_monitor_seat,
						list);
		monitor_free_seat(seat);
	}

	ev_eloop_rm_fd(mon->umon_fd);
	udev_monitor_unref(mon->umon);
	udev_unref(mon->udev);
	monitor_sd_deinit(mon);
	ev_eloop_unref(mon->eloop);
	free(mon);
}

SHL_EXPORT
void uterm_monitor_scan(struct uterm_monitor *mon)
{
	struct udev_enumerate *e;
	struct udev_list_entry *entry;
	struct udev_device *dev;
	const char *path;
	int ret;

	if (!mon)
		return;

	monitor_refresh_seats(mon);

	e = udev_enumerate_new(mon->udev);
	if (!e) {
		log_err("cannot create udev enumeration");
		return;
	}

	ret = udev_enumerate_add_match_subsystem(e, "drm");
	if (ret) {
		errno = -ret;
		log_err("cannot add udev match (%d): %m", ret);
		goto out_enum;
	}

	ret = udev_enumerate_add_match_subsystem(e, "graphics");
	if (ret) {
		errno = -ret;
		log_err("cannot add udev match (%d): %m", ret);
		goto out_enum;
	}

	ret = udev_enumerate_add_match_subsystem(e, "input");
	if (ret) {
		errno = -ret;
		log_err("cannot add udev match (%d): %m", ret);
		goto out_enum;
	}

	ret = udev_enumerate_scan_devices(e);
	if (ret) {
		log_err("cannot scan udev devices (%d): %m", ret);
		goto out_enum;
	}

	udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
		path = udev_list_entry_get_name(entry);
		if (!path) {
			log_debug("udev device without syspath");
			continue;
		}
		dev = udev_device_new_from_syspath(mon->udev, path);
		if (!dev) {
			log_debug("cannot get udev device for %s", path);
			continue;
		}

		monitor_udev_add(mon, dev);
		udev_device_unref(dev);
	}

out_enum:
	udev_enumerate_unref(e);
}

SHL_EXPORT
void uterm_monitor_set_seat_data(struct uterm_monitor_seat *seat, void *data)
{
	if (!seat)
		return;

	seat->data = data;
}

SHL_EXPORT
void uterm_monitor_set_dev_data(struct uterm_monitor_dev *dev, void *data)
{
	if (!dev)
		return;

	dev->data = data;
}