qemu-char.c 98.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * QEMU System Emulator
 *
 * Copyright (c) 2003-2008 Fabrice Bellard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include "qemu-common.h"
25
#include "monitor/monitor.h"
26
#include "ui/console.h"
27
#include "sysemu/sysemu.h"
28
#include "qemu/timer.h"
29
#include "sysemu/char.h"
aurel32's avatar
aurel32 committed
30
#include "hw/usb.h"
31
#include "qmp-commands.h"
32 33 34 35 36 37 38 39 40 41 42 43 44 45

#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <sys/time.h>
#include <zlib.h>

#ifndef _WIN32
#include <sys/times.h>
#include <sys/wait.h>
#include <termios.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
46
#include <sys/resource.h>
47 48
#include <sys/socket.h>
#include <netinet/in.h>
49 50
#include <net/if.h>
#include <arpa/inet.h>
51 52 53
#include <dirent.h>
#include <netdb.h>
#include <sys/select.h>
54
#ifdef CONFIG_BSD
55
#include <sys/stat.h>
56 57 58
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#include <dev/ppbus/ppi.h>
#include <dev/ppbus/ppbconf.h>
59 60 61
#elif defined(__DragonFly__)
#include <dev/misc/ppi/ppi.h>
#include <bus/ppbus/ppbconf.h>
62
#endif
Aurelien Jarno's avatar
Aurelien Jarno committed
63
#else
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
#ifdef __linux__
#include <linux/ppdev.h>
#include <linux/parport.h>
#endif
#ifdef __sun__
#include <sys/stat.h>
#include <sys/ethernet.h>
#include <sys/sockio.h>
#include <netinet/arp.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h> // must come after ip.h
#include <netinet/udp.h>
#include <netinet/tcp.h>
#endif
#endif
#endif

83
#include "qemu/sockets.h"
Alon Levy's avatar
Alon Levy committed
84
#include "ui/qemu-spice.h"
85

86 87
#define READ_BUF_LEN 4096

88 89 90
/***********************************************************/
/* character device */

91 92
static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
    QTAILQ_HEAD_INITIALIZER(chardevs);
93

94
void qemu_chr_be_event(CharDriverState *s, int event)
95
{
96 97 98
    /* Keep track if the char device is open */
    switch (event) {
        case CHR_EVENT_OPENED:
99
            s->be_open = 1;
100 101
            break;
        case CHR_EVENT_CLOSED:
102
            s->be_open = 0;
103 104 105
            break;
    }

106 107 108 109 110
    if (!s->chr_event)
        return;
    s->chr_event(s->handler_opaque, event);
}

111
void qemu_chr_be_generic_open(CharDriverState *s)
112
{
113
    qemu_chr_be_event(s, CHR_EVENT_OPENED);
114 115
}

116
int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
117 118 119 120
{
    return s->chr_write(s, buf, len);
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
{
    int offset = 0;
    int res;

    while (offset < len) {
        do {
            res = s->chr_write(s, buf + offset, len - offset);
            if (res == -1 && errno == EAGAIN) {
                g_usleep(100);
            }
        } while (res == -1 && errno == EAGAIN);

        if (res == 0) {
            break;
        }

        if (res < 0) {
            return res;
        }

        offset += res;
    }

    return offset;
}

148
int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
149 150 151 152 153 154
{
    if (!s->chr_ioctl)
        return -ENOTSUP;
    return s->chr_ioctl(s, cmd, arg);
}

155
int qemu_chr_be_can_write(CharDriverState *s)
156 157 158 159 160 161
{
    if (!s->chr_can_read)
        return 0;
    return s->chr_can_read(s->handler_opaque);
}

162
void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
163
{
164 165 166
    if (s->chr_read) {
        s->chr_read(s->handler_opaque, buf, len);
    }
167 168
}

169
int qemu_chr_fe_get_msgfd(CharDriverState *s)
170 171 172 173
{
    return s->get_msgfd ? s->get_msgfd(s) : -1;
}

174 175 176 177 178
int qemu_chr_add_client(CharDriverState *s, int fd)
{
    return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
}

179 180 181 182
void qemu_chr_accept_input(CharDriverState *s)
{
    if (s->chr_accept_input)
        s->chr_accept_input(s);
183
    qemu_notify_event();
184 185
}

186
void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
187
{
188
    char buf[READ_BUF_LEN];
189 190 191
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof(buf), fmt, ap);
192
    qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
193 194 195
    va_end(ap);
}

196 197
static void remove_fd_in_watch(CharDriverState *chr);

198
void qemu_chr_add_handlers(CharDriverState *s,
199
                           IOCanReadHandler *fd_can_read,
200 201 202 203
                           IOReadHandler *fd_read,
                           IOEventHandler *fd_event,
                           void *opaque)
{
204 205
    int fe_open;

206
    if (!opaque && !fd_can_read && !fd_read && !fd_event) {
207
        fe_open = 0;
208
        remove_fd_in_watch(s);
209 210
    } else {
        fe_open = 1;
211
    }
212 213 214 215 216 217
    s->chr_can_read = fd_can_read;
    s->chr_read = fd_read;
    s->chr_event = fd_event;
    s->handler_opaque = opaque;
    if (s->chr_update_read_handler)
        s->chr_update_read_handler(s);
218

219
    if (!s->explicit_fe_open) {
220
        qemu_chr_fe_set_open(s, fe_open);
221 222
    }

223 224
    /* We're connecting to an already opened device, so let's make sure we
       also get the open event */
225
    if (fe_open && s->be_open) {
226
        qemu_chr_be_generic_open(s);
227
    }
228 229 230 231 232 233 234
}

