fd.c 1.9 KB
Newer Older
J
Jeff Dike 已提交
1
/*
J
Jeff Dike 已提交
2
 * Copyright (C) 2001 - 2007 Jeff Dike (jdike@{linux.intel,addtoit}.com)
L
Linus Torvalds 已提交
3 4 5
 * Licensed under the GPL
 */

J
Jeff Dike 已提交
6
#include <stdio.h>
J
Jeff Dike 已提交
7 8
#include <stdlib.h>
#include <unistd.h>
L
Linus Torvalds 已提交
9
#include <errno.h>
J
Jeff Dike 已提交
10
#include <termios.h>
L
Linus Torvalds 已提交
11
#include "chan_user.h"
12 13
#include <os.h>
#include <um_malloc.h>
L
Linus Torvalds 已提交
14 15 16 17 18 19 20 21

struct fd_chan {
	int fd;
	int raw;
	struct termios tt;
	char str[sizeof("1234567890\0")];
};

J
Jeff Dike 已提交
22
static void *fd_init(char *str, int device, const struct chan_opts *opts)
L
Linus Torvalds 已提交
23 24 25 26 27
{
	struct fd_chan *data;
	char *end;
	int n;

J
Jeff Dike 已提交
28 29 30 31
	if (*str != ':') {
		printk(UM_KERN_ERR "fd_init : channel type 'fd' must specify a "
		       "file descriptor\n");
		return NULL;
L
Linus Torvalds 已提交
32 33 34
	}
	str++;
	n = strtoul(str, &end, 0);
J
Jeff Dike 已提交
35 36 37 38
	if ((*end != '\0') || (end == str)) {
		printk(UM_KERN_ERR "fd_init : couldn't parse file descriptor "
		       "'%s'\n", str);
		return NULL;
L
Linus Torvalds 已提交
39
	}
J
Jeff Dike 已提交
40

J
Jeff Dike 已提交
41
	data = uml_kmalloc(sizeof(*data), UM_GFP_KERNEL);
J
Jeff Dike 已提交
42
	if (data == NULL)
J
Jeff Dike 已提交
43 44
		return NULL;

L
Linus Torvalds 已提交
45 46
	*data = ((struct fd_chan) { .fd  	= n,
				    .raw  	= opts->raw });
J
Jeff Dike 已提交
47
	return data;
L
Linus Torvalds 已提交
48 49 50 51 52 53 54
}

static int fd_open(int input, int output, int primary, void *d, char **dev_out)
{
	struct fd_chan *data = d;
	int err;

J
Jeff Dike 已提交
55
	if (data->raw && isatty(data->fd)) {
L
Linus Torvalds 已提交
56
		CATCH_EINTR(err = tcgetattr(data->fd, &data->tt));
J
Jeff Dike 已提交
57 58
		if (err)
			return err;
L
Linus Torvalds 已提交
59 60

		err = raw(data->fd);
J
Jeff Dike 已提交
61 62
		if (err)
			return err;
L
Linus Torvalds 已提交
63 64 65
	}
	sprintf(data->str, "%d", data->fd);
	*dev_out = data->str;
J
Jeff Dike 已提交
66
	return data->fd;
L
Linus Torvalds 已提交
67 68 69 70 71 72 73
}

static void fd_close(int fd, void *d)
{
	struct fd_chan *data = d;
	int err;

J
Jeff Dike 已提交
74 75 76 77 78 79 80 81
	if (!data->raw || !isatty(fd))
		return;

	CATCH_EINTR(err = tcsetattr(fd, TCSAFLUSH, &data->tt));
	if (err)
		printk(UM_KERN_ERR "Failed to restore terminal state - "
		       "errno = %d\n", -err);
	data->raw = 0;
L
Linus Torvalds 已提交
82 83
}

J
Jeff Dike 已提交
84
const struct chan_ops fd_ops = {
L
Linus Torvalds 已提交
85 86 87 88 89 90
	.type		= "fd",
	.init		= fd_init,
	.open		= fd_open,
	.close		= fd_close,
	.read		= generic_read,
	.write		= generic_write,
91
	.console_write	= generic_console_write,
L
Linus Torvalds 已提交
92 93 94 95
	.window_size	= generic_window_size,
	.free		= generic_free,
	.winch		= 1,
};