intel_iommu: redo configuraton check in realize
[qemu.git] / qemu-char.c
blobd83a89618e19709e3c7715c7dd3b1681a3f94ffd
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "qemu-common.h"
26 #include "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/error-report.h"
31 #include "qemu/timer.h"
32 #include "sysemu/char.h"
33 #include "hw/usb.h"
34 #include "qmp-commands.h"
35 #include "qapi/clone-visitor.h"
36 #include "qapi-visit.h"
37 #include "qemu/base64.h"
38 #include "io/channel-socket.h"
39 #include "io/channel-file.h"
40 #include "io/channel-tls.h"
41 #include "sysemu/replay.h"
42 #include "qemu/help_option.h"
44 #include <zlib.h>
46 #ifndef _WIN32
47 #include <sys/times.h>
48 #include <sys/wait.h>
49 #include <termios.h>
50 #include <sys/ioctl.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <net/if.h>
55 #include <arpa/inet.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef CONFIG_BSD
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
60 #include <dev/ppbus/ppi.h>
61 #include <dev/ppbus/ppbconf.h>
62 #elif defined(__DragonFly__)
63 #include <dev/misc/ppi/ppi.h>
64 #include <bus/ppbus/ppbconf.h>
65 #endif
66 #else
67 #ifdef __linux__
68 #include <linux/ppdev.h>
69 #include <linux/parport.h>
70 #endif
71 #ifdef __sun__
72 #include <sys/ethernet.h>
73 #include <sys/sockio.h>
74 #include <netinet/arp.h>
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_icmp.h> // must come after ip.h
79 #include <netinet/udp.h>
80 #include <netinet/tcp.h>
81 #endif
82 #endif
83 #endif
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
89 #define READ_RETRIES 10
90 #define TCP_MAX_FDS 16
92 /***********************************************************/
93 /* Socket address helpers */
95 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
96 bool is_listen, bool is_telnet)
98 switch (addr->type) {
99 case SOCKET_ADDRESS_KIND_INET:
100 return g_strdup_printf("%s%s:%s:%s%s", prefix,
101 is_telnet ? "telnet" : "tcp",
102 addr->u.inet.data->host,
103 addr->u.inet.data->port,
104 is_listen ? ",server" : "");
105 break;
106 case SOCKET_ADDRESS_KIND_UNIX:
107 return g_strdup_printf("%sunix:%s%s", prefix,
108 addr->u.q_unix.data->path,
109 is_listen ? ",server" : "");
110 break;
111 case SOCKET_ADDRESS_KIND_FD:
112 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
113 is_listen ? ",server" : "");
114 break;
115 default:
116 abort();
120 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
121 struct sockaddr_storage *ps, socklen_t ps_len,
122 bool is_listen, bool is_telnet)
124 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
125 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
126 const char *left = "", *right = "";
128 switch (ss->ss_family) {
129 #ifndef _WIN32
130 case AF_UNIX:
131 return g_strdup_printf("unix:%s%s",
132 ((struct sockaddr_un *)(ss))->sun_path,
133 is_listen ? ",server" : "");
134 #endif
135 case AF_INET6:
136 left = "[";
137 right = "]";
138 /* fall through */
139 case AF_INET:
140 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
141 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
142 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
143 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
145 is_telnet ? "telnet" : "tcp",
146 left, shost, right, sserv,
147 is_listen ? ",server" : "",
148 left, phost, right, pserv);
150 default:
151 return g_strdup_printf("unknown");
155 /***********************************************************/
156 /* character device */
158 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
159 QTAILQ_HEAD_INITIALIZER(chardevs);
161 static void qemu_chr_free_common(CharDriverState *chr);
163 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
165 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
166 qemu_mutex_init(&chr->chr_write_lock);
168 if (backend->has_logfile) {
169 int flags = O_WRONLY | O_CREAT;
170 if (backend->has_logappend &&
171 backend->logappend) {
172 flags |= O_APPEND;
173 } else {
174 flags |= O_TRUNC;
176 chr->logfd = qemu_open(backend->logfile, flags, 0666);
177 if (chr->logfd < 0) {
178 error_setg_errno(errp, errno,
179 "Unable to open logfile %s",
180 backend->logfile);
181 g_free(chr);
182 return NULL;
184 } else {
185 chr->logfd = -1;
188 return chr;
191 void qemu_chr_be_event(CharDriverState *s, int event)
193 /* Keep track if the char device is open */
194 switch (event) {
195 case CHR_EVENT_OPENED:
196 s->be_open = 1;
197 break;
198 case CHR_EVENT_CLOSED:
199 s->be_open = 0;
200 break;
203 if (!s->chr_event)
204 return;
205 s->chr_event(s->handler_opaque, event);
208 void qemu_chr_be_generic_open(CharDriverState *s)
210 qemu_chr_be_event(s, CHR_EVENT_OPENED);
214 /* Not reporting errors from writing to logfile, as logs are
215 * defined to be "best effort" only */
216 static void qemu_chr_fe_write_log(CharDriverState *s,
217 const uint8_t *buf, size_t len)
219 size_t done = 0;
220 ssize_t ret;
222 if (s->logfd < 0) {
223 return;
226 while (done < len) {
227 retry:
228 ret = write(s->logfd, buf + done, len - done);
229 if (ret == -1 && errno == EAGAIN) {
230 g_usleep(100);
231 goto retry;
234 if (ret <= 0) {
235 return;
237 done += ret;
241 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
243 int res = 0;
244 *offset = 0;
246 qemu_mutex_lock(&s->chr_write_lock);
247 while (*offset < len) {
248 retry:
249 res = s->chr_write(s, buf + *offset, len - *offset);
250 if (res < 0 && errno == EAGAIN) {
251 g_usleep(100);
252 goto retry;
255 if (res <= 0) {
256 break;
259 *offset += res;
261 if (*offset > 0) {
262 qemu_chr_fe_write_log(s, buf, *offset);
264 qemu_mutex_unlock(&s->chr_write_lock);
266 return res;
269 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
271 int ret;
273 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
274 int offset;
275 replay_char_write_event_load(&ret, &offset);
276 assert(offset <= len);
277 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
278 return ret;
281 qemu_mutex_lock(&s->chr_write_lock);
282 ret = s->chr_write(s, buf, len);
284 if (ret > 0) {
285 qemu_chr_fe_write_log(s, buf, ret);
288 qemu_mutex_unlock(&s->chr_write_lock);
290 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
291 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
294 return ret;
297 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
299 int offset;
300 int res;
302 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
303 replay_char_write_event_load(&res, &offset);
304 assert(offset <= len);
305 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
306 return res;
309 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
311 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
312 replay_char_write_event_save(res, offset);
315 if (res < 0) {
316 return res;
318 return offset;
321 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
323 int offset = 0, counter = 10;
324 int res;
326 if (!s->chr_sync_read) {
327 return 0;
330 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
331 return replay_char_read_all_load(buf);
334 while (offset < len) {
335 retry:
336 res = s->chr_sync_read(s, buf + offset, len - offset);
337 if (res == -1 && errno == EAGAIN) {
338 g_usleep(100);
339 goto retry;
342 if (res == 0) {
343 break;
346 if (res < 0) {
347 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
348 replay_char_read_all_save_error(res);
350 return res;
353 offset += res;
355 if (!counter--) {
356 break;
360 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
361 replay_char_read_all_save_buf(buf, offset);
363 return offset;
366 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
368 int res;
369 if (!s->chr_ioctl || s->replay) {
370 res = -ENOTSUP;
371 } else {
372 res = s->chr_ioctl(s, cmd, arg);
375 return res;
378 int qemu_chr_be_can_write(CharDriverState *s)
380 if (!s->chr_can_read)
381 return 0;
382 return s->chr_can_read(s->handler_opaque);
385 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
387 if (s->chr_read) {
388 s->chr_read(s->handler_opaque, buf, len);
392 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
394 if (s->replay) {
395 if (replay_mode == REPLAY_MODE_PLAY) {
396 return;
398 replay_chr_be_write(s, buf, len);
399 } else {
400 qemu_chr_be_write_impl(s, buf, len);
404 int qemu_chr_fe_get_msgfd(CharDriverState *s)
406 int fd;
407 int res = (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
408 if (s->replay) {
409 fprintf(stderr,
410 "Replay: get msgfd is not supported for serial devices yet\n");
411 exit(1);
413 return res;
416 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
418 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
421 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
423 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
426 int qemu_chr_add_client(CharDriverState *s, int fd)
428 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
431 void qemu_chr_accept_input(CharDriverState *s)
433 if (s->chr_accept_input)
434 s->chr_accept_input(s);
435 qemu_notify_event();
438 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
440 char buf[READ_BUF_LEN];
441 va_list ap;
442 va_start(ap, fmt);
443 vsnprintf(buf, sizeof(buf), fmt, ap);
444 /* XXX this blocks entire thread. Rewrite to use
445 * qemu_chr_fe_write and background I/O callbacks */
446 qemu_chr_fe_write_all(s, (uint8_t *)buf, strlen(buf));
447 va_end(ap);
450 static void remove_fd_in_watch(CharDriverState *chr);
452 void qemu_chr_add_handlers_full(CharDriverState *s,
453 IOCanReadHandler *fd_can_read,
454 IOReadHandler *fd_read,
455 IOEventHandler *fd_event,
456 void *opaque,
457 GMainContext *context)
459 int fe_open;
461 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
462 fe_open = 0;
463 remove_fd_in_watch(s);
464 } else {
465 fe_open = 1;
467 s->chr_can_read = fd_can_read;
468 s->chr_read = fd_read;
469 s->chr_event = fd_event;
470 s->handler_opaque = opaque;
471 if (s->chr_update_read_handler) {
472 s->chr_update_read_handler(s, context);
475 if (!s->explicit_fe_open) {
476 qemu_chr_fe_set_open(s, fe_open);
479 /* We're connecting to an already opened device, so let's make sure we
480 also get the open event */
481 if (fe_open && s->be_open) {
482 qemu_chr_be_generic_open(s);
486 void qemu_chr_add_handlers(CharDriverState *s,
487 IOCanReadHandler *fd_can_read,
488 IOReadHandler *fd_read,
489 IOEventHandler *fd_event,
490 void *opaque)
492 qemu_chr_add_handlers_full(s, fd_can_read, fd_read,
493 fd_event, opaque, NULL);
496 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
498 return len;
501 static CharDriverState *qemu_chr_open_null(const char *id,
502 ChardevBackend *backend,
503 ChardevReturn *ret,
504 Error **errp)
506 CharDriverState *chr;
507 ChardevCommon *common = backend->u.null.data;
509 chr = qemu_chr_alloc(common, errp);
510 if (!chr) {
511 return NULL;
513 chr->chr_write = null_chr_write;
514 chr->explicit_be_open = true;
515 return chr;
518 /* MUX driver for serial I/O splitting */
519 #define MAX_MUX 4
520 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
521 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
522 typedef struct {
523 IOCanReadHandler *chr_can_read[MAX_MUX];
524 IOReadHandler *chr_read[MAX_MUX];
525 IOEventHandler *chr_event[MAX_MUX];
526 void *ext_opaque[MAX_MUX];
527 CharDriverState *drv;
528 int focus;
529 int mux_cnt;
530 int term_got_escape;
531 int max_size;
532 /* Intermediate input buffer allows to catch escape sequences even if the
533 currently active device is not accepting any input - but only until it
534 is full as well. */
535 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
536 int prod[MAX_MUX];
537 int cons[MAX_MUX];
538 int timestamps;
540 /* Protected by the CharDriverState chr_write_lock. */
541 int linestart;
542 int64_t timestamps_start;
543 } MuxDriver;
546 /* Called with chr_write_lock held. */
547 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
549 MuxDriver *d = chr->opaque;
550 int ret;
551 if (!d->timestamps) {
552 ret = qemu_chr_fe_write(d->drv, buf, len);
553 } else {
554 int i;
556 ret = 0;
557 for (i = 0; i < len; i++) {
558 if (d->linestart) {
559 char buf1[64];
560 int64_t ti;
561 int secs;
563 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
564 if (d->timestamps_start == -1)
565 d->timestamps_start = ti;
566 ti -= d->timestamps_start;
567 secs = ti / 1000;
568 snprintf(buf1, sizeof(buf1),
569 "[%02d:%02d:%02d.%03d] ",
570 secs / 3600,
571 (secs / 60) % 60,
572 secs % 60,
573 (int)(ti % 1000));
574 /* XXX this blocks entire thread. Rewrite to use
575 * qemu_chr_fe_write and background I/O callbacks */
576 qemu_chr_fe_write_all(d->drv, (uint8_t *)buf1, strlen(buf1));
577 d->linestart = 0;
579 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
580 if (buf[i] == '\n') {
581 d->linestart = 1;
585 return ret;
588 static const char * const mux_help[] = {
589 "% h print this help\n\r",
590 "% x exit emulator\n\r",
591 "% s save disk data back to file (if -snapshot)\n\r",
592 "% t toggle console timestamps\n\r",
593 "% b send break (magic sysrq)\n\r",
594 "% c switch between console and monitor\n\r",
595 "% % sends %\n\r",
596 NULL
599 int term_escape_char = 0x01; /* ctrl-a is used for escape */
600 static void mux_print_help(CharDriverState *chr)
602 int i, j;
603 char ebuf[15] = "Escape-Char";
604 char cbuf[50] = "\n\r";
606 if (term_escape_char > 0 && term_escape_char < 26) {
607 snprintf(cbuf, sizeof(cbuf), "\n\r");
608 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
609 } else {
610 snprintf(cbuf, sizeof(cbuf),
611 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
612 term_escape_char);
614 /* XXX this blocks entire thread. Rewrite to use
615 * qemu_chr_fe_write and background I/O callbacks */
616 qemu_chr_fe_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
617 for (i = 0; mux_help[i] != NULL; i++) {
618 for (j=0; mux_help[i][j] != '\0'; j++) {
619 if (mux_help[i][j] == '%')
620 qemu_chr_fe_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
621 else
622 qemu_chr_fe_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
627 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
629 if (d->chr_event[mux_nr])
630 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
633 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
635 if (d->term_got_escape) {
636 d->term_got_escape = 0;
637 if (ch == term_escape_char)
638 goto send_char;
639 switch(ch) {
640 case '?':
641 case 'h':
642 mux_print_help(chr);
643 break;
644 case 'x':
646 const char *term = "QEMU: Terminated\n\r";
647 qemu_chr_fe_write_all(chr, (uint8_t *)term, strlen(term));
648 exit(0);
649 break;
651 case 's':
652 blk_commit_all();
653 break;
654 case 'b':
655 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
656 break;
657 case 'c':
658 /* Switch to the next registered device */
659 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
660 d->focus++;
661 if (d->focus >= d->mux_cnt)
662 d->focus = 0;
663 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
664 break;
665 case 't':
666 d->timestamps = !d->timestamps;
667 d->timestamps_start = -1;
668 d->linestart = 0;
669 break;
671 } else if (ch == term_escape_char) {
672 d->term_got_escape = 1;
673 } else {
674 send_char:
675 return 1;
677 return 0;
680 static void mux_chr_accept_input(CharDriverState *chr)
682 MuxDriver *d = chr->opaque;
683 int m = d->focus;
685 while (d->prod[m] != d->cons[m] &&
686 d->chr_can_read[m] &&
687 d->chr_can_read[m](d->ext_opaque[m])) {
688 d->chr_read[m](d->ext_opaque[m],
689 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
693 static int mux_chr_can_read(void *opaque)
695 CharDriverState *chr = opaque;
696 MuxDriver *d = chr->opaque;
697 int m = d->focus;
699 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
700 return 1;
701 if (d->chr_can_read[m])
702 return d->chr_can_read[m](d->ext_opaque[m]);
703 return 0;
706 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
708 CharDriverState *chr = opaque;
709 MuxDriver *d = chr->opaque;
710 int m = d->focus;
711 int i;
713 mux_chr_accept_input (opaque);
715 for(i = 0; i < size; i++)
716 if (mux_proc_byte(chr, d, buf[i])) {
717 if (d->prod[m] == d->cons[m] &&
718 d->chr_can_read[m] &&
719 d->chr_can_read[m](d->ext_opaque[m]))
720 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
721 else
722 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
726 static void mux_chr_event(void *opaque, int event)
728 CharDriverState *chr = opaque;
729 MuxDriver *d = chr->opaque;
730 int i;
732 /* Send the event to all registered listeners */
733 for (i = 0; i < d->mux_cnt; i++)
734 mux_chr_send_event(d, i, event);
737 static void mux_chr_update_read_handler(CharDriverState *chr,
738 GMainContext *context)
740 MuxDriver *d = chr->opaque;
742 if (d->mux_cnt >= MAX_MUX) {
743 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
744 return;
746 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
747 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
748 d->chr_read[d->mux_cnt] = chr->chr_read;
749 d->chr_event[d->mux_cnt] = chr->chr_event;
750 /* Fix up the real driver with mux routines */
751 if (d->mux_cnt == 0) {
752 qemu_chr_add_handlers_full(d->drv, mux_chr_can_read,
753 mux_chr_read,
754 mux_chr_event,
755 chr, context);
757 if (d->focus != -1) {
758 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
760 d->focus = d->mux_cnt;
761 d->mux_cnt++;
762 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
765 static bool muxes_realized;
768 * Called after processing of default and command-line-specified
769 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
770 * to a mux chardev. This is done here to ensure that
771 * output/prompts/banners are only displayed for the FE that has
772 * focus when initial command-line processing/machine init is
773 * completed.
775 * After this point, any new FE attached to any new or existing
776 * mux will receive CHR_EVENT_OPENED notifications for the BE
777 * immediately.
779 static void muxes_realize_done(Notifier *notifier, void *unused)
781 CharDriverState *chr;
783 QTAILQ_FOREACH(chr, &chardevs, next) {
784 if (chr->is_mux) {
785 MuxDriver *d = chr->opaque;
786 int i;
788 /* send OPENED to all already-attached FEs */
789 for (i = 0; i < d->mux_cnt; i++) {
790 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
792 /* mark mux as OPENED so any new FEs will immediately receive
793 * OPENED event
795 qemu_chr_be_generic_open(chr);
798 muxes_realized = true;
801 static Notifier muxes_realize_notify = {
802 .notify = muxes_realize_done,
805 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
807 MuxDriver *d = s->opaque;
808 return d->drv->chr_add_watch(d->drv, cond);
811 static void mux_chr_close(struct CharDriverState *chr)
813 MuxDriver *d = chr->opaque;
815 g_free(d);
818 static CharDriverState *qemu_chr_open_mux(const char *id,
819 ChardevBackend *backend,
820 ChardevReturn *ret, Error **errp)
822 ChardevMux *mux = backend->u.mux.data;
823 CharDriverState *chr, *drv;
824 MuxDriver *d;
825 ChardevCommon *common = qapi_ChardevMux_base(mux);
827 drv = qemu_chr_find(mux->chardev);
828 if (drv == NULL) {
829 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
830 return NULL;
833 chr = qemu_chr_alloc(common, errp);
834 if (!chr) {
835 return NULL;
837 d = g_new0(MuxDriver, 1);
839 chr->opaque = d;
840 d->drv = drv;
841 d->focus = -1;
842 chr->chr_close = mux_chr_close;
843 chr->chr_write = mux_chr_write;
844 chr->chr_update_read_handler = mux_chr_update_read_handler;
845 chr->chr_accept_input = mux_chr_accept_input;
846 /* Frontend guest-open / -close notification is not support with muxes */
847 chr->chr_set_fe_open = NULL;
848 if (drv->chr_add_watch) {
849 chr->chr_add_watch = mux_chr_add_watch;
851 /* only default to opened state if we've realized the initial
852 * set of muxes
854 chr->explicit_be_open = muxes_realized ? 0 : 1;
855 chr->is_mux = 1;
857 return chr;
861 typedef struct IOWatchPoll
863 GSource parent;
865 QIOChannel *ioc;
866 GSource *src;
868 IOCanReadHandler *fd_can_read;
869 GSourceFunc fd_read;
870 void *opaque;
871 GMainContext *context;
872 } IOWatchPoll;
874 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
876 return container_of(source, IOWatchPoll, parent);
879 static gboolean io_watch_poll_prepare(GSource *source,
880 gint *timeout_)
882 IOWatchPoll *iwp = io_watch_poll_from_source(source);
883 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
884 bool was_active = iwp->src != NULL;
885 if (was_active == now_active) {
886 return FALSE;
889 if (now_active) {
890 iwp->src = qio_channel_create_watch(
891 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
892 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
893 g_source_attach(iwp->src, iwp->context);
894 } else {
895 g_source_destroy(iwp->src);
896 g_source_unref(iwp->src);
897 iwp->src = NULL;
899 return FALSE;
902 static gboolean io_watch_poll_check(GSource *source)
904 return FALSE;
907 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
908 gpointer user_data)
910 abort();
913 static void io_watch_poll_finalize(GSource *source)
915 /* Due to a glib bug, removing the last reference to a source
916 * inside a finalize callback causes recursive locking (and a
917 * deadlock). This is not a problem inside other callbacks,
918 * including dispatch callbacks, so we call io_remove_watch_poll
919 * to remove this source. At this point, iwp->src must
920 * be NULL, or we would leak it.
922 * This would be solved much more elegantly by child sources,
923 * but we support older glib versions that do not have them.
925 IOWatchPoll *iwp = io_watch_poll_from_source(source);
926 assert(iwp->src == NULL);
929 static GSourceFuncs io_watch_poll_funcs = {
930 .prepare = io_watch_poll_prepare,
931 .check = io_watch_poll_check,
932 .dispatch = io_watch_poll_dispatch,
933 .finalize = io_watch_poll_finalize,
936 /* Can only be used for read */
937 static guint io_add_watch_poll(QIOChannel *ioc,
938 IOCanReadHandler *fd_can_read,
939 QIOChannelFunc fd_read,
940 gpointer user_data,
941 GMainContext *context)
943 IOWatchPoll *iwp;
944 int tag;
946 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
947 sizeof(IOWatchPoll));
948 iwp->fd_can_read = fd_can_read;
949 iwp->opaque = user_data;
950 iwp->ioc = ioc;
951 iwp->fd_read = (GSourceFunc) fd_read;
952 iwp->src = NULL;
953 iwp->context = context;
955 tag = g_source_attach(&iwp->parent, context);
956 g_source_unref(&iwp->parent);
957 return tag;
960 static void io_remove_watch_poll(guint tag)
962 GSource *source;
963 IOWatchPoll *iwp;
965 g_return_if_fail (tag > 0);
967 source = g_main_context_find_source_by_id(NULL, tag);
968 g_return_if_fail (source != NULL);
970 iwp = io_watch_poll_from_source(source);
971 if (iwp->src) {
972 g_source_destroy(iwp->src);
973 g_source_unref(iwp->src);
974 iwp->src = NULL;
976 g_source_destroy(&iwp->parent);
979 static void remove_fd_in_watch(CharDriverState *chr)
981 if (chr->fd_in_tag) {
982 io_remove_watch_poll(chr->fd_in_tag);
983 chr->fd_in_tag = 0;
988 static int io_channel_send_full(QIOChannel *ioc,
989 const void *buf, size_t len,
990 int *fds, size_t nfds)
992 size_t offset = 0;
994 while (offset < len) {
995 ssize_t ret = 0;
996 struct iovec iov = { .iov_base = (char *)buf + offset,
997 .iov_len = len - offset };
999 ret = qio_channel_writev_full(
1000 ioc, &iov, 1,
1001 fds, nfds, NULL);
1002 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1003 if (offset) {
1004 return offset;
1007 errno = EAGAIN;
1008 return -1;
1009 } else if (ret < 0) {
1010 errno = EINVAL;
1011 return -1;
1014 offset += ret;
1017 return offset;
1021 #ifndef _WIN32
1022 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1024 return io_channel_send_full(ioc, buf, len, NULL, 0);
1028 typedef struct FDCharDriver {
1029 CharDriverState *chr;
1030 QIOChannel *ioc_in, *ioc_out;
1031 int max_size;
1032 } FDCharDriver;
1034 /* Called with chr_write_lock held. */
1035 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1037 FDCharDriver *s = chr->opaque;
1039 return io_channel_send(s->ioc_out, buf, len);
1042 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1044 CharDriverState *chr = opaque;
1045 FDCharDriver *s = chr->opaque;
1046 int len;
1047 uint8_t buf[READ_BUF_LEN];
1048 ssize_t ret;
1050 len = sizeof(buf);
1051 if (len > s->max_size) {
1052 len = s->max_size;
1054 if (len == 0) {
1055 return TRUE;
1058 ret = qio_channel_read(
1059 chan, (gchar *)buf, len, NULL);
1060 if (ret == 0) {
1061 remove_fd_in_watch(chr);
1062 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1063 return FALSE;
1065 if (ret > 0) {
1066 qemu_chr_be_write(chr, buf, ret);
1069 return TRUE;
1072 static int fd_chr_read_poll(void *opaque)
1074 CharDriverState *chr = opaque;
1075 FDCharDriver *s = chr->opaque;
1077 s->max_size = qemu_chr_be_can_write(chr);
1078 return s->max_size;
1081 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1083 FDCharDriver *s = chr->opaque;
1084 return qio_channel_create_watch(s->ioc_out, cond);
1087 static void fd_chr_update_read_handler(CharDriverState *chr,
1088 GMainContext *context)
1090 FDCharDriver *s = chr->opaque;
1092 remove_fd_in_watch(chr);
1093 if (s->ioc_in) {
1094 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1095 fd_chr_read_poll,
1096 fd_chr_read, chr,
1097 context);
1101 static void fd_chr_close(struct CharDriverState *chr)
1103 FDCharDriver *s = chr->opaque;
1105 remove_fd_in_watch(chr);
1106 if (s->ioc_in) {
1107 object_unref(OBJECT(s->ioc_in));
1109 if (s->ioc_out) {
1110 object_unref(OBJECT(s->ioc_out));
1113 g_free(s);
1114 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1117 /* open a character device to a unix fd */
1118 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1119 ChardevCommon *backend, Error **errp)
1121 CharDriverState *chr;
1122 FDCharDriver *s;
1124 chr = qemu_chr_alloc(backend, errp);
1125 if (!chr) {
1126 return NULL;
1128 s = g_new0(FDCharDriver, 1);
1129 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1130 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1131 qemu_set_nonblock(fd_out);
1132 s->chr = chr;
1133 chr->opaque = s;
1134 chr->chr_add_watch = fd_chr_add_watch;
1135 chr->chr_write = fd_chr_write;
1136 chr->chr_update_read_handler = fd_chr_update_read_handler;
1137 chr->chr_close = fd_chr_close;
1139 return chr;
1142 static CharDriverState *qemu_chr_open_pipe(const char *id,
1143 ChardevBackend *backend,
1144 ChardevReturn *ret,
1145 Error **errp)
1147 ChardevHostdev *opts = backend->u.pipe.data;
1148 int fd_in, fd_out;
1149 char *filename_in;
1150 char *filename_out;
1151 const char *filename = opts->device;
1152 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1155 filename_in = g_strdup_printf("%s.in", filename);
1156 filename_out = g_strdup_printf("%s.out", filename);
1157 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1158 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1159 g_free(filename_in);
1160 g_free(filename_out);
1161 if (fd_in < 0 || fd_out < 0) {
1162 if (fd_in >= 0)
1163 close(fd_in);
1164 if (fd_out >= 0)
1165 close(fd_out);
1166 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1167 if (fd_in < 0) {
1168 error_setg_file_open(errp, errno, filename);
1169 return NULL;
1172 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1175 /* init terminal so that we can grab keys */
1176 static struct termios oldtty;
1177 static int old_fd0_flags;
1178 static bool stdio_in_use;
1179 static bool stdio_allow_signal;
1180 static bool stdio_echo_state;
1182 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1184 static void term_exit(void)
1186 tcsetattr (0, TCSANOW, &oldtty);
1187 fcntl(0, F_SETFL, old_fd0_flags);
1190 static void term_stdio_handler(int sig)
1192 /* restore echo after resume from suspend. */
1193 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1196 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1198 struct termios tty;
1200 stdio_echo_state = echo;
1201 tty = oldtty;
1202 if (!echo) {
1203 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1204 |INLCR|IGNCR|ICRNL|IXON);
1205 tty.c_oflag |= OPOST;
1206 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1207 tty.c_cflag &= ~(CSIZE|PARENB);
1208 tty.c_cflag |= CS8;
1209 tty.c_cc[VMIN] = 1;
1210 tty.c_cc[VTIME] = 0;
1212 if (!stdio_allow_signal)
1213 tty.c_lflag &= ~ISIG;
1215 tcsetattr (0, TCSANOW, &tty);
1218 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1220 term_exit();
1221 fd_chr_close(chr);
1224 static CharDriverState *qemu_chr_open_stdio(const char *id,
1225 ChardevBackend *backend,
1226 ChardevReturn *ret,
1227 Error **errp)
1229 ChardevStdio *opts = backend->u.stdio.data;
1230 CharDriverState *chr;
1231 struct sigaction act;
1232 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1234 if (is_daemonized()) {
1235 error_setg(errp, "cannot use stdio with -daemonize");
1236 return NULL;
1239 if (stdio_in_use) {
1240 error_setg(errp, "cannot use stdio by multiple character devices");
1241 return NULL;
1244 stdio_in_use = true;
1245 old_fd0_flags = fcntl(0, F_GETFL);
1246 tcgetattr(0, &oldtty);
1247 qemu_set_nonblock(0);
1248 atexit(term_exit);
1250 memset(&act, 0, sizeof(act));
1251 act.sa_handler = term_stdio_handler;
1252 sigaction(SIGCONT, &act, NULL);
1254 chr = qemu_chr_open_fd(0, 1, common, errp);
1255 if (!chr) {
1256 return NULL;
1258 chr->chr_close = qemu_chr_close_stdio;
1259 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1260 if (opts->has_signal) {
1261 stdio_allow_signal = opts->signal;
1263 qemu_chr_fe_set_echo(chr, false);
1265 return chr;
1268 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1269 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1270 || defined(__GLIBC__)
1272 #define HAVE_CHARDEV_SERIAL 1
1273 #define HAVE_CHARDEV_PTY 1
1275 typedef struct {
1276 QIOChannel *ioc;
1277 int read_bytes;
1279 /* Protected by the CharDriverState chr_write_lock. */
1280 int connected;
1281 guint timer_tag;
1282 guint open_tag;
1283 } PtyCharDriver;
1285 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1286 static void pty_chr_state(CharDriverState *chr, int connected);
1288 static gboolean pty_chr_timer(gpointer opaque)
1290 struct CharDriverState *chr = opaque;
1291 PtyCharDriver *s = chr->opaque;
1293 qemu_mutex_lock(&chr->chr_write_lock);
1294 s->timer_tag = 0;
1295 s->open_tag = 0;
1296 if (!s->connected) {
1297 /* Next poll ... */
1298 pty_chr_update_read_handler_locked(chr);
1300 qemu_mutex_unlock(&chr->chr_write_lock);
1301 return FALSE;
1304 /* Called with chr_write_lock held. */
1305 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1307 PtyCharDriver *s = chr->opaque;
1309 if (s->timer_tag) {
1310 g_source_remove(s->timer_tag);
1311 s->timer_tag = 0;
1314 if (ms == 1000) {
1315 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1316 } else {
1317 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1321 /* Called with chr_write_lock held. */
1322 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1324 PtyCharDriver *s = chr->opaque;
1325 GPollFD pfd;
1326 int rc;
1327 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1329 pfd.fd = fioc->fd;
1330 pfd.events = G_IO_OUT;
1331 pfd.revents = 0;
1332 do {
1333 rc = g_poll(&pfd, 1, 0);
1334 } while (rc == -1 && errno == EINTR);
1335 assert(rc >= 0);
1337 if (pfd.revents & G_IO_HUP) {
1338 pty_chr_state(chr, 0);
1339 } else {
1340 pty_chr_state(chr, 1);
1344 static void pty_chr_update_read_handler(CharDriverState *chr,
1345 GMainContext *context)
1347 qemu_mutex_lock(&chr->chr_write_lock);
1348 pty_chr_update_read_handler_locked(chr);
1349 qemu_mutex_unlock(&chr->chr_write_lock);
1352 /* Called with chr_write_lock held. */
1353 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1355 PtyCharDriver *s = chr->opaque;
1357 if (!s->connected) {
1358 /* guest sends data, check for (re-)connect */
1359 pty_chr_update_read_handler_locked(chr);
1360 if (!s->connected) {
1361 return 0;
1364 return io_channel_send(s->ioc, buf, len);
1367 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1369 PtyCharDriver *s = chr->opaque;
1370 if (!s->connected) {
1371 return NULL;
1373 return qio_channel_create_watch(s->ioc, cond);
1376 static int pty_chr_read_poll(void *opaque)
1378 CharDriverState *chr = opaque;
1379 PtyCharDriver *s = chr->opaque;
1381 s->read_bytes = qemu_chr_be_can_write(chr);
1382 return s->read_bytes;
1385 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1387 CharDriverState *chr = opaque;
1388 PtyCharDriver *s = chr->opaque;
1389 gsize len;
1390 uint8_t buf[READ_BUF_LEN];
1391 ssize_t ret;
1393 len = sizeof(buf);
1394 if (len > s->read_bytes)
1395 len = s->read_bytes;
1396 if (len == 0) {
1397 return TRUE;
1399 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1400 if (ret <= 0) {
1401 pty_chr_state(chr, 0);
1402 return FALSE;
1403 } else {
1404 pty_chr_state(chr, 1);
1405 qemu_chr_be_write(chr, buf, ret);
1407 return TRUE;
1410 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1412 CharDriverState *chr = opaque;
1413 PtyCharDriver *s = chr->opaque;
1415 s->open_tag = 0;
1416 qemu_chr_be_generic_open(chr);
1417 return FALSE;
1420 /* Called with chr_write_lock held. */
1421 static void pty_chr_state(CharDriverState *chr, int connected)
1423 PtyCharDriver *s = chr->opaque;
1425 if (!connected) {
1426 if (s->open_tag) {
1427 g_source_remove(s->open_tag);
1428 s->open_tag = 0;
1430 remove_fd_in_watch(chr);
1431 s->connected = 0;
1432 /* (re-)connect poll interval for idle guests: once per second.
1433 * We check more frequently in case the guests sends data to
1434 * the virtual device linked to our pty. */
1435 pty_chr_rearm_timer(chr, 1000);
1436 } else {
1437 if (s->timer_tag) {
1438 g_source_remove(s->timer_tag);
1439 s->timer_tag = 0;
1441 if (!s->connected) {
1442 g_assert(s->open_tag == 0);
1443 s->connected = 1;
1444 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1446 if (!chr->fd_in_tag) {
1447 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1448 pty_chr_read_poll,
1449 pty_chr_read,
1450 chr, NULL);
1455 static void pty_chr_close(struct CharDriverState *chr)
1457 PtyCharDriver *s = chr->opaque;
1459 qemu_mutex_lock(&chr->chr_write_lock);
1460 pty_chr_state(chr, 0);
1461 object_unref(OBJECT(s->ioc));
1462 if (s->timer_tag) {
1463 g_source_remove(s->timer_tag);
1464 s->timer_tag = 0;
1466 qemu_mutex_unlock(&chr->chr_write_lock);
1467 g_free(s);
1468 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1471 static CharDriverState *qemu_chr_open_pty(const char *id,
1472 ChardevBackend *backend,
1473 ChardevReturn *ret,
1474 Error **errp)
1476 CharDriverState *chr;
1477 PtyCharDriver *s;
1478 int master_fd, slave_fd;
1479 char pty_name[PATH_MAX];
1480 ChardevCommon *common = backend->u.pty.data;
1482 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1483 if (master_fd < 0) {
1484 error_setg_errno(errp, errno, "Failed to create PTY");
1485 return NULL;
1488 close(slave_fd);
1489 qemu_set_nonblock(master_fd);
1491 chr = qemu_chr_alloc(common, errp);
1492 if (!chr) {
1493 close(master_fd);
1494 return NULL;
1497 chr->filename = g_strdup_printf("pty:%s", pty_name);
1498 ret->pty = g_strdup(pty_name);
1499 ret->has_pty = true;
1501 fprintf(stderr, "char device redirected to %s (label %s)\n",
1502 pty_name, id);
1504 s = g_new0(PtyCharDriver, 1);
1505 chr->opaque = s;
1506 chr->chr_write = pty_chr_write;
1507 chr->chr_update_read_handler = pty_chr_update_read_handler;
1508 chr->chr_close = pty_chr_close;
1509 chr->chr_add_watch = pty_chr_add_watch;
1510 chr->explicit_be_open = true;
1512 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1513 s->timer_tag = 0;
1515 return chr;
1518 static void tty_serial_init(int fd, int speed,
1519 int parity, int data_bits, int stop_bits)
1521 struct termios tty;
1522 speed_t spd;
1524 #if 0
1525 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1526 speed, parity, data_bits, stop_bits);
1527 #endif
1528 tcgetattr (fd, &tty);
1530 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1531 speed = speed * 10 / 11;
1532 do {
1533 check_speed(50);
1534 check_speed(75);
1535 check_speed(110);
1536 check_speed(134);
1537 check_speed(150);
1538 check_speed(200);
1539 check_speed(300);
1540 check_speed(600);
1541 check_speed(1200);
1542 check_speed(1800);
1543 check_speed(2400);
1544 check_speed(4800);
1545 check_speed(9600);
1546 check_speed(19200);
1547 check_speed(38400);
1548 /* Non-Posix values follow. They may be unsupported on some systems. */
1549 check_speed(57600);
1550 check_speed(115200);
1551 #ifdef B230400
1552 check_speed(230400);
1553 #endif
1554 #ifdef B460800
1555 check_speed(460800);
1556 #endif
1557 #ifdef B500000
1558 check_speed(500000);
1559 #endif
1560 #ifdef B576000
1561 check_speed(576000);
1562 #endif
1563 #ifdef B921600
1564 check_speed(921600);
1565 #endif
1566 #ifdef B1000000
1567 check_speed(1000000);
1568 #endif
1569 #ifdef B1152000
1570 check_speed(1152000);
1571 #endif
1572 #ifdef B1500000
1573 check_speed(1500000);
1574 #endif
1575 #ifdef B2000000
1576 check_speed(2000000);
1577 #endif
1578 #ifdef B2500000
1579 check_speed(2500000);
1580 #endif
1581 #ifdef B3000000
1582 check_speed(3000000);
1583 #endif
1584 #ifdef B3500000
1585 check_speed(3500000);
1586 #endif
1587 #ifdef B4000000
1588 check_speed(4000000);
1589 #endif
1590 spd = B115200;
1591 } while (0);
1593 cfsetispeed(&tty, spd);
1594 cfsetospeed(&tty, spd);
1596 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1597 |INLCR|IGNCR|ICRNL|IXON);
1598 tty.c_oflag |= OPOST;
1599 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1600 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1601 switch(data_bits) {
1602 default:
1603 case 8:
1604 tty.c_cflag |= CS8;
1605 break;
1606 case 7:
1607 tty.c_cflag |= CS7;
1608 break;
1609 case 6:
1610 tty.c_cflag |= CS6;
1611 break;
1612 case 5:
1613 tty.c_cflag |= CS5;
1614 break;
1616 switch(parity) {
1617 default:
1618 case 'N':
1619 break;
1620 case 'E':
1621 tty.c_cflag |= PARENB;
1622 break;
1623 case 'O':
1624 tty.c_cflag |= PARENB | PARODD;
1625 break;
1627 if (stop_bits == 2)
1628 tty.c_cflag |= CSTOPB;
1630 tcsetattr (fd, TCSANOW, &tty);
1633 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1635 FDCharDriver *s = chr->opaque;
1636 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1638 switch(cmd) {
1639 case CHR_IOCTL_SERIAL_SET_PARAMS:
1641 QEMUSerialSetParams *ssp = arg;
1642 tty_serial_init(fioc->fd,
1643 ssp->speed, ssp->parity,
1644 ssp->data_bits, ssp->stop_bits);
1646 break;
1647 case CHR_IOCTL_SERIAL_SET_BREAK:
1649 int enable = *(int *)arg;
1650 if (enable) {
1651 tcsendbreak(fioc->fd, 1);
1654 break;
1655 case CHR_IOCTL_SERIAL_GET_TIOCM:
1657 int sarg = 0;
1658 int *targ = (int *)arg;
1659 ioctl(fioc->fd, TIOCMGET, &sarg);
1660 *targ = 0;
1661 if (sarg & TIOCM_CTS)
1662 *targ |= CHR_TIOCM_CTS;
1663 if (sarg & TIOCM_CAR)
1664 *targ |= CHR_TIOCM_CAR;
1665 if (sarg & TIOCM_DSR)
1666 *targ |= CHR_TIOCM_DSR;
1667 if (sarg & TIOCM_RI)
1668 *targ |= CHR_TIOCM_RI;
1669 if (sarg & TIOCM_DTR)
1670 *targ |= CHR_TIOCM_DTR;
1671 if (sarg & TIOCM_RTS)
1672 *targ |= CHR_TIOCM_RTS;
1674 break;
1675 case CHR_IOCTL_SERIAL_SET_TIOCM:
1677 int sarg = *(int *)arg;
1678 int targ = 0;
1679 ioctl(fioc->fd, TIOCMGET, &targ);
1680 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1681 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1682 if (sarg & CHR_TIOCM_CTS)
1683 targ |= TIOCM_CTS;
1684 if (sarg & CHR_TIOCM_CAR)
1685 targ |= TIOCM_CAR;
1686 if (sarg & CHR_TIOCM_DSR)
1687 targ |= TIOCM_DSR;
1688 if (sarg & CHR_TIOCM_RI)
1689 targ |= TIOCM_RI;
1690 if (sarg & CHR_TIOCM_DTR)
1691 targ |= TIOCM_DTR;
1692 if (sarg & CHR_TIOCM_RTS)
1693 targ |= TIOCM_RTS;
1694 ioctl(fioc->fd, TIOCMSET, &targ);
1696 break;
1697 default:
1698 return -ENOTSUP;
1700 return 0;
1703 static void qemu_chr_close_tty(CharDriverState *chr)
1705 fd_chr_close(chr);
1708 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1709 ChardevCommon *backend,
1710 Error **errp)
1712 CharDriverState *chr;
1714 tty_serial_init(fd, 115200, 'N', 8, 1);
1715 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1716 if (!chr) {
1717 return NULL;
1719 chr->chr_ioctl = tty_serial_ioctl;
1720 chr->chr_close = qemu_chr_close_tty;
1721 return chr;
1723 #endif /* __linux__ || __sun__ */
1725 #if defined(__linux__)
1727 #define HAVE_CHARDEV_PARPORT 1
1729 typedef struct {
1730 int fd;
1731 int mode;
1732 } ParallelCharDriver;
1734 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1736 if (s->mode != mode) {
1737 int m = mode;
1738 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1739 return 0;
1740 s->mode = mode;
1742 return 1;
1745 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1747 ParallelCharDriver *drv = chr->opaque;
1748 int fd = drv->fd;
1749 uint8_t b;
1751 switch(cmd) {
1752 case CHR_IOCTL_PP_READ_DATA:
1753 if (ioctl(fd, PPRDATA, &b) < 0)
1754 return -ENOTSUP;
1755 *(uint8_t *)arg = b;
1756 break;
1757 case CHR_IOCTL_PP_WRITE_DATA:
1758 b = *(uint8_t *)arg;
1759 if (ioctl(fd, PPWDATA, &b) < 0)
1760 return -ENOTSUP;
1761 break;
1762 case CHR_IOCTL_PP_READ_CONTROL:
1763 if (ioctl(fd, PPRCONTROL, &b) < 0)
1764 return -ENOTSUP;
1765 /* Linux gives only the lowest bits, and no way to know data
1766 direction! For better compatibility set the fixed upper
1767 bits. */
1768 *(uint8_t *)arg = b | 0xc0;
1769 break;
1770 case CHR_IOCTL_PP_WRITE_CONTROL:
1771 b = *(uint8_t *)arg;
1772 if (ioctl(fd, PPWCONTROL, &b) < 0)
1773 return -ENOTSUP;
1774 break;
1775 case CHR_IOCTL_PP_READ_STATUS:
1776 if (ioctl(fd, PPRSTATUS, &b) < 0)
1777 return -ENOTSUP;
1778 *(uint8_t *)arg = b;
1779 break;
1780 case CHR_IOCTL_PP_DATA_DIR:
1781 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1782 return -ENOTSUP;
1783 break;
1784 case CHR_IOCTL_PP_EPP_READ_ADDR:
1785 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1786 struct ParallelIOArg *parg = arg;
1787 int n = read(fd, parg->buffer, parg->count);
1788 if (n != parg->count) {
1789 return -EIO;
1792 break;
1793 case CHR_IOCTL_PP_EPP_READ:
1794 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1795 struct ParallelIOArg *parg = arg;
1796 int n = read(fd, parg->buffer, parg->count);
1797 if (n != parg->count) {
1798 return -EIO;
1801 break;
1802 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1803 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1804 struct ParallelIOArg *parg = arg;
1805 int n = write(fd, parg->buffer, parg->count);
1806 if (n != parg->count) {
1807 return -EIO;
1810 break;
1811 case CHR_IOCTL_PP_EPP_WRITE:
1812 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1813 struct ParallelIOArg *parg = arg;
1814 int n = write(fd, parg->buffer, parg->count);
1815 if (n != parg->count) {
1816 return -EIO;
1819 break;
1820 default:
1821 return -ENOTSUP;
1823 return 0;
1826 static void pp_close(CharDriverState *chr)
1828 ParallelCharDriver *drv = chr->opaque;
1829 int fd = drv->fd;
1831 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1832 ioctl(fd, PPRELEASE);
1833 close(fd);
1834 g_free(drv);
1835 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1838 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1839 ChardevCommon *backend,
1840 Error **errp)
1842 CharDriverState *chr;
1843 ParallelCharDriver *drv;
1845 if (ioctl(fd, PPCLAIM) < 0) {
1846 error_setg_errno(errp, errno, "not a parallel port");
1847 close(fd);
1848 return NULL;
1851 chr = qemu_chr_alloc(backend, errp);
1852 if (!chr) {
1853 return NULL;
1856 drv = g_new0(ParallelCharDriver, 1);
1857 chr->opaque = drv;
1858 chr->chr_write = null_chr_write;
1859 chr->chr_ioctl = pp_ioctl;
1860 chr->chr_close = pp_close;
1862 drv->fd = fd;
1863 drv->mode = IEEE1284_MODE_COMPAT;
1865 return chr;
1867 #endif /* __linux__ */
1869 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1871 #define HAVE_CHARDEV_PARPORT 1
1873 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1875 int fd = (int)(intptr_t)chr->opaque;
1876 uint8_t b;
1878 switch(cmd) {
1879 case CHR_IOCTL_PP_READ_DATA:
1880 if (ioctl(fd, PPIGDATA, &b) < 0)
1881 return -ENOTSUP;
1882 *(uint8_t *)arg = b;
1883 break;
1884 case CHR_IOCTL_PP_WRITE_DATA:
1885 b = *(uint8_t *)arg;
1886 if (ioctl(fd, PPISDATA, &b) < 0)
1887 return -ENOTSUP;
1888 break;
1889 case CHR_IOCTL_PP_READ_CONTROL:
1890 if (ioctl(fd, PPIGCTRL, &b) < 0)
1891 return -ENOTSUP;
1892 *(uint8_t *)arg = b;
1893 break;
1894 case CHR_IOCTL_PP_WRITE_CONTROL:
1895 b = *(uint8_t *)arg;
1896 if (ioctl(fd, PPISCTRL, &b) < 0)
1897 return -ENOTSUP;
1898 break;
1899 case CHR_IOCTL_PP_READ_STATUS:
1900 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1901 return -ENOTSUP;
1902 *(uint8_t *)arg = b;
1903 break;
1904 default:
1905 return -ENOTSUP;
1907 return 0;
1910 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1911 ChardevCommon *backend,
1912 Error **errp)
1914 CharDriverState *chr;
1916 chr = qemu_chr_alloc(backend, errp);
1917 if (!chr) {
1918 return NULL;
1920 chr->opaque = (void *)(intptr_t)fd;
1921 chr->chr_write = null_chr_write;
1922 chr->chr_ioctl = pp_ioctl;
1923 chr->explicit_be_open = true;
1924 return chr;
1926 #endif
1928 #else /* _WIN32 */
1930 #define HAVE_CHARDEV_SERIAL 1
1932 typedef struct {
1933 int max_size;
1934 HANDLE hcom, hrecv, hsend;
1935 OVERLAPPED orecv;
1936 BOOL fpipe;
1937 DWORD len;
1939 /* Protected by the CharDriverState chr_write_lock. */
1940 OVERLAPPED osend;
1941 } WinCharState;
1943 typedef struct {
1944 HANDLE hStdIn;
1945 HANDLE hInputReadyEvent;
1946 HANDLE hInputDoneEvent;
1947 HANDLE hInputThread;
1948 uint8_t win_stdio_buf;
1949 } WinStdioCharState;
1951 #define NSENDBUF 2048
1952 #define NRECVBUF 2048
1953 #define MAXCONNECT 1
1954 #define NTIMEOUT 5000
1956 static int win_chr_poll(void *opaque);
1957 static int win_chr_pipe_poll(void *opaque);
1959 static void win_chr_close(CharDriverState *chr)
1961 WinCharState *s = chr->opaque;
1963 if (s->hsend) {
1964 CloseHandle(s->hsend);
1965 s->hsend = NULL;
1967 if (s->hrecv) {
1968 CloseHandle(s->hrecv);
1969 s->hrecv = NULL;
1971 if (s->hcom) {
1972 CloseHandle(s->hcom);
1973 s->hcom = NULL;
1975 if (s->fpipe)
1976 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1977 else
1978 qemu_del_polling_cb(win_chr_poll, chr);
1980 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1983 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1985 WinCharState *s = chr->opaque;
1986 COMMCONFIG comcfg;
1987 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1988 COMSTAT comstat;
1989 DWORD size;
1990 DWORD err;
1992 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1993 if (!s->hsend) {
1994 error_setg(errp, "Failed CreateEvent");
1995 goto fail;
1997 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1998 if (!s->hrecv) {
1999 error_setg(errp, "Failed CreateEvent");
2000 goto fail;
2003 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2004 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2005 if (s->hcom == INVALID_HANDLE_VALUE) {
2006 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2007 s->hcom = NULL;
2008 goto fail;
2011 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2012 error_setg(errp, "Failed SetupComm");
2013 goto fail;
2016 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2017 size = sizeof(COMMCONFIG);
2018 GetDefaultCommConfig(filename, &comcfg, &size);
2019 comcfg.dcb.DCBlength = sizeof(DCB);
2020 CommConfigDialog(filename, NULL, &comcfg);
2022 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2023 error_setg(errp, "Failed SetCommState");
2024 goto fail;
2027 if (!SetCommMask(s->hcom, EV_ERR)) {
2028 error_setg(errp, "Failed SetCommMask");
2029 goto fail;
2032 cto.ReadIntervalTimeout = MAXDWORD;
2033 if (!SetCommTimeouts(s->hcom, &cto)) {
2034 error_setg(errp, "Failed SetCommTimeouts");
2035 goto fail;
2038 if (!ClearCommError(s->hcom, &err, &comstat)) {
2039 error_setg(errp, "Failed ClearCommError");
2040 goto fail;
2042 qemu_add_polling_cb(win_chr_poll, chr);
2043 return 0;
2045 fail:
2046 win_chr_close(chr);
2047 return -1;
2050 /* Called with chr_write_lock held. */
2051 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2053 WinCharState *s = chr->opaque;
2054 DWORD len, ret, size, err;
2056 len = len1;
2057 ZeroMemory(&s->osend, sizeof(s->osend));
2058 s->osend.hEvent = s->hsend;
2059 while (len > 0) {
2060 if (s->hsend)
2061 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2062 else
2063 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2064 if (!ret) {
2065 err = GetLastError();
2066 if (err == ERROR_IO_PENDING) {
2067 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2068 if (ret) {
2069 buf += size;
2070 len -= size;
2071 } else {
2072 break;
2074 } else {
2075 break;
2077 } else {
2078 buf += size;
2079 len -= size;
2082 return len1 - len;
2085 static int win_chr_read_poll(CharDriverState *chr)
2087 WinCharState *s = chr->opaque;
2089 s->max_size = qemu_chr_be_can_write(chr);
2090 return s->max_size;
2093 static void win_chr_readfile(CharDriverState *chr)
2095 WinCharState *s = chr->opaque;
2096 int ret, err;
2097 uint8_t buf[READ_BUF_LEN];
2098 DWORD size;
2100 ZeroMemory(&s->orecv, sizeof(s->orecv));
2101 s->orecv.hEvent = s->hrecv;
2102 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2103 if (!ret) {
2104 err = GetLastError();
2105 if (err == ERROR_IO_PENDING) {
2106 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2110 if (size > 0) {
2111 qemu_chr_be_write(chr, buf, size);
2115 static void win_chr_read(CharDriverState *chr)
2117 WinCharState *s = chr->opaque;
2119 if (s->len > s->max_size)
2120 s->len = s->max_size;
2121 if (s->len == 0)
2122 return;
2124 win_chr_readfile(chr);
2127 static int win_chr_poll(void *opaque)
2129 CharDriverState *chr = opaque;
2130 WinCharState *s = chr->opaque;
2131 COMSTAT status;
2132 DWORD comerr;
2134 ClearCommError(s->hcom, &comerr, &status);
2135 if (status.cbInQue > 0) {
2136 s->len = status.cbInQue;
2137 win_chr_read_poll(chr);
2138 win_chr_read(chr);
2139 return 1;
2141 return 0;
2144 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2145 ChardevCommon *backend,
2146 Error **errp)
2148 CharDriverState *chr;
2149 WinCharState *s;
2151 chr = qemu_chr_alloc(backend, errp);
2152 if (!chr) {
2153 return NULL;
2155 s = g_new0(WinCharState, 1);
2156 chr->opaque = s;
2157 chr->chr_write = win_chr_write;
2158 chr->chr_close = win_chr_close;
2160 if (win_chr_init(chr, filename, errp) < 0) {
2161 g_free(s);
2162 qemu_chr_free_common(chr);
2163 return NULL;
2165 return chr;
2168 static int win_chr_pipe_poll(void *opaque)
2170 CharDriverState *chr = opaque;
2171 WinCharState *s = chr->opaque;
2172 DWORD size;
2174 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2175 if (size > 0) {
2176 s->len = size;
2177 win_chr_read_poll(chr);
2178 win_chr_read(chr);
2179 return 1;
2181 return 0;
2184 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2185 Error **errp)
2187 WinCharState *s = chr->opaque;
2188 OVERLAPPED ov;
2189 int ret;
2190 DWORD size;
2191 char *openname;
2193 s->fpipe = TRUE;
2195 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2196 if (!s->hsend) {
2197 error_setg(errp, "Failed CreateEvent");
2198 goto fail;
2200 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2201 if (!s->hrecv) {
2202 error_setg(errp, "Failed CreateEvent");
2203 goto fail;
2206 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2207 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2208 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2209 PIPE_WAIT,
2210 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2211 g_free(openname);
2212 if (s->hcom == INVALID_HANDLE_VALUE) {
2213 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2214 s->hcom = NULL;
2215 goto fail;
2218 ZeroMemory(&ov, sizeof(ov));
2219 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2220 ret = ConnectNamedPipe(s->hcom, &ov);
2221 if (ret) {
2222 error_setg(errp, "Failed ConnectNamedPipe");
2223 goto fail;
2226 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2227 if (!ret) {
2228 error_setg(errp, "Failed GetOverlappedResult");
2229 if (ov.hEvent) {
2230 CloseHandle(ov.hEvent);
2231 ov.hEvent = NULL;
2233 goto fail;
2236 if (ov.hEvent) {
2237 CloseHandle(ov.hEvent);
2238 ov.hEvent = NULL;
2240 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2241 return 0;
2243 fail:
2244 win_chr_close(chr);
2245 return -1;
2249 static CharDriverState *qemu_chr_open_pipe(const char *id,
2250 ChardevBackend *backend,
2251 ChardevReturn *ret,
2252 Error **errp)
2254 ChardevHostdev *opts = backend->u.pipe.data;
2255 const char *filename = opts->device;
2256 CharDriverState *chr;
2257 WinCharState *s;
2258 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2260 chr = qemu_chr_alloc(common, errp);
2261 if (!chr) {
2262 return NULL;
2264 s = g_new0(WinCharState, 1);
2265 chr->opaque = s;
2266 chr->chr_write = win_chr_write;
2267 chr->chr_close = win_chr_close;
2269 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2270 g_free(s);
2271 qemu_chr_free_common(chr);
2272 return NULL;
2274 return chr;
2277 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2278 ChardevCommon *backend,
2279 Error **errp)
2281 CharDriverState *chr;
2282 WinCharState *s;
2284 chr = qemu_chr_alloc(backend, errp);
2285 if (!chr) {
2286 return NULL;
2288 s = g_new0(WinCharState, 1);
2289 s->hcom = fd_out;
2290 chr->opaque = s;
2291 chr->chr_write = win_chr_write;
2292 return chr;
2295 static CharDriverState *qemu_chr_open_win_con(const char *id,
2296 ChardevBackend *backend,
2297 ChardevReturn *ret,
2298 Error **errp)
2300 ChardevCommon *common = backend->u.console.data;
2301 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2302 common, errp);
2305 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2307 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2308 DWORD dwSize;
2309 int len1;
2311 len1 = len;
2313 while (len1 > 0) {
2314 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2315 break;
2317 buf += dwSize;
2318 len1 -= dwSize;
2321 return len - len1;
2324 static void win_stdio_wait_func(void *opaque)
2326 CharDriverState *chr = opaque;
2327 WinStdioCharState *stdio = chr->opaque;
2328 INPUT_RECORD buf[4];
2329 int ret;
2330 DWORD dwSize;
2331 int i;
2333 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2335 if (!ret) {
2336 /* Avoid error storm */
2337 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2338 return;
2341 for (i = 0; i < dwSize; i++) {
2342 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2344 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2345 int j;
2346 if (kev->uChar.AsciiChar != 0) {
2347 for (j = 0; j < kev->wRepeatCount; j++) {
2348 if (qemu_chr_be_can_write(chr)) {
2349 uint8_t c = kev->uChar.AsciiChar;
2350 qemu_chr_be_write(chr, &c, 1);
2358 static DWORD WINAPI win_stdio_thread(LPVOID param)
2360 CharDriverState *chr = param;
2361 WinStdioCharState *stdio = chr->opaque;
2362 int ret;
2363 DWORD dwSize;
2365 while (1) {
2367 /* Wait for one byte */
2368 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2370 /* Exit in case of error, continue if nothing read */
2371 if (!ret) {
2372 break;
2374 if (!dwSize) {
2375 continue;
2378 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2379 if (stdio->win_stdio_buf == '\r') {
2380 continue;
2383 /* Signal the main thread and wait until the byte was eaten */
2384 if (!SetEvent(stdio->hInputReadyEvent)) {
2385 break;
2387 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2388 != WAIT_OBJECT_0) {
2389 break;
2393 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2394 return 0;
2397 static void win_stdio_thread_wait_func(void *opaque)
2399 CharDriverState *chr = opaque;
2400 WinStdioCharState *stdio = chr->opaque;
2402 if (qemu_chr_be_can_write(chr)) {
2403 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2406 SetEvent(stdio->hInputDoneEvent);
2409 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2411 WinStdioCharState *stdio = chr->opaque;
2412 DWORD dwMode = 0;
2414 GetConsoleMode(stdio->hStdIn, &dwMode);
2416 if (echo) {
2417 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2418 } else {
2419 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2423 static void win_stdio_close(CharDriverState *chr)
2425 WinStdioCharState *stdio = chr->opaque;
2427 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2428 CloseHandle(stdio->hInputReadyEvent);
2430 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2431 CloseHandle(stdio->hInputDoneEvent);
2433 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2434 TerminateThread(stdio->hInputThread, 0);
2437 g_free(chr->opaque);
2438 g_free(chr);
2441 static CharDriverState *qemu_chr_open_stdio(const char *id,
2442 ChardevBackend *backend,
2443 ChardevReturn *ret,
2444 Error **errp)
2446 CharDriverState *chr;
2447 WinStdioCharState *stdio;
2448 DWORD dwMode;
2449 int is_console = 0;
2450 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2452 chr = qemu_chr_alloc(common, errp);
2453 if (!chr) {
2454 return NULL;
2456 stdio = g_new0(WinStdioCharState, 1);
2458 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2459 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2460 error_setg(errp, "cannot open stdio: invalid handle");
2461 return NULL;
2464 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2466 chr->opaque = stdio;
2467 chr->chr_write = win_stdio_write;
2468 chr->chr_close = win_stdio_close;
2470 if (is_console) {
2471 if (qemu_add_wait_object(stdio->hStdIn,
2472 win_stdio_wait_func, chr)) {
2473 error_setg(errp, "qemu_add_wait_object: failed");
2474 goto err1;
2476 } else {
2477 DWORD dwId;
2479 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2480 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2481 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2482 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2483 error_setg(errp, "cannot create event");
2484 goto err2;
2486 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2487 win_stdio_thread_wait_func, chr)) {
2488 error_setg(errp, "qemu_add_wait_object: failed");
2489 goto err2;
2491 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2492 chr, 0, &dwId);
2494 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2495 error_setg(errp, "cannot create stdio thread");
2496 goto err3;
2500 dwMode |= ENABLE_LINE_INPUT;
2502 if (is_console) {
2503 /* set the terminal in raw mode */
2504 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2505 dwMode |= ENABLE_PROCESSED_INPUT;
2508 SetConsoleMode(stdio->hStdIn, dwMode);
2510 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2511 qemu_chr_fe_set_echo(chr, false);
2513 return chr;
2515 err3:
2516 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2517 err2:
2518 CloseHandle(stdio->hInputReadyEvent);
2519 CloseHandle(stdio->hInputDoneEvent);
2520 err1:
2521 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2522 return NULL;
2524 #endif /* !_WIN32 */
2527 /***********************************************************/
2528 /* UDP Net console */
2530 typedef struct {
2531 QIOChannel *ioc;
2532 uint8_t buf[READ_BUF_LEN];
2533 int bufcnt;
2534 int bufptr;
2535 int max_size;
2536 } NetCharDriver;
2538 /* Called with chr_write_lock held. */
2539 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2541 NetCharDriver *s = chr->opaque;
2543 return qio_channel_write(
2544 s->ioc, (const char *)buf, len, NULL);
2547 static int udp_chr_read_poll(void *opaque)
2549 CharDriverState *chr = opaque;
2550 NetCharDriver *s = chr->opaque;
2552 s->max_size = qemu_chr_be_can_write(chr);
2554 /* If there were any stray characters in the queue process them
2555 * first
2557 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2558 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2559 s->bufptr++;
2560 s->max_size = qemu_chr_be_can_write(chr);
2562 return s->max_size;
2565 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2567 CharDriverState *chr = opaque;
2568 NetCharDriver *s = chr->opaque;
2569 ssize_t ret;
2571 if (s->max_size == 0) {
2572 return TRUE;
2574 ret = qio_channel_read(
2575 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2576 if (ret <= 0) {
2577 remove_fd_in_watch(chr);
2578 return FALSE;
2580 s->bufcnt = ret;
2582 s->bufptr = 0;
2583 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2584 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2585 s->bufptr++;
2586 s->max_size = qemu_chr_be_can_write(chr);
2589 return TRUE;
2592 static void udp_chr_update_read_handler(CharDriverState *chr,
2593 GMainContext *context)
2595 NetCharDriver *s = chr->opaque;
2597 remove_fd_in_watch(chr);
2598 if (s->ioc) {
2599 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2600 udp_chr_read_poll,
2601 udp_chr_read, chr,
2602 context);
2606 static void udp_chr_close(CharDriverState *chr)
2608 NetCharDriver *s = chr->opaque;
2610 remove_fd_in_watch(chr);
2611 if (s->ioc) {
2612 object_unref(OBJECT(s->ioc));
2614 g_free(s);
2615 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2618 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2619 ChardevCommon *backend,
2620 Error **errp)
2622 CharDriverState *chr = NULL;
2623 NetCharDriver *s = NULL;
2625 chr = qemu_chr_alloc(backend, errp);
2626 if (!chr) {
2627 return NULL;
2629 s = g_new0(NetCharDriver, 1);
2631 s->ioc = QIO_CHANNEL(sioc);
2632 s->bufcnt = 0;
2633 s->bufptr = 0;
2634 chr->opaque = s;
2635 chr->chr_write = udp_chr_write;
2636 chr->chr_update_read_handler = udp_chr_update_read_handler;
2637 chr->chr_close = udp_chr_close;
2638 /* be isn't opened until we get a connection */
2639 chr->explicit_be_open = true;
2640 return chr;
2643 /***********************************************************/
2644 /* TCP Net console */
2646 typedef struct {
2647 QIOChannel *ioc; /* Client I/O channel */
2648 QIOChannelSocket *sioc; /* Client master channel */
2649 QIOChannelSocket *listen_ioc;
2650 guint listen_tag;
2651 QCryptoTLSCreds *tls_creds;
2652 int connected;
2653 int max_size;
2654 int do_telnetopt;
2655 int do_nodelay;
2656 int is_unix;
2657 int *read_msgfds;
2658 size_t read_msgfds_num;
2659 int *write_msgfds;
2660 size_t write_msgfds_num;
2662 SocketAddress *addr;
2663 bool is_listen;
2664 bool is_telnet;
2666 guint reconnect_timer;
2667 int64_t reconnect_time;
2668 bool connect_err_reported;
2669 } TCPCharDriver;
2671 static gboolean socket_reconnect_timeout(gpointer opaque);
2673 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2675 TCPCharDriver *s = chr->opaque;
2676 assert(s->connected == 0);
2677 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2678 socket_reconnect_timeout, chr);
2681 static void check_report_connect_error(CharDriverState *chr,
2682 Error *err)
2684 TCPCharDriver *s = chr->opaque;
2686 if (!s->connect_err_reported) {
2687 error_report("Unable to connect character device %s: %s",
2688 chr->label, error_get_pretty(err));
2689 s->connect_err_reported = true;
2691 qemu_chr_socket_restart_timer(chr);
2694 static gboolean tcp_chr_accept(QIOChannel *chan,
2695 GIOCondition cond,
2696 void *opaque);
2698 /* Called with chr_write_lock held. */
2699 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2701 TCPCharDriver *s = chr->opaque;
2702 if (s->connected) {
2703 int ret = io_channel_send_full(s->ioc, buf, len,
2704 s->write_msgfds,
2705 s->write_msgfds_num);
2707 /* free the written msgfds, no matter what */
2708 if (s->write_msgfds_num) {
2709 g_free(s->write_msgfds);
2710 s->write_msgfds = 0;
2711 s->write_msgfds_num = 0;
2714 return ret;
2715 } else {
2716 /* XXX: indicate an error ? */
2717 return len;
2721 static int tcp_chr_read_poll(void *opaque)
2723 CharDriverState *chr = opaque;
2724 TCPCharDriver *s = chr->opaque;
2725 if (!s->connected)
2726 return 0;
2727 s->max_size = qemu_chr_be_can_write(chr);
2728 return s->max_size;
2731 #define IAC 255
2732 #define IAC_BREAK 243
2733 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2734 TCPCharDriver *s,
2735 uint8_t *buf, int *size)
2737 /* Handle any telnet client's basic IAC options to satisfy char by
2738 * char mode with no echo. All IAC options will be removed from
2739 * the buf and the do_telnetopt variable will be used to track the
2740 * state of the width of the IAC information.
2742 * IAC commands come in sets of 3 bytes with the exception of the
2743 * "IAC BREAK" command and the double IAC.
2746 int i;
2747 int j = 0;
2749 for (i = 0; i < *size; i++) {
2750 if (s->do_telnetopt > 1) {
2751 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2752 /* Double IAC means send an IAC */
2753 if (j != i)
2754 buf[j] = buf[i];
2755 j++;
2756 s->do_telnetopt = 1;
2757 } else {
2758 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2759 /* Handle IAC break commands by sending a serial break */
2760 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2761 s->do_telnetopt++;
2763 s->do_telnetopt++;
2765 if (s->do_telnetopt >= 4) {
2766 s->do_telnetopt = 1;
2768 } else {
2769 if ((unsigned char)buf[i] == IAC) {
2770 s->do_telnetopt = 2;
2771 } else {
2772 if (j != i)
2773 buf[j] = buf[i];
2774 j++;
2778 *size = j;
2781 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2783 TCPCharDriver *s = chr->opaque;
2784 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2786 assert(num <= TCP_MAX_FDS);
2788 if (to_copy) {
2789 int i;
2791 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2793 /* Close unused fds */
2794 for (i = to_copy; i < s->read_msgfds_num; i++) {
2795 close(s->read_msgfds[i]);
2798 g_free(s->read_msgfds);
2799 s->read_msgfds = 0;
2800 s->read_msgfds_num = 0;
2803 return to_copy;
2806 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2808 TCPCharDriver *s = chr->opaque;
2810 /* clear old pending fd array */
2811 g_free(s->write_msgfds);
2812 s->write_msgfds = NULL;
2813 s->write_msgfds_num = 0;
2815 if (!s->connected ||
2816 !qio_channel_has_feature(s->ioc,
2817 QIO_CHANNEL_FEATURE_FD_PASS)) {
2818 return -1;
2821 if (num) {
2822 s->write_msgfds = g_new(int, num);
2823 memcpy(s->write_msgfds, fds, num * sizeof(int));
2826 s->write_msgfds_num = num;
2828 return 0;
2831 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2833 TCPCharDriver *s = chr->opaque;
2834 struct iovec iov = { .iov_base = buf, .iov_len = len };
2835 int ret;
2836 size_t i;
2837 int *msgfds = NULL;
2838 size_t msgfds_num = 0;
2840 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2841 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2842 &msgfds, &msgfds_num,
2843 NULL);
2844 } else {
2845 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2846 NULL, NULL,
2847 NULL);
2850 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2851 errno = EAGAIN;
2852 ret = -1;
2853 } else if (ret == -1) {
2854 errno = EIO;
2857 if (msgfds_num) {
2858 /* close and clean read_msgfds */
2859 for (i = 0; i < s->read_msgfds_num; i++) {
2860 close(s->read_msgfds[i]);
2863 if (s->read_msgfds_num) {
2864 g_free(s->read_msgfds);
2867 s->read_msgfds = msgfds;
2868 s->read_msgfds_num = msgfds_num;
2871 for (i = 0; i < s->read_msgfds_num; i++) {
2872 int fd = s->read_msgfds[i];
2873 if (fd < 0) {
2874 continue;
2877 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2878 qemu_set_block(fd);
2880 #ifndef MSG_CMSG_CLOEXEC
2881 qemu_set_cloexec(fd);
2882 #endif
2885 return ret;
2888 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2890 TCPCharDriver *s = chr->opaque;
2891 return qio_channel_create_watch(s->ioc, cond);
2894 static void tcp_chr_free_connection(CharDriverState *chr)
2896 TCPCharDriver *s = chr->opaque;
2897 int i;
2899 if (!s->connected) {
2900 return;
2903 if (s->read_msgfds_num) {
2904 for (i = 0; i < s->read_msgfds_num; i++) {
2905 close(s->read_msgfds[i]);
2907 g_free(s->read_msgfds);
2908 s->read_msgfds = NULL;
2909 s->read_msgfds_num = 0;
2912 tcp_set_msgfds(chr, NULL, 0);
2913 remove_fd_in_watch(chr);
2914 object_unref(OBJECT(s->sioc));
2915 s->sioc = NULL;
2916 object_unref(OBJECT(s->ioc));
2917 s->ioc = NULL;
2918 g_free(chr->filename);
2919 chr->filename = NULL;
2920 s->connected = 0;
2923 static void tcp_chr_disconnect(CharDriverState *chr)
2925 TCPCharDriver *s = chr->opaque;
2927 if (!s->connected) {
2928 return;
2931 tcp_chr_free_connection(chr);
2933 if (s->listen_ioc) {
2934 s->listen_tag = qio_channel_add_watch(
2935 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2937 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2938 s->is_listen, s->is_telnet);
2939 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2940 if (s->reconnect_time) {
2941 qemu_chr_socket_restart_timer(chr);
2945 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2947 CharDriverState *chr = opaque;
2948 TCPCharDriver *s = chr->opaque;
2949 uint8_t buf[READ_BUF_LEN];
2950 int len, size;
2952 if (!s->connected || s->max_size <= 0) {
2953 return TRUE;
2955 len = sizeof(buf);
2956 if (len > s->max_size)
2957 len = s->max_size;
2958 size = tcp_chr_recv(chr, (void *)buf, len);
2959 if (size == 0 || size == -1) {
2960 /* connection closed */
2961 tcp_chr_disconnect(chr);
2962 } else if (size > 0) {
2963 if (s->do_telnetopt)
2964 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2965 if (size > 0)
2966 qemu_chr_be_write(chr, buf, size);
2969 return TRUE;
2972 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2974 TCPCharDriver *s = chr->opaque;
2975 int size;
2977 if (!s->connected) {
2978 return 0;
2981 size = tcp_chr_recv(chr, (void *) buf, len);
2982 if (size == 0) {
2983 /* connection closed */
2984 tcp_chr_disconnect(chr);
2987 return size;
2990 static void tcp_chr_connect(void *opaque)
2992 CharDriverState *chr = opaque;
2993 TCPCharDriver *s = chr->opaque;
2995 g_free(chr->filename);
2996 chr->filename = sockaddr_to_str(
2997 &s->sioc->localAddr, s->sioc->localAddrLen,
2998 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2999 s->is_listen, s->is_telnet);
3001 s->connected = 1;
3002 if (s->ioc) {
3003 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3004 tcp_chr_read_poll,
3005 tcp_chr_read,
3006 chr, NULL);
3008 qemu_chr_be_generic_open(chr);
3011 static void tcp_chr_update_read_handler(CharDriverState *chr,
3012 GMainContext *context)
3014 TCPCharDriver *s = chr->opaque;
3016 if (!s->connected) {
3017 return;
3020 remove_fd_in_watch(chr);
3021 if (s->ioc) {
3022 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3023 tcp_chr_read_poll,
3024 tcp_chr_read, chr,
3025 context);
3029 typedef struct {
3030 CharDriverState *chr;
3031 char buf[12];
3032 size_t buflen;
3033 } TCPCharDriverTelnetInit;
3035 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3036 GIOCondition cond G_GNUC_UNUSED,
3037 gpointer user_data)
3039 TCPCharDriverTelnetInit *init = user_data;
3040 ssize_t ret;
3042 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3043 if (ret < 0) {
3044 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3045 ret = 0;
3046 } else {
3047 tcp_chr_disconnect(init->chr);
3048 return FALSE;
3051 init->buflen -= ret;
3053 if (init->buflen == 0) {
3054 tcp_chr_connect(init->chr);
3055 return FALSE;
3058 memmove(init->buf, init->buf + ret, init->buflen);
3060 return TRUE;
3063 static void tcp_chr_telnet_init(CharDriverState *chr)
3065 TCPCharDriver *s = chr->opaque;
3066 TCPCharDriverTelnetInit *init =
3067 g_new0(TCPCharDriverTelnetInit, 1);
3068 size_t n = 0;
3070 init->chr = chr;
3071 init->buflen = 12;
3073 #define IACSET(x, a, b, c) \
3074 do { \
3075 x[n++] = a; \
3076 x[n++] = b; \
3077 x[n++] = c; \
3078 } while (0)
3080 /* Prep the telnet negotion to put telnet in binary,
3081 * no echo, single char mode */
3082 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3083 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3084 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3085 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3087 #undef IACSET
3089 qio_channel_add_watch(
3090 s->ioc, G_IO_OUT,
3091 tcp_chr_telnet_init_io,
3092 init, NULL);
3096 static void tcp_chr_tls_handshake(Object *source,
3097 Error *err,
3098 gpointer user_data)
3100 CharDriverState *chr = user_data;
3101 TCPCharDriver *s = chr->opaque;
3103 if (err) {
3104 tcp_chr_disconnect(chr);
3105 } else {
3106 if (s->do_telnetopt) {
3107 tcp_chr_telnet_init(chr);
3108 } else {
3109 tcp_chr_connect(chr);
3115 static void tcp_chr_tls_init(CharDriverState *chr)
3117 TCPCharDriver *s = chr->opaque;
3118 QIOChannelTLS *tioc;
3119 Error *err = NULL;
3121 if (s->is_listen) {
3122 tioc = qio_channel_tls_new_server(
3123 s->ioc, s->tls_creds,
3124 NULL, /* XXX Use an ACL */
3125 &err);
3126 } else {
3127 tioc = qio_channel_tls_new_client(
3128 s->ioc, s->tls_creds,
3129 s->addr->u.inet.data->host,
3130 &err);
3132 if (tioc == NULL) {
3133 error_free(err);
3134 tcp_chr_disconnect(chr);
3135 return;
3137 object_unref(OBJECT(s->ioc));
3138 s->ioc = QIO_CHANNEL(tioc);
3140 qio_channel_tls_handshake(tioc,
3141 tcp_chr_tls_handshake,
3142 chr,
3143 NULL);
3147 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3149 TCPCharDriver *s = chr->opaque;
3150 if (s->ioc != NULL) {
3151 return -1;
3154 s->ioc = QIO_CHANNEL(sioc);
3155 object_ref(OBJECT(sioc));
3156 s->sioc = sioc;
3157 object_ref(OBJECT(sioc));
3159 qio_channel_set_blocking(s->ioc, false, NULL);
3161 if (s->do_nodelay) {
3162 qio_channel_set_delay(s->ioc, false);
3164 if (s->listen_tag) {
3165 g_source_remove(s->listen_tag);
3166 s->listen_tag = 0;
3169 if (s->tls_creds) {
3170 tcp_chr_tls_init(chr);
3171 } else {
3172 if (s->do_telnetopt) {
3173 tcp_chr_telnet_init(chr);
3174 } else {
3175 tcp_chr_connect(chr);
3179 return 0;
3183 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3185 int ret;
3186 QIOChannelSocket *sioc;
3188 sioc = qio_channel_socket_new_fd(fd, NULL);
3189 if (!sioc) {
3190 return -1;
3192 ret = tcp_chr_new_client(chr, sioc);
3193 object_unref(OBJECT(sioc));
3194 return ret;
3197 static gboolean tcp_chr_accept(QIOChannel *channel,
3198 GIOCondition cond,
3199 void *opaque)
3201 CharDriverState *chr = opaque;
3202 QIOChannelSocket *sioc;
3204 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3205 NULL);
3206 if (!sioc) {
3207 return TRUE;
3210 tcp_chr_new_client(chr, sioc);
3212 object_unref(OBJECT(sioc));
3214 return TRUE;
3217 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3219 TCPCharDriver *s = chr->opaque;
3220 QIOChannelSocket *sioc;
3222 /* It can't wait on s->connected, since it is set asynchronously
3223 * in TLS and telnet cases, only wait for an accepted socket */
3224 while (!s->ioc) {
3225 if (s->is_listen) {
3226 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3227 chr->filename);
3228 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3229 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3230 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3231 } else {
3232 sioc = qio_channel_socket_new();
3233 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3234 object_unref(OBJECT(sioc));
3235 return -1;
3237 tcp_chr_new_client(chr, sioc);
3238 object_unref(OBJECT(sioc));
3242 return 0;
3245 int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3247 if (chr->chr_wait_connected) {
3248 return chr->chr_wait_connected(chr, errp);
3251 return 0;
3254 static void tcp_chr_close(CharDriverState *chr)
3256 TCPCharDriver *s = chr->opaque;
3258 tcp_chr_free_connection(chr);
3260 if (s->reconnect_timer) {
3261 g_source_remove(s->reconnect_timer);
3262 s->reconnect_timer = 0;
3264 qapi_free_SocketAddress(s->addr);
3265 if (s->listen_tag) {
3266 g_source_remove(s->listen_tag);
3267 s->listen_tag = 0;
3269 if (s->listen_ioc) {
3270 object_unref(OBJECT(s->listen_ioc));
3272 if (s->tls_creds) {
3273 object_unref(OBJECT(s->tls_creds));
3275 g_free(s);
3276 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3280 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3282 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3283 CharDriverState *chr = opaque;
3284 TCPCharDriver *s = chr->opaque;
3286 if (err) {
3287 check_report_connect_error(chr, err);
3288 object_unref(src);
3289 return;
3292 s->connect_err_reported = false;
3293 tcp_chr_new_client(chr, sioc);
3294 object_unref(OBJECT(sioc));
3298 /*********************************************************/
3299 /* Ring buffer chardev */
3301 typedef struct {
3302 size_t size;
3303 size_t prod;
3304 size_t cons;
3305 uint8_t *cbuf;
3306 } RingBufCharDriver;
3308 static size_t ringbuf_count(const CharDriverState *chr)
3310 const RingBufCharDriver *d = chr->opaque;
3312 return d->prod - d->cons;
3315 /* Called with chr_write_lock held. */
3316 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3318 RingBufCharDriver *d = chr->opaque;
3319 int i;
3321 if (!buf || (len < 0)) {
3322 return -1;
3325 for (i = 0; i < len; i++ ) {
3326 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3327 if (d->prod - d->cons > d->size) {
3328 d->cons = d->prod - d->size;
3332 return 0;
3335 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3337 RingBufCharDriver *d = chr->opaque;
3338 int i;
3340 qemu_mutex_lock(&chr->chr_write_lock);
3341 for (i = 0; i < len && d->cons != d->prod; i++) {
3342 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3344 qemu_mutex_unlock(&chr->chr_write_lock);
3346 return i;
3349 static void ringbuf_chr_close(struct CharDriverState *chr)
3351 RingBufCharDriver *d = chr->opaque;
3353 g_free(d->cbuf);
3354 g_free(d);
3355 chr->opaque = NULL;
3358 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3359 ChardevBackend *backend,
3360 ChardevReturn *ret,
3361 Error **errp)
3363 ChardevRingbuf *opts = backend->u.ringbuf.data;
3364 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3365 CharDriverState *chr;
3366 RingBufCharDriver *d;
3368 chr = qemu_chr_alloc(common, errp);
3369 if (!chr) {
3370 return NULL;
3372 d = g_malloc(sizeof(*d));
3374 d->size = opts->has_size ? opts->size : 65536;
3376 /* The size must be power of 2 */
3377 if (d->size & (d->size - 1)) {
3378 error_setg(errp, "size of ringbuf chardev must be power of two");
3379 goto fail;
3382 d->prod = 0;
3383 d->cons = 0;
3384 d->cbuf = g_malloc0(d->size);
3386 chr->opaque = d;
3387 chr->chr_write = ringbuf_chr_write;
3388 chr->chr_close = ringbuf_chr_close;
3390 return chr;
3392 fail:
3393 g_free(d);
3394 qemu_chr_free_common(chr);
3395 return NULL;
3398 bool chr_is_ringbuf(const CharDriverState *chr)
3400 return chr->chr_write == ringbuf_chr_write;
3403 void qmp_ringbuf_write(const char *device, const char *data,
3404 bool has_format, enum DataFormat format,
3405 Error **errp)
3407 CharDriverState *chr;
3408 const uint8_t *write_data;
3409 int ret;
3410 gsize write_count;
3412 chr = qemu_chr_find(device);
3413 if (!chr) {
3414 error_setg(errp, "Device '%s' not found", device);
3415 return;
3418 if (!chr_is_ringbuf(chr)) {
3419 error_setg(errp,"%s is not a ringbuf device", device);
3420 return;
3423 if (has_format && (format == DATA_FORMAT_BASE64)) {
3424 write_data = qbase64_decode(data, -1,
3425 &write_count,
3426 errp);
3427 if (!write_data) {
3428 return;
3430 } else {
3431 write_data = (uint8_t *)data;
3432 write_count = strlen(data);
3435 ret = ringbuf_chr_write(chr, write_data, write_count);
3437 if (write_data != (uint8_t *)data) {
3438 g_free((void *)write_data);
3441 if (ret < 0) {
3442 error_setg(errp, "Failed to write to device %s", device);
3443 return;
3447 char *qmp_ringbuf_read(const char *device, int64_t size,
3448 bool has_format, enum DataFormat format,
3449 Error **errp)
3451 CharDriverState *chr;
3452 uint8_t *read_data;
3453 size_t count;
3454 char *data;
3456 chr = qemu_chr_find(device);
3457 if (!chr) {
3458 error_setg(errp, "Device '%s' not found", device);
3459 return NULL;
3462 if (!chr_is_ringbuf(chr)) {
3463 error_setg(errp,"%s is not a ringbuf device", device);
3464 return NULL;
3467 if (size <= 0) {
3468 error_setg(errp, "size must be greater than zero");
3469 return NULL;
3472 count = ringbuf_count(chr);
3473 size = size > count ? count : size;
3474 read_data = g_malloc(size + 1);
3476 ringbuf_chr_read(chr, read_data, size);
3478 if (has_format && (format == DATA_FORMAT_BASE64)) {
3479 data = g_base64_encode(read_data, size);
3480 g_free(read_data);
3481 } else {
3483 * FIXME should read only complete, valid UTF-8 characters up
3484 * to @size bytes. Invalid sequences should be replaced by a
3485 * suitable replacement character. Except when (and only
3486 * when) ring buffer lost characters since last read, initial
3487 * continuation characters should be dropped.
3489 read_data[size] = 0;
3490 data = (char *)read_data;
3493 return data;
3496 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3498 char host[65], port[33], width[8], height[8];
3499 int pos;
3500 const char *p;
3501 QemuOpts *opts;
3502 Error *local_err = NULL;
3504 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3505 if (local_err) {
3506 error_report_err(local_err);
3507 return NULL;
3510 if (strstart(filename, "mon:", &p)) {
3511 filename = p;
3512 qemu_opt_set(opts, "mux", "on", &error_abort);
3513 if (strcmp(filename, "stdio") == 0) {
3514 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3515 * but pass it to the guest. Handle this only for compat syntax,
3516 * for -chardev syntax we have special option for this.
3517 * This is what -nographic did, redirecting+muxing serial+monitor
3518 * to stdio causing Ctrl+C to be passed to guest. */
3519 qemu_opt_set(opts, "signal", "off", &error_abort);
3523 if (strcmp(filename, "null") == 0 ||
3524 strcmp(filename, "pty") == 0 ||
3525 strcmp(filename, "msmouse") == 0 ||
3526 strcmp(filename, "braille") == 0 ||
3527 strcmp(filename, "testdev") == 0 ||
3528 strcmp(filename, "stdio") == 0) {
3529 qemu_opt_set(opts, "backend", filename, &error_abort);
3530 return opts;
3532 if (strstart(filename, "vc", &p)) {
3533 qemu_opt_set(opts, "backend", "vc", &error_abort);
3534 if (*p == ':') {
3535 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3536 /* pixels */
3537 qemu_opt_set(opts, "width", width, &error_abort);
3538 qemu_opt_set(opts, "height", height, &error_abort);
3539 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3540 /* chars */
3541 qemu_opt_set(opts, "cols", width, &error_abort);
3542 qemu_opt_set(opts, "rows", height, &error_abort);
3543 } else {
3544 goto fail;
3547 return opts;
3549 if (strcmp(filename, "con:") == 0) {
3550 qemu_opt_set(opts, "backend", "console", &error_abort);
3551 return opts;
3553 if (strstart(filename, "COM", NULL)) {
3554 qemu_opt_set(opts, "backend", "serial", &error_abort);
3555 qemu_opt_set(opts, "path", filename, &error_abort);
3556 return opts;
3558 if (strstart(filename, "file:", &p)) {
3559 qemu_opt_set(opts, "backend", "file", &error_abort);
3560 qemu_opt_set(opts, "path", p, &error_abort);
3561 return opts;
3563 if (strstart(filename, "pipe:", &p)) {
3564 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3565 qemu_opt_set(opts, "path", p, &error_abort);
3566 return opts;
3568 if (strstart(filename, "tcp:", &p) ||
3569 strstart(filename, "telnet:", &p)) {
3570 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3571 host[0] = 0;
3572 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3573 goto fail;
3575 qemu_opt_set(opts, "backend", "socket", &error_abort);
3576 qemu_opt_set(opts, "host", host, &error_abort);
3577 qemu_opt_set(opts, "port", port, &error_abort);
3578 if (p[pos] == ',') {
3579 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3580 if (local_err) {
3581 error_report_err(local_err);
3582 goto fail;
3585 if (strstart(filename, "telnet:", &p))
3586 qemu_opt_set(opts, "telnet", "on", &error_abort);
3587 return opts;
3589 if (strstart(filename, "udp:", &p)) {
3590 qemu_opt_set(opts, "backend", "udp", &error_abort);
3591 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3592 host[0] = 0;
3593 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3594 goto fail;
3597 qemu_opt_set(opts, "host", host, &error_abort);
3598 qemu_opt_set(opts, "port", port, &error_abort);
3599 if (p[pos] == '@') {
3600 p += pos + 1;
3601 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3602 host[0] = 0;
3603 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3604 goto fail;
3607 qemu_opt_set(opts, "localaddr", host, &error_abort);
3608 qemu_opt_set(opts, "localport", port, &error_abort);
3610 return opts;
3612 if (strstart(filename, "unix:", &p)) {
3613 qemu_opt_set(opts, "backend", "socket", &error_abort);
3614 qemu_opts_do_parse(opts, p, "path", &local_err);
3615 if (local_err) {
3616 error_report_err(local_err);
3617 goto fail;
3619 return opts;
3621 if (strstart(filename, "/dev/parport", NULL) ||
3622 strstart(filename, "/dev/ppi", NULL)) {
3623 qemu_opt_set(opts, "backend", "parport", &error_abort);
3624 qemu_opt_set(opts, "path", filename, &error_abort);
3625 return opts;
3627 if (strstart(filename, "/dev/", NULL)) {
3628 qemu_opt_set(opts, "backend", "tty", &error_abort);
3629 qemu_opt_set(opts, "path", filename, &error_abort);
3630 return opts;
3633 fail:
3634 qemu_opts_del(opts);
3635 return NULL;
3638 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3640 const char *logfile = qemu_opt_get(opts, "logfile");
3642 backend->has_logfile = logfile != NULL;
3643 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3645 backend->has_logappend = true;
3646 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3650 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3651 Error **errp)
3653 const char *path = qemu_opt_get(opts, "path");
3654 ChardevFile *file;
3656 if (path == NULL) {
3657 error_setg(errp, "chardev: file: no filename given");
3658 return;
3660 file = backend->u.file.data = g_new0(ChardevFile, 1);
3661 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3662 file->out = g_strdup(path);
3664 file->has_append = true;
3665 file->append = qemu_opt_get_bool(opts, "append", false);
3668 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3669 Error **errp)
3671 ChardevStdio *stdio;
3673 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3674 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3675 stdio->has_signal = true;
3676 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3679 #ifdef HAVE_CHARDEV_SERIAL
3680 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3681 Error **errp)
3683 const char *device = qemu_opt_get(opts, "path");
3684 ChardevHostdev *serial;
3686 if (device == NULL) {
3687 error_setg(errp, "chardev: serial/tty: no device path given");
3688 return;
3690 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3691 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3692 serial->device = g_strdup(device);
3694 #endif
3696 #ifdef HAVE_CHARDEV_PARPORT
3697 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3698 Error **errp)
3700 const char *device = qemu_opt_get(opts, "path");
3701 ChardevHostdev *parallel;
3703 if (device == NULL) {
3704 error_setg(errp, "chardev: parallel: no device path given");
3705 return;
3707 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3708 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3709 parallel->device = g_strdup(device);
3711 #endif
3713 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3714 Error **errp)
3716 const char *device = qemu_opt_get(opts, "path");
3717 ChardevHostdev *dev;
3719 if (device == NULL) {
3720 error_setg(errp, "chardev: pipe: no device path given");
3721 return;
3723 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3724 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3725 dev->device = g_strdup(device);
3728 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3729 Error **errp)
3731 int val;
3732 ChardevRingbuf *ringbuf;
3734 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3735 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3737 val = qemu_opt_get_size(opts, "size", 0);
3738 if (val != 0) {
3739 ringbuf->has_size = true;
3740 ringbuf->size = val;
3744 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3745 Error **errp)
3747 const char *chardev = qemu_opt_get(opts, "chardev");
3748 ChardevMux *mux;
3750 if (chardev == NULL) {
3751 error_setg(errp, "chardev: mux: no chardev given");
3752 return;
3754 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3755 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3756 mux->chardev = g_strdup(chardev);
3759 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3760 Error **errp)
3762 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3763 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3764 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3765 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3766 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3767 const char *path = qemu_opt_get(opts, "path");
3768 const char *host = qemu_opt_get(opts, "host");
3769 const char *port = qemu_opt_get(opts, "port");
3770 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3771 SocketAddress *addr;
3772 ChardevSocket *sock;
3774 if (!path) {
3775 if (!host) {
3776 error_setg(errp, "chardev: socket: no host given");
3777 return;
3779 if (!port) {
3780 error_setg(errp, "chardev: socket: no port given");
3781 return;
3783 } else {
3784 if (tls_creds) {
3785 error_setg(errp, "TLS can only be used over TCP socket");
3786 return;
3790 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3791 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3793 sock->has_nodelay = true;
3794 sock->nodelay = do_nodelay;
3795 sock->has_server = true;
3796 sock->server = is_listen;
3797 sock->has_telnet = true;
3798 sock->telnet = is_telnet;
3799 sock->has_wait = true;
3800 sock->wait = is_waitconnect;
3801 sock->has_reconnect = true;
3802 sock->reconnect = reconnect;
3803 sock->tls_creds = g_strdup(tls_creds);
3805 addr = g_new0(SocketAddress, 1);
3806 if (path) {
3807 UnixSocketAddress *q_unix;
3808 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3809 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3810 q_unix->path = g_strdup(path);
3811 } else {
3812 addr->type = SOCKET_ADDRESS_KIND_INET;
3813 addr->u.inet.data = g_new(InetSocketAddress, 1);
3814 *addr->u.inet.data = (InetSocketAddress) {
3815 .host = g_strdup(host),
3816 .port = g_strdup(port),
3817 .has_to = qemu_opt_get(opts, "to"),
3818 .to = qemu_opt_get_number(opts, "to", 0),
3819 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3820 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3821 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3822 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3825 sock->addr = addr;
3828 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3829 Error **errp)
3831 const char *host = qemu_opt_get(opts, "host");
3832 const char *port = qemu_opt_get(opts, "port");
3833 const char *localaddr = qemu_opt_get(opts, "localaddr");
3834 const char *localport = qemu_opt_get(opts, "localport");
3835 bool has_local = false;
3836 SocketAddress *addr;
3837 ChardevUdp *udp;
3839 if (host == NULL || strlen(host) == 0) {
3840 host = "localhost";
3842 if (port == NULL || strlen(port) == 0) {
3843 error_setg(errp, "chardev: udp: remote port not specified");
3844 return;
3846 if (localport == NULL || strlen(localport) == 0) {
3847 localport = "0";
3848 } else {
3849 has_local = true;
3851 if (localaddr == NULL || strlen(localaddr) == 0) {
3852 localaddr = "";
3853 } else {
3854 has_local = true;
3857 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3858 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3860 addr = g_new0(SocketAddress, 1);
3861 addr->type = SOCKET_ADDRESS_KIND_INET;
3862 addr->u.inet.data = g_new(InetSocketAddress, 1);
3863 *addr->u.inet.data = (InetSocketAddress) {
3864 .host = g_strdup(host),
3865 .port = g_strdup(port),
3866 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3867 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3868 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3869 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3871 udp->remote = addr;
3873 if (has_local) {
3874 udp->has_local = true;
3875 addr = g_new0(SocketAddress, 1);
3876 addr->type = SOCKET_ADDRESS_KIND_INET;
3877 addr->u.inet.data = g_new(InetSocketAddress, 1);
3878 *addr->u.inet.data = (InetSocketAddress) {
3879 .host = g_strdup(localaddr),
3880 .port = g_strdup(localport),
3882 udp->local = addr;
3886 typedef struct CharDriver {
3887 const char *name;
3888 ChardevBackendKind kind;
3889 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3890 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3891 ChardevReturn *ret, Error **errp);
3892 } CharDriver;
3894 static GSList *backends;
3896 void register_char_driver(const char *name, ChardevBackendKind kind,
3897 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3898 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3899 ChardevReturn *ret, Error **errp))
3901 CharDriver *s;
3903 s = g_malloc0(sizeof(*s));
3904 s->name = g_strdup(name);
3905 s->kind = kind;
3906 s->parse = parse;
3907 s->create = create;
3909 backends = g_slist_append(backends, s);
3912 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3913 void (*init)(struct CharDriverState *s),
3914 Error **errp)
3916 Error *local_err = NULL;
3917 CharDriver *cd;
3918 CharDriverState *chr;
3919 GSList *i;
3920 ChardevReturn *ret = NULL;
3921 ChardevBackend *backend;
3922 const char *id = qemu_opts_id(opts);
3923 char *bid = NULL;
3925 if (qemu_opt_get(opts, "backend") == NULL) {
3926 error_setg(errp, "chardev: \"%s\" missing backend",
3927 qemu_opts_id(opts));
3928 goto err;
3931 if (is_help_option(qemu_opt_get(opts, "backend"))) {
3932 fprintf(stderr, "Available chardev backend types:\n");
3933 for (i = backends; i; i = i->next) {
3934 cd = i->data;
3935 fprintf(stderr, "%s\n", cd->name);
3937 exit(!is_help_option(qemu_opt_get(opts, "backend")));
3940 if (id == NULL) {
3941 error_setg(errp, "chardev: no id specified");
3942 goto err;
3945 for (i = backends; i; i = i->next) {
3946 cd = i->data;
3948 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3949 break;
3952 if (i == NULL) {
3953 error_setg(errp, "chardev: backend \"%s\" not found",
3954 qemu_opt_get(opts, "backend"));
3955 goto err;
3958 backend = g_new0(ChardevBackend, 1);
3960 if (qemu_opt_get_bool(opts, "mux", 0)) {
3961 bid = g_strdup_printf("%s-base", id);
3964 chr = NULL;
3965 backend->type = cd->kind;
3966 if (cd->parse) {
3967 cd->parse(opts, backend, &local_err);
3968 if (local_err) {
3969 error_propagate(errp, local_err);
3970 goto qapi_out;
3972 } else {
3973 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3974 qemu_chr_parse_common(opts, cc);
3975 backend->u.null.data = cc; /* Any ChardevCommon member would work */
3978 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3979 if (!ret) {
3980 goto qapi_out;
3983 if (bid) {
3984 qapi_free_ChardevBackend(backend);
3985 qapi_free_ChardevReturn(ret);
3986 backend = g_new0(ChardevBackend, 1);
3987 backend->u.mux.data = g_new0(ChardevMux, 1);
3988 backend->type = CHARDEV_BACKEND_KIND_MUX;
3989 backend->u.mux.data->chardev = g_strdup(bid);
3990 ret = qmp_chardev_add(id, backend, errp);
3991 if (!ret) {
3992 chr = qemu_chr_find(bid);
3993 qemu_chr_delete(chr);
3994 chr = NULL;
3995 goto qapi_out;
3999 chr = qemu_chr_find(id);
4001 qapi_out:
4002 qapi_free_ChardevBackend(backend);
4003 qapi_free_ChardevReturn(ret);
4004 g_free(bid);
4005 return chr;
4007 err:
4008 return NULL;
4011 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
4012 void (*init)(struct CharDriverState *s))
4014 const char *p;
4015 CharDriverState *chr;
4016 QemuOpts *opts;
4017 Error *err = NULL;
4019 if (strstart(filename, "chardev:", &p)) {
4020 return qemu_chr_find(p);
4023 opts = qemu_chr_parse_compat(label, filename);
4024 if (!opts)
4025 return NULL;
4027 chr = qemu_chr_new_from_opts(opts, init, &err);
4028 if (err) {
4029 error_report_err(err);
4031 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4032 qemu_chr_fe_claim_no_fail(chr);
4033 monitor_init(chr, MONITOR_USE_READLINE);
4035 qemu_opts_del(opts);
4036 return chr;
4039 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
4041 CharDriverState *chr;
4042 chr = qemu_chr_new_noreplay(label, filename, init);
4043 if (chr) {
4044 chr->replay = replay_mode != REPLAY_MODE_NONE;
4045 if (chr->replay && chr->chr_ioctl) {
4046 fprintf(stderr,
4047 "Replay: ioctl is not supported for serial devices yet\n");
4049 replay_register_char_driver(chr);
4051 return chr;
4054 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
4056 if (chr->chr_set_echo) {
4057 chr->chr_set_echo(chr, echo);
4061 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
4063 if (chr->fe_open == fe_open) {
4064 return;
4066 chr->fe_open = fe_open;
4067 if (chr->chr_set_fe_open) {
4068 chr->chr_set_fe_open(chr, fe_open);
4072 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
4074 if (chr->chr_fe_event) {
4075 chr->chr_fe_event(chr, event);
4079 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
4080 GIOFunc func, void *user_data)
4082 GSource *src;
4083 guint tag;
4085 if (s->chr_add_watch == NULL) {
4086 return 0;
4089 src = s->chr_add_watch(s, cond);
4090 if (!src) {
4091 return 0;
4094 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4095 tag = g_source_attach(src, NULL);
4096 g_source_unref(src);
4098 return tag;
4101 int qemu_chr_fe_claim(CharDriverState *s)
4103 if (s->avail_connections < 1) {
4104 return -1;
4106 s->avail_connections--;
4107 return 0;
4110 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
4112 if (qemu_chr_fe_claim(s) != 0) {
4113 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
4114 __func__, s->label);
4115 exit(1);
4119 void qemu_chr_fe_release(CharDriverState *s)
4121 s->avail_connections++;
4124 void qemu_chr_disconnect(CharDriverState *chr)
4126 if (chr->chr_disconnect) {
4127 chr->chr_disconnect(chr);
4131 static void qemu_chr_free_common(CharDriverState *chr)
4133 g_free(chr->filename);
4134 g_free(chr->label);
4135 if (chr->logfd != -1) {
4136 close(chr->logfd);
4138 qemu_mutex_destroy(&chr->chr_write_lock);
4139 g_free(chr);
4142 void qemu_chr_free(CharDriverState *chr)
4144 if (chr->chr_close) {
4145 chr->chr_close(chr);
4147 qemu_chr_free_common(chr);
4150 void qemu_chr_delete(CharDriverState *chr)
4152 QTAILQ_REMOVE(&chardevs, chr, next);
4153 qemu_chr_free(chr);
4156 ChardevInfoList *qmp_query_chardev(Error **errp)
4158 ChardevInfoList *chr_list = NULL;
4159 CharDriverState *chr;
4161 QTAILQ_FOREACH(chr, &chardevs, next) {
4162 ChardevInfoList *info = g_malloc0(sizeof(*info));
4163 info->value = g_malloc0(sizeof(*info->value));
4164 info->value->label = g_strdup(chr->label);
4165 info->value->filename = g_strdup(chr->filename);
4166 info->value->frontend_open = chr->fe_open;
4168 info->next = chr_list;
4169 chr_list = info;
4172 return chr_list;
4175 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4177 ChardevBackendInfoList *backend_list = NULL;
4178 CharDriver *c = NULL;
4179 GSList *i = NULL;
4181 for (i = backends; i; i = i->next) {
4182 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4183 c = i->data;
4184 info->value = g_malloc0(sizeof(*info->value));
4185 info->value->name = g_strdup(c->name);
4187 info->next = backend_list;
4188 backend_list = info;
4191 return backend_list;
4194 CharDriverState *qemu_chr_find(const char *name)
4196 CharDriverState *chr;
4198 QTAILQ_FOREACH(chr, &chardevs, next) {
4199 if (strcmp(chr->label, name) != 0)
4200 continue;
4201 return chr;
4203 return NULL;
4206 QemuOptsList qemu_chardev_opts = {
4207 .name = "chardev",
4208 .implied_opt_name = "backend",
4209 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4210 .desc = {
4212 .name = "backend",
4213 .type = QEMU_OPT_STRING,
4215 .name = "path",
4216 .type = QEMU_OPT_STRING,
4218 .name = "host",
4219 .type = QEMU_OPT_STRING,
4221 .name = "port",
4222 .type = QEMU_OPT_STRING,
4224 .name = "localaddr",
4225 .type = QEMU_OPT_STRING,
4227 .name = "localport",
4228 .type = QEMU_OPT_STRING,
4230 .name = "to",
4231 .type = QEMU_OPT_NUMBER,
4233 .name = "ipv4",
4234 .type = QEMU_OPT_BOOL,
4236 .name = "ipv6",
4237 .type = QEMU_OPT_BOOL,
4239 .name = "wait",
4240 .type = QEMU_OPT_BOOL,
4242 .name = "server",
4243 .type = QEMU_OPT_BOOL,
4245 .name = "delay",
4246 .type = QEMU_OPT_BOOL,
4248 .name = "reconnect",
4249 .type = QEMU_OPT_NUMBER,
4251 .name = "telnet",
4252 .type = QEMU_OPT_BOOL,
4254 .name = "tls-creds",
4255 .type = QEMU_OPT_STRING,
4257 .name = "width",
4258 .type = QEMU_OPT_NUMBER,
4260 .name = "height",
4261 .type = QEMU_OPT_NUMBER,
4263 .name = "cols",
4264 .type = QEMU_OPT_NUMBER,
4266 .name = "rows",
4267 .type = QEMU_OPT_NUMBER,
4269 .name = "mux",
4270 .type = QEMU_OPT_BOOL,
4272 .name = "signal",
4273 .type = QEMU_OPT_BOOL,
4275 .name = "name",
4276 .type = QEMU_OPT_STRING,
4278 .name = "debug",
4279 .type = QEMU_OPT_NUMBER,
4281 .name = "size",
4282 .type = QEMU_OPT_SIZE,
4284 .name = "chardev",
4285 .type = QEMU_OPT_STRING,
4287 .name = "append",
4288 .type = QEMU_OPT_BOOL,
4290 .name = "logfile",
4291 .type = QEMU_OPT_STRING,
4293 .name = "logappend",
4294 .type = QEMU_OPT_BOOL,
4296 { /* end of list */ }
4300 #ifdef _WIN32
4302 static CharDriverState *qmp_chardev_open_file(const char *id,
4303 ChardevBackend *backend,
4304 ChardevReturn *ret,
4305 Error **errp)
4307 ChardevFile *file = backend->u.file.data;
4308 ChardevCommon *common = qapi_ChardevFile_base(file);
4309 HANDLE out;
4310 DWORD accessmode;
4311 DWORD flags;
4313 if (file->has_in) {
4314 error_setg(errp, "input file not supported");
4315 return NULL;
4318 if (file->has_append && file->append) {
4319 /* Append to file if it already exists. */
4320 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4321 flags = OPEN_ALWAYS;
4322 } else {
4323 /* Truncate file if it already exists. */
4324 accessmode = GENERIC_WRITE;
4325 flags = CREATE_ALWAYS;
4328 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4329 FILE_ATTRIBUTE_NORMAL, NULL);
4330 if (out == INVALID_HANDLE_VALUE) {
4331 error_setg(errp, "open %s failed", file->out);
4332 return NULL;
4334 return qemu_chr_open_win_file(out, common, errp);
4337 static CharDriverState *qmp_chardev_open_serial(const char *id,
4338 ChardevBackend *backend,
4339 ChardevReturn *ret,
4340 Error **errp)
4342 ChardevHostdev *serial = backend->u.serial.data;
4343 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4344 return qemu_chr_open_win_path(serial->device, common, errp);
4347 #else /* WIN32 */
4349 static int qmp_chardev_open_file_source(char *src, int flags,
4350 Error **errp)
4352 int fd = -1;
4354 TFR(fd = qemu_open(src, flags, 0666));
4355 if (fd == -1) {
4356 error_setg_file_open(errp, errno, src);
4358 return fd;
4361 static CharDriverState *qmp_chardev_open_file(const char *id,
4362 ChardevBackend *backend,
4363 ChardevReturn *ret,
4364 Error **errp)
4366 ChardevFile *file = backend->u.file.data;
4367 ChardevCommon *common = qapi_ChardevFile_base(file);
4368 int flags, in = -1, out;
4370 flags = O_WRONLY | O_CREAT | O_BINARY;
4371 if (file->has_append && file->append) {
4372 flags |= O_APPEND;
4373 } else {
4374 flags |= O_TRUNC;
4377 out = qmp_chardev_open_file_source(file->out, flags, errp);
4378 if (out < 0) {
4379 return NULL;
4382 if (file->has_in) {
4383 flags = O_RDONLY;
4384 in = qmp_chardev_open_file_source(file->in, flags, errp);
4385 if (in < 0) {
4386 qemu_close(out);
4387 return NULL;
4391 return qemu_chr_open_fd(in, out, common, errp);
4394 #ifdef HAVE_CHARDEV_SERIAL
4395 static CharDriverState *qmp_chardev_open_serial(const char *id,
4396 ChardevBackend *backend,
4397 ChardevReturn *ret,
4398 Error **errp)
4400 ChardevHostdev *serial = backend->u.serial.data;
4401 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4402 int fd;
4404 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4405 if (fd < 0) {
4406 return NULL;
4408 qemu_set_nonblock(fd);
4409 return qemu_chr_open_tty_fd(fd, common, errp);
4411 #endif
4413 #ifdef HAVE_CHARDEV_PARPORT
4414 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4415 ChardevBackend *backend,
4416 ChardevReturn *ret,
4417 Error **errp)
4419 ChardevHostdev *parallel = backend->u.parallel.data;
4420 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4421 int fd;
4423 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4424 if (fd < 0) {
4425 return NULL;
4427 return qemu_chr_open_pp_fd(fd, common, errp);
4429 #endif
4431 #endif /* WIN32 */
4433 static gboolean socket_reconnect_timeout(gpointer opaque)
4435 CharDriverState *chr = opaque;
4436 TCPCharDriver *s = chr->opaque;
4437 QIOChannelSocket *sioc;
4439 s->reconnect_timer = 0;
4441 if (chr->be_open) {
4442 return false;
4445 sioc = qio_channel_socket_new();
4446 qio_channel_socket_connect_async(sioc, s->addr,
4447 qemu_chr_socket_connected,
4448 chr, NULL);
4450 return false;
4453 static CharDriverState *qmp_chardev_open_socket(const char *id,
4454 ChardevBackend *backend,
4455 ChardevReturn *ret,
4456 Error **errp)
4458 CharDriverState *chr;
4459 TCPCharDriver *s;
4460 ChardevSocket *sock = backend->u.socket.data;
4461 SocketAddress *addr = sock->addr;
4462 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4463 bool is_listen = sock->has_server ? sock->server : true;
4464 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4465 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4466 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4467 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4468 QIOChannelSocket *sioc = NULL;
4470 chr = qemu_chr_alloc(common, errp);
4471 if (!chr) {
4472 return NULL;
4474 s = g_new0(TCPCharDriver, 1);
4476 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4477 s->is_listen = is_listen;
4478 s->is_telnet = is_telnet;
4479 s->do_nodelay = do_nodelay;
4480 if (sock->tls_creds) {
4481 Object *creds;
4482 creds = object_resolve_path_component(
4483 object_get_objects_root(), sock->tls_creds);
4484 if (!creds) {
4485 error_setg(errp, "No TLS credentials with id '%s'",
4486 sock->tls_creds);
4487 goto error;
4489 s->tls_creds = (QCryptoTLSCreds *)
4490 object_dynamic_cast(creds,
4491 TYPE_QCRYPTO_TLS_CREDS);
4492 if (!s->tls_creds) {
4493 error_setg(errp, "Object with id '%s' is not TLS credentials",
4494 sock->tls_creds);
4495 goto error;
4497 object_ref(OBJECT(s->tls_creds));
4498 if (is_listen) {
4499 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4500 error_setg(errp, "%s",
4501 "Expected TLS credentials for server endpoint");
4502 goto error;
4504 } else {
4505 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4506 error_setg(errp, "%s",
4507 "Expected TLS credentials for client endpoint");
4508 goto error;
4513 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4515 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
4516 if (s->is_unix) {
4517 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
4520 chr->opaque = s;
4521 chr->chr_wait_connected = tcp_chr_wait_connected;
4522 chr->chr_write = tcp_chr_write;
4523 chr->chr_sync_read = tcp_chr_sync_read;
4524 chr->chr_close = tcp_chr_close;
4525 chr->chr_disconnect = tcp_chr_disconnect;
4526 chr->get_msgfds = tcp_get_msgfds;
4527 chr->set_msgfds = tcp_set_msgfds;
4528 chr->chr_add_client = tcp_chr_add_client;
4529 chr->chr_add_watch = tcp_chr_add_watch;
4530 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4531 /* be isn't opened until we get a connection */
4532 chr->explicit_be_open = true;
4534 chr->filename = SocketAddress_to_str("disconnected:",
4535 addr, is_listen, is_telnet);
4537 if (is_listen) {
4538 if (is_telnet) {
4539 s->do_telnetopt = 1;
4541 } else if (reconnect > 0) {
4542 s->reconnect_time = reconnect;
4545 if (s->reconnect_time) {
4546 sioc = qio_channel_socket_new();
4547 qio_channel_socket_connect_async(sioc, s->addr,
4548 qemu_chr_socket_connected,
4549 chr, NULL);
4550 } else {
4551 if (s->is_listen) {
4552 sioc = qio_channel_socket_new();
4553 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4554 goto error;
4556 s->listen_ioc = sioc;
4557 if (is_waitconnect &&
4558 qemu_chr_wait_connected(chr, errp) < 0) {
4559 goto error;
4561 if (!s->ioc) {
4562 s->listen_tag = qio_channel_add_watch(
4563 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4564 tcp_chr_accept, chr, NULL);
4566 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4567 goto error;
4571 return chr;
4573 error:
4574 if (sioc) {
4575 object_unref(OBJECT(sioc));
4577 if (s->tls_creds) {
4578 object_unref(OBJECT(s->tls_creds));
4580 g_free(s);
4581 qemu_chr_free_common(chr);
4582 return NULL;
4585 static CharDriverState *qmp_chardev_open_udp(const char *id,
4586 ChardevBackend *backend,
4587 ChardevReturn *ret,
4588 Error **errp)
4590 ChardevUdp *udp = backend->u.udp.data;
4591 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4592 QIOChannelSocket *sioc = qio_channel_socket_new();
4594 if (qio_channel_socket_dgram_sync(sioc,
4595 udp->local, udp->remote,
4596 errp) < 0) {
4597 object_unref(OBJECT(sioc));
4598 return NULL;
4600 return qemu_chr_open_udp(sioc, common, errp);
4604 bool qemu_chr_has_feature(CharDriverState *chr,
4605 CharDriverFeature feature)
4607 return test_bit(feature, chr->features);
4610 void qemu_chr_set_feature(CharDriverState *chr,
4611 CharDriverFeature feature)
4613 return set_bit(feature, chr->features);
4616 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4617 Error **errp)
4619 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4620 CharDriverState *chr = NULL;
4621 Error *local_err = NULL;
4622 GSList *i;
4623 CharDriver *cd;
4625 chr = qemu_chr_find(id);
4626 if (chr) {
4627 error_setg(errp, "Chardev '%s' already exists", id);
4628 g_free(ret);
4629 return NULL;
4632 for (i = backends; i; i = i->next) {
4633 cd = i->data;
4635 if (cd->kind == backend->type) {
4636 chr = cd->create(id, backend, ret, &local_err);
4637 if (local_err) {
4638 error_propagate(errp, local_err);
4639 goto out_error;
4641 break;
4645 if (chr == NULL) {
4646 assert(!i);
4647 error_setg(errp, "chardev backend not available");
4648 goto out_error;
4651 chr->label = g_strdup(id);
4652 chr->avail_connections =
4653 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4654 if (!chr->filename) {
4655 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4657 if (!chr->explicit_be_open) {
4658 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4660 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4661 return ret;
4663 out_error:
4664 g_free(ret);
4665 return NULL;
4668 void qmp_chardev_remove(const char *id, Error **errp)
4670 CharDriverState *chr;
4672 chr = qemu_chr_find(id);
4673 if (chr == NULL) {
4674 error_setg(errp, "Chardev '%s' not found", id);
4675 return;
4677 if (chr->chr_can_read || chr->chr_read ||
4678 chr->chr_event || chr->handler_opaque) {
4679 error_setg(errp, "Chardev '%s' is busy", id);
4680 return;
4682 if (chr->replay) {
4683 error_setg(errp,
4684 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4685 return;
4687 qemu_chr_delete(chr);
4690 void qemu_chr_cleanup(void)
4692 CharDriverState *chr, *tmp;
4694 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4695 qemu_chr_delete(chr);
4699 static void register_types(void)
4701 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4702 qemu_chr_open_null);
4703 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4704 qemu_chr_parse_socket, qmp_chardev_open_socket);
4705 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4706 qmp_chardev_open_udp);
4707 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4708 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4709 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4710 qemu_chr_parse_file_out, qmp_chardev_open_file);
4711 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4712 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4713 #if defined HAVE_CHARDEV_SERIAL
4714 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4715 qemu_chr_parse_serial, qmp_chardev_open_serial);
4716 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4717 qemu_chr_parse_serial, qmp_chardev_open_serial);
4718 #endif
4719 #ifdef HAVE_CHARDEV_PARPORT
4720 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4721 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4722 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4723 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4724 #endif
4725 #ifdef HAVE_CHARDEV_PTY
4726 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4727 qemu_chr_open_pty);
4728 #endif
4729 #ifdef _WIN32
4730 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4731 qemu_chr_open_win_con);
4732 #endif
4733 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4734 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4735 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4736 qemu_chr_open_mux);
4737 /* Bug-compatibility: */
4738 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4739 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4740 /* this must be done after machine init, since we register FEs with muxes
4741 * as part of realize functions like serial_isa_realizefn when -nographic
4742 * is specified
4744 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4747 type_init(register_types);