static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    return len;
}

235
static CharDriverState *qemu_chr_open_null(void)
236 237 238
{
    CharDriverState *chr;

239
    chr = g_malloc0(sizeof(CharDriverState));
240
    chr->chr_write = null_chr_write;
241
    chr->explicit_be_open = true;
242
    return chr;
243 244 245 246 247 248 249
}

/* MUX driver for serial I/O splitting */
#define MAX_MUX 4
#define MUX_BUFFER_SIZE 32	/* Must be a power of 2.  */
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
typedef struct {
250
    IOCanReadHandler *chr_can_read[MAX_MUX];
251 252 253 254
    IOReadHandler *chr_read[MAX_MUX];
    IOEventHandler *chr_event[MAX_MUX];
    void *ext_opaque[MAX_MUX];
    CharDriverState *drv;
255
    int focus;
256 257 258
    int mux_cnt;
    int term_got_escape;
    int max_size;
259 260 261 262 263 264
    /* Intermediate input buffer allows to catch escape sequences even if the
       currently active device is not accepting any input - but only until it
       is full as well. */
    unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
    int prod[MAX_MUX];
    int cons[MAX_MUX];
265
    int timestamps;
266
    int linestart;
267
    int64_t timestamps_start;
268 269 270 271 272 273 274
} MuxDriver;


static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    MuxDriver *d = chr->opaque;
    int ret;
275
    if (!d->timestamps) {
276 277 278 279 280
        ret = d->drv->chr_write(d->drv, buf, len);
    } else {
        int i;

        ret = 0;
281 282
        for (i = 0; i < len; i++) {
            if (d->linestart) {
283 284 285 286
                char buf1[64];
                int64_t ti;
                int secs;

287
                ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
288 289 290
                if (d->timestamps_start == -1)
                    d->timestamps_start = ti;
                ti -= d->timestamps_start;
291
                secs = ti / 1000;
292 293 294 295 296
                snprintf(buf1, sizeof(buf1),
                         "[%02d:%02d:%02d.%03d] ",
                         secs / 3600,
                         (secs / 60) % 60,
                         secs % 60,
297
                         (int)(ti % 1000));
298
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
299 300 301 302 303
                d->linestart = 0;
            }
            ret += d->drv->chr_write(d->drv, buf+i, 1);
            if (buf[i] == '\n') {
                d->linestart = 1;
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
            }
        }
    }
    return ret;
}

static const char * const mux_help[] = {
    "% h    print this help\n\r",
    "% x    exit emulator\n\r",
    "% s    save disk data back to file (if -snapshot)\n\r",
    "% t    toggle console timestamps\n\r"
    "% b    send break (magic sysrq)\n\r",
    "% c    switch between console and monitor\n\r",
    "% %  sends %\n\r",
    NULL
};

int term_escape_char = 0x01; /* ctrl-a is used for escape */
static void mux_print_help(CharDriverState *chr)
{
    int i, j;
    char ebuf[15] = "Escape-Char";
    char cbuf[50] = "\n\r";

    if (term_escape_char > 0 && term_escape_char < 26) {
        snprintf(cbuf, sizeof(cbuf), "\n\r");
        snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
    } else {
        snprintf(cbuf, sizeof(cbuf),
                 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
                 term_escape_char);
    }
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
    for (i = 0; mux_help[i] != NULL; i++) {
        for (j=0; mux_help[i][j] != '\0'; j++) {
            if (mux_help[i][j] == '%')
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
            else
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
        }
    }
}

347 348 349 350 351 352
static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
{
    if (d->chr_event[mux_nr])
        d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
}

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
{
    if (d->term_got_escape) {
        d->term_got_escape = 0;
        if (ch == term_escape_char)
            goto send_char;
        switch(ch) {
        case '?':
        case 'h':
            mux_print_help(chr);
            break;
        case 'x':
            {
                 const char *term =  "QEMU: Terminated\n\r";
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
                 exit(0);
                 break;
            }
        case 's':
372
            bdrv_commit_all();
373 374
            break;
        case 'b':
375
            qemu_chr_be_event(chr, CHR_EVENT_BREAK);
376 377 378
            break;
        case 'c':
            /* Switch to the next registered device */
379 380 381 382 383
            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
            d->focus++;
            if (d->focus >= d->mux_cnt)
                d->focus = 0;
            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
384
            break;
385 386 387
        case 't':
            d->timestamps = !d->timestamps;
            d->timestamps_start = -1;
388
            d->linestart = 0;
389
            break;
390 391 392 393 394 395 396 397 398 399 400 401 402
        }
    } else if (ch == term_escape_char) {
        d->term_got_escape = 1;
    } else {
    send_char:
        return 1;
    }
    return 0;
}

