1 /*
2  * This work is licensed under the terms of the GNU GPL, version 2 or
3  * (at your option) any later version.  See the COPYING file in the
4  * top-level directory.
5  */
6 
7 #include "qemu/osdep.h"
8 
9 #include <glib.h>
10 #include <linux/input.h>
11 
12 #include "qemu/iov.h"
13 #include "qemu/bswap.h"
14 #include "qemu/sockets.h"
15 #include "contrib/libvhost-user/libvhost-user.h"
16 #include "contrib/libvhost-user/libvhost-user-glib.h"
17 #include "standard-headers/linux/virtio_input.h"
18 #include "qapi/error.h"
19 
20 typedef struct virtio_input_event virtio_input_event;
21 typedef struct virtio_input_config virtio_input_config;
22 
23 typedef struct VuInput {
24     VugDev dev;
25     GSource *evsrc;
26     int evdevfd;
27     GArray *config;
28     virtio_input_config *sel_config;
29     struct {
30         virtio_input_event event;
31         VuVirtqElement *elem;
32     } *queue;
33     uint32_t qindex, qsize;
34 } VuInput;
35 
36 static void vi_input_send(VuInput *vi, struct virtio_input_event *event)
37 {
38     VuDev *dev = &vi->dev.parent;
39     VuVirtq *vq = vu_get_queue(dev, 0);
40     VuVirtqElement *elem;
41     int i, len;
42 
43     /* queue up events ... */
44     if (vi->qindex == vi->qsize) {
45         vi->qsize++;
46         vi->queue = g_realloc_n(vi->queue, vi->qsize, sizeof(vi->queue[0]));
47     }
48     vi->queue[vi->qindex++].event = *event;
49 
50     /* ... until we see a report sync ... */
51     if (event->type != htole16(EV_SYN) ||
52         event->code != htole16(SYN_REPORT)) {
53         return;
54     }
55 
56     /* ... then check available space ... */
57     for (i = 0; i < vi->qindex; i++) {
58         elem = vu_queue_pop(dev, vq, sizeof(VuVirtqElement));
59         if (!elem) {
60             while (--i >= 0) {
61                 vu_queue_unpop(dev, vq, vi->queue[i].elem, 0);
62             }
63             vi->qindex = 0;
64             g_warning("virtio-input queue full");
65             return;
66         }
67         vi->queue[i].elem = elem;
68     }
69 
70     /* ... and finally pass them to the guest */
71     for (i = 0; i < vi->qindex; i++) {
72         elem = vi->queue[i].elem;
73         len = iov_from_buf(elem->in_sg, elem->in_num,
74                            0, &vi->queue[i].event, sizeof(virtio_input_event));
75         vu_queue_push(dev, vq, elem, len);
76         g_free(elem);
77     }
78 
79     vu_queue_notify(&vi->dev.parent, vq);
80     vi->qindex = 0;
81 }
82 
83 static void
84 vi_evdev_watch(VuDev *dev, int condition, void *data)
85 {
86     VuInput *vi = data;
87     int fd = vi->evdevfd;
88 
89     g_debug("Got evdev condition %x", condition);
90 
91     struct virtio_input_event virtio;
92     struct input_event evdev;
93     int rc;
94 
95     for (;;) {
96         rc = read(fd, &evdev, sizeof(evdev));
97         if (rc != sizeof(evdev)) {
98             break;
99         }
100 
101         g_debug("input %d %d %d", evdev.type, evdev.code, evdev.value);
102 
103         virtio.type  = htole16(evdev.type);
104         virtio.code  = htole16(evdev.code);
105         virtio.value = htole32(evdev.value);
106         vi_input_send(vi, &virtio);
107     }
108 }
109 
110 
111 static void vi_handle_status(VuInput *vi, virtio_input_event *event)
112 {
113     struct input_event evdev;
114     int rc;
115 
116     if (gettimeofday(&evdev.time, NULL)) {
117         perror("vi_handle_status: gettimeofday");
118         return;
119     }
120 
121     evdev.type = le16toh(event->type);
122     evdev.code = le16toh(event->code);
123     evdev.value = le32toh(event->value);
124 
125     rc = write(vi->evdevfd, &evdev, sizeof(evdev));
126     if (rc == -1) {
127         perror("vi_host_handle_status: write");
128     }
129 }
130 
131 static void vi_handle_sts(VuDev *dev, int qidx)
132 {
133     VuInput *vi = container_of(dev, VuInput, dev.parent);
134     VuVirtq *vq = vu_get_queue(dev, qidx);
135     virtio_input_event event;
136     VuVirtqElement *elem;
137     int len;
138 
139     g_debug("%s", G_STRFUNC);
140 
141     for (;;) {
142         elem = vu_queue_pop(dev, vq, sizeof(VuVirtqElement));
143         if (!elem) {
144             break;
145         }
146 
147         memset(&event, 0, sizeof(event));
148         len = iov_to_buf(elem->out_sg, elem->out_num,
149                          0, &event, sizeof(event));
150         vi_handle_status(vi, &event);
151         vu_queue_push(dev, vq, elem, len);
152         g_free(elem);
153     }
154 
155     vu_queue_notify(&vi->dev.parent, vq);
156 }
157 
158 static void
159 vi_panic(VuDev *dev, const char *msg)
160 {
161     g_critical("%s\n", msg);
162     exit(EXIT_FAILURE);
163 }
164 
165 static void
166 vi_queue_set_started(VuDev *dev, int qidx, bool started)
167 {
168     VuInput *vi = container_of(dev, VuInput, dev.parent);
169     VuVirtq *vq = vu_get_queue(dev, qidx);
170 
171     g_debug("queue started %d:%d", qidx, started);
172 
173     if (qidx == 1) {
174         vu_set_queue_handler(dev, vq, started ? vi_handle_sts : NULL);
175     }
176 
177     started = vu_queue_started(dev, vu_get_queue(dev, 0)) &&
178         vu_queue_started(dev, vu_get_queue(dev, 1));
179 
180     if (started && !vi->evsrc) {
181         vi->evsrc = vug_source_new(&vi->dev, vi->evdevfd,
182                                    G_IO_IN, vi_evdev_watch, vi);
183     }
184 
185     if (!started && vi->evsrc) {
186         g_source_destroy(vi->evsrc);
187         vi->evsrc = NULL;
188     }
189 }
190 
191 static virtio_input_config *
192 vi_find_config(VuInput *vi, uint8_t select, uint8_t subsel)
193 {
194     virtio_input_config *cfg;
195     int i;
196 
197     for (i = 0; i < vi->config->len; i++) {
198         cfg = &g_array_index(vi->config, virtio_input_config, i);
199         if (select == cfg->select && subsel == cfg->subsel) {
200             return cfg;
201         }
202     }
203 
204     return NULL;
205 }
206 
207 static int vi_get_config(VuDev *dev, uint8_t *config, uint32_t len)
208 {
209     VuInput *vi = container_of(dev, VuInput, dev.parent);
210 
211     g_return_val_if_fail(len <= sizeof(*vi->sel_config), -1);
212 
213     if (vi->sel_config) {
214         memcpy(config, vi->sel_config, len);
215     } else {
216         memset(config, 0, len);
217     }
218 
219     return 0;
220 }
221 
222 static int vi_set_config(VuDev *dev, const uint8_t *data,
223                          uint32_t offset, uint32_t size,
224                          uint32_t flags)
225 {
226     VuInput *vi = container_of(dev, VuInput, dev.parent);
227     virtio_input_config *config = (virtio_input_config *)data;
228 
229     vi->sel_config = vi_find_config(vi, config->select, config->subsel);
230 
231     return 0;
232 }
233 
234 static const VuDevIface vuiface = {
235     .queue_set_started = vi_queue_set_started,
236     .get_config = vi_get_config,
237     .set_config = vi_set_config,
238 };
239 
240 static void
241 vi_bits_config(VuInput *vi, int type, int count)
242 {
243     virtio_input_config bits;
244     int rc, i, size = 0;
245 
246     memset(&bits, 0, sizeof(bits));
247     rc = ioctl(vi->evdevfd, EVIOCGBIT(type, count / 8), bits.u.bitmap);
248     if (rc < 0) {
249         return;
250     }
251 
252     for (i = 0; i < count / 8; i++) {
253         if (bits.u.bitmap[i]) {
254             size = i + 1;
255         }
256     }
257     if (size == 0) {
258         return;
259     }
260 
261     bits.select = VIRTIO_INPUT_CFG_EV_BITS;
262     bits.subsel = type;
263     bits.size   = size;
264     g_array_append_val(vi->config, bits);
265 }
266 
267 static char *opt_evdev;
268 static int opt_fdnum = -1;
269 static char *opt_socket_path;
270 static gboolean opt_nograb;
271 static gboolean opt_print_caps;
272 
273 static GOptionEntry entries[] = {
274     { "print-capabilities", 'c', 0, G_OPTION_ARG_NONE, &opt_print_caps,
275       "Print capabilities", NULL },
276     { "no-grab", 'n', 0, G_OPTION_ARG_NONE, &opt_nograb,
277       "Don't grab device", NULL },
278     { "fd", 'f', 0, G_OPTION_ARG_INT, &opt_fdnum,
279       "Use inherited fd socket", "FDNUM" },
280     { "socket-path", 's', 0, G_OPTION_ARG_FILENAME, &opt_socket_path,
281       "Use UNIX socket path", "PATH" },
282     { "evdev-path", 'p', 0, G_OPTION_ARG_FILENAME, &opt_evdev,
283       "evdev input device path", "PATH" },
284     { NULL, }
285 };
286 
287 int
288 main(int argc, char *argv[])
289 {
290     GMainLoop *loop = NULL;
291     VuInput vi = { 0, };
292     int rc, ver, fd;
293     virtio_input_config id;
294     struct input_id ids;
295     GError *error = NULL;
296     GOptionContext *context;
297 
298     context = g_option_context_new(NULL);
299     g_option_context_add_main_entries(context, entries, NULL);
300     if (!g_option_context_parse(context, &argc, &argv, &error)) {
301         g_printerr("Option parsing failed: %s\n", error->message);
302         exit(EXIT_FAILURE);
303     }
304     if (opt_print_caps) {
305         g_print("{\n");
306         g_print("  \"type\": \"input\",\n");
307         g_print("  \"features\": [\n");
308         g_print("    \"evdev-path\",\n");
309         g_print("    \"no-grab\"\n");
310         g_print("  ]\n");
311         g_print("}\n");
312         exit(EXIT_SUCCESS);
313     }
314     if (!opt_evdev) {
315         g_printerr("Please specify an evdev path\n");
316         exit(EXIT_FAILURE);
317     }
318     if ((!!opt_socket_path + (opt_fdnum != -1)) != 1) {
319         g_printerr("Please specify either --fd or --socket-path\n");
320         exit(EXIT_FAILURE);
321     }
322 
323     vi.evdevfd = open(opt_evdev, O_RDWR);
324     if (vi.evdevfd < 0) {
325         g_printerr("Failed to open evdev: %s\n", g_strerror(errno));
326         exit(EXIT_FAILURE);
327     }
328 
329     rc = ioctl(vi.evdevfd, EVIOCGVERSION, &ver);
330     if (rc < 0) {
331         g_printerr("%s: is not an evdev device\n", argv[1]);
332         exit(EXIT_FAILURE);
333     }
334 
335     if (!opt_nograb) {
336         rc = ioctl(vi.evdevfd, EVIOCGRAB, 1);
337         if (rc < 0) {
338             g_printerr("Failed to grab device\n");
339             exit(EXIT_FAILURE);
340         }
341     }
342 
343     vi.config = g_array_new(false, false, sizeof(virtio_input_config));
344     memset(&id, 0, sizeof(id));
345     if (ioctl(vi.evdevfd, EVIOCGNAME(sizeof(id.u.string) - 1),
346               id.u.string) < 0) {
347         g_printerr("Failed to get evdev name: %s\n", g_strerror(errno));
348         exit(EXIT_FAILURE);
349     }
350     id.select = VIRTIO_INPUT_CFG_ID_NAME;
351     id.size = strlen(id.u.string);
352     g_array_append_val(vi.config, id);
353 
354     if (ioctl(vi.evdevfd, EVIOCGID, &ids) == 0) {
355         memset(&id, 0, sizeof(id));
356         id.select = VIRTIO_INPUT_CFG_ID_DEVIDS;
357         id.size = sizeof(struct virtio_input_devids);
358         id.u.ids.bustype = cpu_to_le16(ids.bustype);
359         id.u.ids.vendor  = cpu_to_le16(ids.vendor);
360         id.u.ids.product = cpu_to_le16(ids.product);
361         id.u.ids.version = cpu_to_le16(ids.version);
362         g_array_append_val(vi.config, id);
363     }
364 
365     vi_bits_config(&vi, EV_KEY, KEY_CNT);
366     vi_bits_config(&vi, EV_REL, REL_CNT);
367     vi_bits_config(&vi, EV_ABS, ABS_CNT);
368     vi_bits_config(&vi, EV_MSC, MSC_CNT);
369     vi_bits_config(&vi, EV_SW,  SW_CNT);
370     g_debug("config length: %u", vi.config->len);
371 
372     if (opt_socket_path) {
373         int lsock = unix_listen(opt_socket_path, &error_fatal);
374         if (lsock < 0) {
375             g_printerr("Failed to listen on %s.\n", opt_socket_path);
376             exit(EXIT_FAILURE);
377         }
378         fd = accept(lsock, NULL, NULL);
379         close(lsock);
380     } else {
381         fd = opt_fdnum;
382     }
383     if (fd == -1) {
384         g_printerr("Invalid vhost-user socket.\n");
385         exit(EXIT_FAILURE);
386     }
387     vug_init(&vi.dev, fd, vi_panic, &vuiface);
388 
389     loop = g_main_loop_new(NULL, FALSE);
390     g_main_loop_run(loop);
391     g_main_loop_unref(loop);
392 
393     vug_deinit(&vi.dev);
394 
395     if (vi.evsrc) {
396         g_source_unref(vi.evsrc);
397     }
398     g_array_free(vi.config, TRUE);
399     g_free(vi.queue);
400     return 0;
401 }
402