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