static void mux_chr_accept_input(CharDriverState *chr)
{
    MuxDriver *d = chr->opaque;
403
    int m = d->focus;
404

405
    while (d->prod[m] != d->cons[m] &&
406 407 408
           d->chr_can_read[m] &&
           d->chr_can_read[m](d->ext_opaque[m])) {
        d->chr_read[m](d->ext_opaque[m],
409
                       &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
410 411 412 413 414 415 416
    }
}

static int mux_chr_can_read(void *opaque)
{
    CharDriverState *chr = opaque;
    MuxDriver *d = chr->opaque;
417
    int m = d->focus;
418

419
    if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
420
        return 1;
421 422
    if (d->chr_can_read[m])
        return d->chr_can_read[m](d->ext_opaque[m]);
423 424 425 426 427 428 429
    return 0;
}

static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
{
    CharDriverState *chr = opaque;
    MuxDriver *d = chr->opaque;
430
    int m = d->focus;
431 432 433 434 435 436
    int i;

    mux_chr_accept_input (opaque);

    for(i = 0; i < size; i++)
        if (mux_proc_byte(chr, d, buf[i])) {
437
            if (d->prod[m] == d->cons[m] &&
438 439 440 441
                d->chr_can_read[m] &&
                d->chr_can_read[m](d->ext_opaque[m]))
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
            else
442
                d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
443 444 445 446 447 448 449 450 451 452 453
        }
}

static void mux_chr_event(void *opaque, int event)
{
    CharDriverState *chr = opaque;
    MuxDriver *d = chr->opaque;
    int i;

    /* Send the event to all registered listeners */
    for (i = 0; i < d->mux_cnt; i++)
454
        mux_chr_send_event(d, i, event);
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
}

static void mux_chr_update_read_handler(CharDriverState *chr)
{
    MuxDriver *d = chr->opaque;

    if (d->mux_cnt >= MAX_MUX) {
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
        return;
    }
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
    d->chr_read[d->mux_cnt] = chr->chr_read;
    d->chr_event[d->mux_cnt] = chr->chr_event;
    /* Fix up the real driver with mux routines */
    if (d->mux_cnt == 0) {
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
                              mux_chr_event, chr);
    }
474 475
    if (d->focus != -1) {
        mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
Gerd Hoffmann's avatar
Gerd Hoffmann committed
476
    }
477
    d->focus = d->mux_cnt;
478
    d->mux_cnt++;
479
    mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
480 481
}

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
static bool muxes_realized;

/**
 * Called after processing of default and command-line-specified
 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
 * to a mux chardev. This is done here to ensure that
 * output/prompts/banners are only displayed for the FE that has
 * focus when initial command-line processing/machine init is
 * completed.
 *
 * After this point, any new FE attached to any new or existing
 * mux will receive CHR_EVENT_OPENED notifications for the BE
 * immediately.
 */
static void muxes_realize_done(Notifier *notifier, void *unused)
{
    CharDriverState *chr;

    QTAILQ_FOREACH(chr, &chardevs, next) {
        if (chr->is_mux) {
            MuxDriver *d = chr->opaque;
            int i;

            /* send OPENED to all already-attached FEs */
            for (i = 0; i < d->mux_cnt; i++) {
                mux_chr_send_event(d, i, CHR_EVENT_OPENED);
            }
            /* mark mux as OPENED so any new FEs will immediately receive
             * OPENED event
             */
            qemu_chr_be_generic_open(chr);
        }
    }
    muxes_realized = true;
}

static Notifier muxes_realize_notify = {
    .notify = muxes_realize_done,
};

522 523 524 525 526
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
{
    CharDriverState *chr;
    MuxDriver *d;

527 528
    chr = g_malloc0(sizeof(CharDriverState));
    d = g_malloc0(sizeof(MuxDriver));
529 530 531

    chr->opaque = d;
    d->drv = drv;
532
    d->focus = -1;
533 534 535
    chr->chr_write = mux_chr_write;
    chr->chr_update_read_handler = mux_chr_update_read_handler;
    chr->chr_accept_input = mux_chr_accept_input;
536
    /* Frontend guest-open / -close notification is not support with muxes */
537
    chr->chr_set_fe_open = NULL;
538 539 540 541 542
    /* only default to opened state if we've realized the initial
     * set of muxes
     */
    chr->explicit_be_open = muxes_realized ? 0 : 1;
    chr->is_mux = 1;
543

544 545 546 547 548
    return chr;
}


#ifdef _WIN32
549
int send_all(int fd, const void *buf, int len1)
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
{
    int ret, len;

    len = len1;
    while (len > 0) {
        ret = send(fd, buf, len, 0);
        if (ret < 0) {
            errno = WSAGetLastError();
            if (errno != WSAEWOULDBLOCK) {
                return -1;
            }
        } else if (ret == 0) {
            break;
        } else {
            buf += ret;
            len -= ret;
        }
    }
    return len1 - len;
}

#else

573
int send_all(int fd, const void *_buf, int len1)
574 575
{
    int ret, len;
576
    const uint8_t *buf = _buf;
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592

    len = len1;
    while (len > 0) {
        ret = write(fd, buf, len);
        if (ret < 0) {
            if (errno != EINTR && errno != EAGAIN)
                return -1;
        } else if (ret == 0) {
            break;
        } else {
            buf += ret;
            len -= ret;
        }
    }
    return len1 - len;
}
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616

int recv_all(int fd, void *_buf, int len1, bool single_read)
{
    int ret, len;
    uint8_t *buf = _buf;

    len = len1;
    while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
        if (ret < 0) {
            if (errno != EINTR && errno != EAGAIN) {
                return -1;
            }
            continue;
        } else {
            if (single_read) {
                return ret;
            }
            buf += ret;
            len -= ret;
        }
    }
    return len1 - len;
}

617 618
#endif /* !_WIN32 */

619 620
typedef struct IOWatchPoll
{
621 622
    GSource parent;

623
    GIOChannel *channel;
624 625 626
    GSource *src;

    IOCanReadHandler *fd_can_read;
627
    GSourceFunc fd_read;
628 629 630 631 632
    void *opaque;
} IOWatchPoll;

static IOWatchPoll *io_watch_poll_from_source(GSource *source)
{
633
    return container_of(source, IOWatchPoll, parent);
634 635 636 637 638
}

static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
{
    IOWatchPoll *iwp = io_watch_poll_from_source(source);
639
    bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
640
    bool was_active = iwp->src != NULL;
641
    if (was_active == now_active) {
642 643 644
        return FALSE;
    }

645
    if (now_active) {
646 647
        iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
        g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
648 649
        g_source_attach(iwp->src, NULL);
    } else {
650 651 652
        g_source_destroy(iwp->src);
        g_source_unref(iwp->src);
        iwp->src = NULL;
653 654
    }
    return FALSE;
655 656 657 658
}

static gboolean io_watch_poll_check(GSource *source)
{
659
    return FALSE;
660 661 662 663 664
}

static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
                                       gpointer user_data)
{
665
    abort();
666 667 668 669
}

static void io_watch_poll_finalize(GSource *source)
{
670 671 672 673 674 675 676 677 678 679
    /* Due to a glib bug, removing the last reference to a source
     * inside a finalize callback causes recursive locking (and a
     * deadlock).  This is not a problem inside other callbacks,
     * including dispatch callbacks, so we call io_remove_watch_poll
     * to remove this source.  At this point, iwp->src must
     * be NULL, or we would leak it.
     *
     * This would be solved much more elegantly by child sources,
     * but we support older glib versions that do not have them.
     */
680
    IOWatchPoll *iwp = io_watch_poll_from_source(source);
681
    assert(iwp->src == NULL);
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
}

static GSourceFuncs io_watch_poll_funcs = {
    .prepare = io_watch_poll_prepare,
    .check = io_watch_poll_check,
    .dispatch = io_watch_poll_dispatch,
    .finalize = io_watch_poll_finalize,
};

/* Can only be used for read */
static guint io_add_watch_poll(GIOChannel *channel,
                               IOCanReadHandler *fd_can_read,
                               GIOFunc fd_read,
                               gpointer user_data)
{
    IOWatchPoll *iwp;
698
    int tag;
699

700
    iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
701 702
    iwp->fd_can_read = fd_can_read;
    iwp->opaque = user_data;
703 704 705
    iwp->channel = channel;
    iwp->fd_read = (GSourceFunc) fd_read;
    iwp->src = NULL;
706

707 708 709
    tag = g_source_attach(&iwp->parent, NULL);
    g_source_unref(&iwp->parent);
    return tag;
710 711
}

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
static void io_remove_watch_poll(guint tag)
{
    GSource *source;
    IOWatchPoll *iwp;

    g_return_if_fail (tag > 0);

    source = g_main_context_find_source_by_id(NULL, tag);
    g_return_if_fail (source != NULL);

    iwp = io_watch_poll_from_source(source);
    if (iwp->src) {
        g_source_destroy(iwp->src);
        g_source_unref(iwp->src);
        iwp->src = NULL;
    }
    g_source_destroy(&iwp->parent);
}

731 732 733 734 735 736 737 738
static void remove_fd_in_watch(CharDriverState *chr)
{
    if (chr->fd_in_tag) {
        io_remove_watch_poll(chr->fd_in_tag);
        chr->fd_in_tag = 0;
    }
}

Blue Swirl's avatar
Blue Swirl committed
739
#ifndef _WIN32
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
static GIOChannel *io_channel_from_fd(int fd)
{
    GIOChannel *chan;

    if (fd == -1) {
        return NULL;
    }

    chan = g_io_channel_unix_new(fd);

    g_io_channel_set_encoding(chan, NULL, NULL);
    g_io_channel_set_buffered(chan, FALSE);

    return chan;
}
Blue Swirl's avatar
Blue Swirl committed
755
#endif
756

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
static GIOChannel *io_channel_from_socket(int fd)
{
    GIOChannel *chan;

    if (fd == -1) {
        return NULL;
    }

#ifdef _WIN32
    chan = g_io_channel_win32_new_socket(fd);
#else
    chan = g_io_channel_unix_new(fd);
#endif

    g_io_channel_set_encoding(chan, NULL, NULL);
    g_io_channel_set_buffered(chan, FALSE);

    return chan;
}

777
static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
778
{
779 780
    size_t offset = 0;
    GIOStatus status = G_IO_STATUS_NORMAL;
781

782 783
    while (offset < len && status == G_IO_STATUS_NORMAL) {
        gsize bytes_written = 0;
784 785

        status = g_io_channel_write_chars(fd, buf + offset, len - offset,
786
                                          &bytes_written, NULL);
787
        offset += bytes_written;
788
    }
789

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
    if (offset > 0) {
        return offset;
    }
    switch (status) {
    case G_IO_STATUS_NORMAL:
        g_assert(len == 0);
        return 0;
    case G_IO_STATUS_AGAIN:
        errno = EAGAIN;
        return -1;
    default:
        break;
    }
    errno = EINVAL;
    return -1;
805 806
}

Blue Swirl's avatar
Blue Swirl committed
807 808
#ifndef _WIN32

809 810 811
typedef struct FDCharDriver {
    CharDriverState *chr;
    GIOChannel *fd_in, *fd_out;
812
    int max_size;
813
    QTAILQ_ENTRY(FDCharDriver) node;
814 815 816 817 818
} FDCharDriver;

static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    FDCharDriver *s = chr->opaque;
819
    
820
    return io_channel_send(s->fd_out, buf, len);
821 822
}

823
static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
824 825 826
{
    CharDriverState *chr = opaque;
    FDCharDriver *s = chr->opaque;
827
    int len;
828
    uint8_t buf[READ_BUF_LEN];
829 830
    GIOStatus status;
    gsize bytes_read;
831 832

    len = sizeof(buf);
833
    if (len > s->max_size) {
834
        len = s->max_size;
835 836
    }
    if (len == 0) {
837
        return TRUE;
838 839 840 841 842
    }

    status = g_io_channel_read_chars(chan, (gchar *)buf,
                                     len, &bytes_read, NULL);
    if (status == G_IO_STATUS_EOF) {
843
        remove_fd_in_watch(chr);
844
        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
845
        return FALSE;
846
    }
847 848
    if (status == G_IO_STATUS_NORMAL) {
        qemu_chr_be_write(chr, buf, bytes_read);
849
    }
850 851 852 853 854 855 856 857 858 859 860

    return TRUE;
}

static int fd_chr_read_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    FDCharDriver *s = chr->opaque;

    s->max_size = qemu_chr_be_can_write(chr);
    return s->max_size;
861 862
}

863 864 865 866 867 868
static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
{
    FDCharDriver *s = chr->opaque;
    return g_io_create_watch(s->fd_out, cond);
}

869 870 871 872
static void fd_chr_update_read_handler(CharDriverState *chr)
{
    FDCharDriver *s = chr->opaque;

873
    remove_fd_in_watch(chr);
874
    if (s->fd_in) {
875 876
        chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
                                           fd_chr_read, chr);
877 878 879 880 881 882 883
    }
}

static void fd_chr_close(struct CharDriverState *chr)
{
    FDCharDriver *s = chr->opaque;

884
    remove_fd_in_watch(chr);
885 886 887 888 889
    if (s->fd_in) {
        g_io_channel_unref(s->fd_in);
    }
    if (s->fd_out) {
        g_io_channel_unref(s->fd_out);
890 891
    }

892
    g_free(s);
893
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
894 895 896 897 898 899 900 901
}

/* open a character device to a unix fd */
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
{
    CharDriverState *chr;
    FDCharDriver *s;

902 903
    chr = g_malloc0(sizeof(CharDriverState));
    s = g_malloc0(sizeof(FDCharDriver));
904 905
    s->fd_in = io_channel_from_fd(fd_in);
    s->fd_out = io_channel_from_fd(fd_out);
906
    fcntl(fd_out, F_SETFL, O_NONBLOCK);
907
    s->chr = chr;
908
    chr->opaque = s;
909
    chr->chr_add_watch = fd_chr_add_watch;
910 911 912 913 914 915 916
    chr->chr_write = fd_chr_write;
    chr->chr_update_read_handler = fd_chr_update_read_handler;
    chr->chr_close = fd_chr_close;

    return chr;
}

917
static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
918 919 920
{
    int fd_in, fd_out;
    char filename_in[256], filename_out[256];
921
    const char *filename = opts->device;
922 923 924

    if (filename == NULL) {
        fprintf(stderr, "chardev: pipe: no filename given\n");
925
        return NULL;
926
    }
927 928 929

    snprintf(filename_in, 256, "%s.in", filename);
    snprintf(filename_out, 256, "%s.out", filename);
Kevin Wolf's avatar
Kevin Wolf committed
930 931
    TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
    TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
932 933 934 935 936
    if (fd_in < 0 || fd_out < 0) {
	if (fd_in >= 0)
	    close(fd_in);
	if (fd_out >= 0)
	    close(fd_out);
937
        TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
938
        if (fd_in < 0) {
939
            return NULL;
940
        }
941
    }
942
    return qemu_chr_open_fd(fd_in, fd_out);
943 944 945 946 947
}

/* init terminal so that we can grab keys */
static struct termios oldtty;
static int old_fd0_flags;
948
static bool stdio_allow_signal;
949 950 951 952 953 954 955

static void term_exit(void)
{
    tcsetattr (0, TCSANOW, &oldtty);
    fcntl(0, F_SETFL, old_fd0_flags);
}

956
static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
957 958 959
{
    struct termios tty;

960
    tty = oldtty;
961 962
    if (!echo) {
        tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
963
                          |INLCR|IGNCR|ICRNL|IXON);
964 965 966 967 968 969 970 971
        tty.c_oflag |= OPOST;
        tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
        tty.c_cflag &= ~(CSIZE|PARENB);
        tty.c_cflag |= CS8;
        tty.c_cc[VMIN] = 1;
        tty.c_cc[VTIME] = 0;
    }
    if (!stdio_allow_signal)
972 973 974 975 976 977 978 979 980 981 982
        tty.c_lflag &= ~ISIG;

    tcsetattr (0, TCSANOW, &tty);
}

static void qemu_chr_close_stdio(struct CharDriverState *chr)
{
    term_exit();
    fd_chr_close(chr);
}

983
static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
984 985 986
{
    CharDriverState *chr;

987 988 989 990
    if (is_daemonized()) {
        error_report("cannot use stdio with -daemonize");
        return NULL;
    }
991 992 993 994
    old_fd0_flags = fcntl(0, F_GETFL);
    tcgetattr (0, &oldtty);
    fcntl(0, F_SETFL, O_NONBLOCK);
    atexit(term_exit);
995

996 997
    chr = qemu_chr_open_fd(0, 1);
    chr->chr_close = qemu_chr_close_stdio;
998
    chr->chr_set_echo = qemu_chr_set_echo_stdio;
999 1000 1001
    if (opts->has_signal) {
        stdio_allow_signal = opts->signal;
    }
1002
    qemu_chr_fe_set_echo(chr, false);
1003

1004
    return chr;
1005 1006 1007
}

#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1008 1009
    || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
    || defined(__GLIBC__)
1010

1011 1012
#define HAVE_CHARDEV_TTY 1

1013
typedef struct {
1014
    GIOChannel *fd;
1015 1016
    int connected;
    int read_bytes;
1017
    guint timer_tag;
1018 1019 1020 1021 1022
} PtyCharDriver;

static void pty_chr_update_read_handler(CharDriverState *chr);
static void pty_chr_state(CharDriverState *chr, int connected);

1023 1024 1025 1026 1027
static gboolean pty_chr_timer(gpointer opaque)
{
    struct CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;

1028
    s->timer_tag = 0;
1029 1030 1031 1032
    if (!s->connected) {
        /* Next poll ... */
        pty_chr_update_read_handler(chr);
    }
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    return FALSE;
}

static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
{
    PtyCharDriver *s = chr->opaque;

    if (s->timer_tag) {
        g_source_remove(s->timer_tag);
        s->timer_tag = 0;
    }

    if (ms == 1000) {
        s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
    } else {
        s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
    }
}

1052 1053 1054 1055 1056 1057 1058 1059 1060
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    PtyCharDriver *s = chr->opaque;

    if (!s->connected) {
        /* guest sends data, check for (re-)connect */
        pty_chr_update_read_handler(chr);
        return 0;
    }
1061
    return io_channel_send(s->fd, buf, len);
1062 1063
}

1064 1065 1066 1067 1068 1069
static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
{
    PtyCharDriver *s = chr->opaque;
    return g_io_create_watch(s->fd, cond);
}

1070 1071 1072 1073 1074
static int pty_chr_read_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;

1075
    s->read_bytes = qemu_chr_be_can_write(chr);
1076 1077 1078
    return s->read_bytes;
}

1079
static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1080 1081 1082
{
    CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;
1083
    gsize size, len;
1084
    uint8_t buf[READ_BUF_LEN];
1085
    GIOStatus status;
1086 1087 1088 1089

    len = sizeof(buf);
    if (len > s->read_bytes)
        len = s->read_bytes;
1090 1091 1092
    if (len == 0) {
        return TRUE;
    }
1093 1094
    status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
    if (status != G_IO_STATUS_NORMAL) {
1095
        pty_chr_state(chr, 0);
1096 1097
        return FALSE;
    } else {
1098
        pty_chr_state(chr, 1);
1099
        qemu_chr_be_write(chr, buf, size);
1100
    }
1101
    return TRUE;
1102 1103 1104 1105 1106
}

static void pty_chr_update_read_handler(CharDriverState *chr)
{
    PtyCharDriver *s = chr->opaque;
1107
    GPollFD pfd;
1108

1109 1110 1111 1112 1113 1114 1115 1116
    pfd.fd = g_io_channel_unix_get_fd(s->fd);
    pfd.events = G_IO_OUT;
    pfd.revents = 0;
    g_poll(&pfd, 1, 0);
    if (pfd.revents & G_IO_HUP) {
        pty_chr_state(chr, 0);
    } else {
        pty_chr_state(chr, 1);
1117
    }
1118 1119 1120 1121 1122 1123 1124
}

static void pty_chr_state(CharDriverState *chr, int connected)
{
    PtyCharDriver *s = chr->opaque;

    if (!connected) {
1125
        remove_fd_in_watch(chr);
1126 1127 1128 1129
        s->connected = 0;
        /* (re-)connect poll interval for idle guests: once per second.
         * We check more frequently in case the guests sends data to
         * the virtual device linked to our pty. */
1130
        pty_chr_rearm_timer(chr, 1000);
1131
    } else {
1132 1133 1134 1135 1136 1137
        if (s->timer_tag) {
            g_source_remove(s->timer_tag);
            s->timer_tag = 0;
        }
        if (!s->connected) {
            s->connected = 1;
1138
            qemu_chr_be_generic_open(chr);
1139 1140
            chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
                                               pty_chr_read, chr);
1141
        }
1142 1143 1144 1145 1146 1147 1148
    }
}


static void pty_chr_close(struct CharDriverState *chr)
{
    PtyCharDriver *s = chr->opaque;
1149
    int fd;
1150

1151
    remove_fd_in_watch(chr);
1152 1153 1154
    fd = g_io_channel_unix_get_fd(s->fd);
    g_io_channel_unref(s->fd);
    close(fd);
1155 1156
    if (s->timer_tag) {
        g_source_remove(s->timer_tag);
1157
        s->timer_tag = 0;
1158
    }
1159
    g_free(s);
1160
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1161 1162
}

1163 1164
static CharDriverState *qemu_chr_open_pty(const char *id,
                                          ChardevReturn *ret)
1165 1166 1167
{
    CharDriverState *chr;
    PtyCharDriver *s;
1168
    int master_fd, slave_fd;
1169 1170
    char pty_name[PATH_MAX];

1171 1172
    master_fd = qemu_openpty_raw(&slave_fd, pty_name);
    if (master_fd < 0) {
1173
        return NULL;
1174 1175 1176 1177
    }

    close(slave_fd);

1178 1179
    chr = g_malloc0(sizeof(CharDriverState));

1180 1181
    chr->filename = g_strdup_printf("pty:%s", pty_name);
    ret->pty = g_strdup(pty_name);
1182
    ret->has_pty = true;
1183

1184
    fprintf(stderr, "char device redirected to %s (label %s)\n",
1185
            pty_name, id);
1186

1187
    s = g_malloc0(sizeof(PtyCharDriver));
1188 1189 1190 1191
    chr->opaque = s;
    chr->chr_write = pty_chr_write;
    chr->chr_update_read_handler = pty_chr_update_read_handler;
    chr->chr_close = pty_chr_close;
1192
    chr->chr_add_watch = pty_chr_add_watch;
1193
    chr->explicit_be_open = true;
1194

1195
    s->fd = io_channel_from_fd(master_fd);
1196
    s->timer_tag = 0;
1197

1198
    return chr;
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
}

static void tty_serial_init(int fd, int speed,
                            int parity, int data_bits, int stop_bits)
{
    struct termios tty;
    speed_t spd;

#if 0
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
           speed, parity, data_bits, stop_bits);
#endif
    tcgetattr (fd, &tty);

1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
#define check_speed(val) if (speed <= val) { spd = B##val; break; }
    speed = speed * 10 / 11;
    do {
        check_speed(50);
        check_speed(75);
        check_speed(110);
        check_speed(134);
        check_speed(150);
        check_speed(200);
        check_speed(300);
        check_speed(600);
        check_speed(1200);
        check_speed(1800);
        check_speed(2400);
        check_speed(4800);
        check_speed(9600);
        check_speed(19200);
        check_speed(38400);
        /* Non-Posix values follow. They may be unsupported on some systems. */
        check_speed(57600);
        check_speed(115200);
#ifdef B230400
        check_speed(230400);
#endif
#ifdef B460800
        check_speed(460800);
#endif
#ifdef B500000
        check_speed(500000);
#endif
#ifdef B576000
        check_speed(576000);
#endif
#ifdef B921600
        check_speed(921600);
#endif
#ifdef B1000000
        check_speed(1000000);
#endif
#ifdef B1152000
        check_speed(1152000);
#endif
#ifdef B1500000
        check_speed(1500000);
#endif
#ifdef B2000000
        check_speed(2000000);
#endif
#ifdef B2500000
        check_speed(2500000);
#endif
#ifdef B3000000
        check_speed(3000000);
#endif
#ifdef B3500000
        check_speed(3500000);
#endif
#ifdef B4000000
        check_speed(4000000);
#endif
1273
        spd = B115200;
1274
    } while (0);
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323

    cfsetispeed(&tty, spd);
    cfsetospeed(&tty, spd);

    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
                          |INLCR|IGNCR|ICRNL|IXON);
    tty.c_oflag |= OPOST;
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
    switch(data_bits) {
    default:
    case 8:
        tty.c_cflag |= CS8;
        break;
    case 7:
        tty.c_cflag |= CS7;
        break;
    case 6:
        tty.c_cflag |= CS6;
        break;
    case 5:
        tty.c_cflag |= CS5;
        break;
    }
    switch(parity) {
    default:
    case 'N':
        break;
    case 'E':
        tty.c_cflag |= PARENB;
        break;
    case 'O':
        tty.c_cflag |= PARENB | PARODD;
        break;
    }
    if (stop_bits == 2)
        tty.c_cflag |= CSTOPB;

    tcsetattr (fd, TCSANOW, &tty);
}

static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
{
    FDCharDriver *s = chr->opaque;

    switch(cmd) {
    case CHR_IOCTL_SERIAL_SET_PARAMS:
        {
            QEMUSerialSetParams *ssp = arg;
1324 1325
            tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
                            ssp->speed, ssp->parity,
1326 1327 1328 1329 1330 1331
                            ssp->data_bits, ssp->stop_bits);
        }
        break;
    case CHR_IOCTL_SERIAL_SET_BREAK:
        {
            int enable = *(int *)arg;
1332 1333 1334
            if (enable) {
                tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
            }
1335 1336 1337 1338 1339 1340
        }
        break;
    case CHR_IOCTL_SERIAL_GET_TIOCM:
        {
            int sarg = 0;
            int *targ = (int *)arg;
1341
            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1342
            *targ = 0;
aurel32's avatar
aurel32 committed
1343
            if (sarg & TIOCM_CTS)
1344
                *targ |= CHR_TIOCM_CTS;
aurel32's avatar
aurel32 committed
1345
            if (sarg & TIOCM_CAR)
1346
                *targ |= CHR_TIOCM_CAR;
aurel32's avatar
aurel32 committed
1347
            if (sarg & TIOCM_DSR)
1348
                *targ |= CHR_TIOCM_DSR;
aurel32's avatar
aurel32 committed
1349
            if (sarg & TIOCM_RI)
1350
                *targ |= CHR_TIOCM_RI;
aurel32's avatar
aurel32 committed
1351
            if (sarg & TIOCM_DTR)
1352
                *targ |= CHR_TIOCM_DTR;
aurel32's avatar
aurel32 committed
1353
            if (sarg & TIOCM_RTS)
1354 1355 1356 1357 1358 1359 1360
                *targ |= CHR_TIOCM_RTS;
        }
        break;
    case CHR_IOCTL_SERIAL_SET_TIOCM:
        {
            int sarg = *(int *)arg;
            int targ = 0;
1361
            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
aurel32's avatar
aurel32 committed
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
            targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
                     | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
            if (sarg & CHR_TIOCM_CTS)
                targ |= TIOCM_CTS;
            if (sarg & CHR_TIOCM_CAR)
                targ |= TIOCM_CAR;
            if (sarg & CHR_TIOCM_DSR)
                targ |= TIOCM_DSR;
            if (sarg & CHR_TIOCM_RI)
                targ |= TIOCM_RI;
            if (sarg & CHR_TIOCM_DTR)
1373
                targ |= TIOCM_DTR;
aurel32's avatar
aurel32 committed
1374
            if (sarg & CHR_TIOCM_RTS)
1375
                targ |= TIOCM_RTS;
1376
            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1377 1378 1379 1380 1381 1382 1383 1384
        }
        break;
    default:
        return -ENOTSUP;
    }
    return 0;
}

1385 1386 1387 1388 1389 1390
static void qemu_chr_close_tty(CharDriverState *chr)
{
    FDCharDriver *s = chr->opaque;
    int fd = -1;

    if (s) {
1391
        fd = g_io_channel_unix_get_fd(s->fd_in);
1392 1393 1394 1395 1396 1397 1398 1399 1400
    }

    fd_chr_close(chr);

    if (fd >= 0) {
        close(fd);
    }
}

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
static CharDriverState *qemu_chr_open_tty_fd(int fd)
{
    CharDriverState *chr;

    tty_serial_init(fd, 115200, 'N', 8, 1);
    chr = qemu_chr_open_fd(fd, fd);
    chr->chr_ioctl = tty_serial_ioctl;
    chr->chr_close = qemu_chr_close_tty;
    return chr;
}
1411 1412 1413
#endif /* __linux__ || __sun__ */

#if defined(__linux__)
1414 1415 1416

#define HAVE_CHARDEV_PARPORT 1

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
typedef struct {
    int fd;
    int mode;
} ParallelCharDriver;

static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
{
    if (s->mode != mode) {
	int m = mode;
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
            return 0;
	s->mode = mode;
    }
    return 1;
}

static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
{
    ParallelCharDriver *drv = chr->opaque;
    int fd = drv->fd;
    uint8_t b;

    switch(cmd) {
    case CHR_IOCTL_PP_READ_DATA:
        if (ioctl(fd, PPRDATA, &b) < 0)
            return -ENOTSUP;
        *(uint8_t *)arg = b;
        break;
    case CHR_IOCTL_PP_WRITE_DATA:
        b = *(uint8_t *)arg;
        if (ioctl(fd, PPWDATA, &b) < 0)
            return -ENOTSUP;
        break;
    case CHR_IOCTL_PP_READ_CONTROL:
        if (ioctl(fd, PPRCONTROL, &b) < 0)
            return -ENOTSUP;
	/* Linux gives only the lowest bits, and no way to know data
	   direction! For better compatibility set the fixed upper
	   bits. */
        *(uint8_t *)arg = b | 0xc0;
        break;
    case CHR_IOCTL_PP_WRITE_CONTROL:
        b = *(uint8_t *)arg;
        if (ioctl(fd, PPWCONTROL, &b) < 0)
            return -ENOTSUP;
        break;
    case CHR_IOCTL_PP_READ_STATUS:
        if (ioctl(fd, PPRSTATUS, &b) < 0)
            return -ENOTSUP;
        *(uint8_t *)arg = b;
        break;
    case CHR_IOCTL_PP_DATA_DIR:
        if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
            return -ENOTSUP;
        break;
    case CHR_IOCTL_PP_EPP_READ_ADDR:
	if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
	    struct ParallelIOArg *parg = arg;
	    int n = read(fd, parg->buffer, parg->count);
	    if (n != parg->count) {
		return -EIO;
	    }
	}
        break;
    case CHR_IOCTL_PP_EPP_READ:
	if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
	    struct ParallelIOArg *parg = arg;
	    int n = read(fd, parg->buffer, parg->count);
	    if (n != parg->count) {
		return -EIO;
	    }
	}
        break;
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
	if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
	    struct ParallelIOArg *parg = arg;
	    int n = write(fd, parg->buffer, parg->count);
	    if (n != parg->count) {
		return -EIO;
	    }
	}
        break;
    case CHR_IOCTL_PP_EPP_WRITE:
	if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
	    struct ParallelIOArg *parg = arg;
	    int n = write(fd, parg->buffer, parg->count);
	    if (n != parg->count) {
		return -EIO;
	    }
	}
        break;
    default:
        return -ENOTSUP;
    }
    return 0;
}

static void pp_close(CharDriverState *chr)
{
    ParallelCharDriver *drv = chr->opaque;
    int fd = drv->fd;

    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
    ioctl(fd, PPRELEASE);
    close(fd);
1522
    g_free(drv);
1523
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1524 1525
}

1526
static CharDriverState *qemu_chr_open_pp_fd(int fd)
1527 1528 1529 1530 1531 1532
{
    CharDriverState *chr;
    ParallelCharDriver *drv;

    if (ioctl(fd, PPCLAIM) < 0) {
        close(fd);
1533
        return NULL;
1534 1535
    }

1536
    drv = g_malloc0(sizeof(ParallelCharDriver));
1537 1538 1539
    drv->fd = fd;
    drv->mode = IEEE1284_MODE_COMPAT;

1540
    chr = g_malloc0(sizeof(CharDriverState));
1541 1542 1543 1544 1545
    chr->chr_write = null_chr_write;
    chr->chr_ioctl = pp_ioctl;
    chr->chr_close = pp_close;
    chr->opaque = drv;

1546
    return chr;
1547 1548 1549
}
#endif /* __linux__ */

1550
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1551 1552 1553

#define HAVE_CHARDEV_PARPORT 1

1554 1555
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
{
1556
    int fd = (int)(intptr_t)chr->opaque;
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
    uint8_t b;

    switch(cmd) {
    case CHR_IOCTL_PP_READ_DATA:
        if (ioctl(fd, PPIGD