aboutsummaryrefslogtreecommitdiffstats
path: root/Config.in
blob: d7ce63e462c86991787164e4659839677fc62b5e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# Copyright (C) 2006-2007 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#

mainmenu "OpenWrt Configuration"

config HAVE_DOT_CONFIG
	bool
	default y

source "target/Config.in"

menu "Target Images"
	config TARGET_ROOTFS_INITRAMFS
		bool "ramdisk"
		default y if USES_INITRAMFS
		depends LINUX_2_6
		help
		  Embed the rootfs into the kernel (initramfs)

	config TARGET_ROOTFS_JFFS2
		bool "jffs2"
		default y if USES_JFFS2
		depends !TARGET_ROOTFS_INITRAMFS
		help
		  Build a jffs2 root filesystem

	config TARGET_ROOTFS_SQUASHFS
		bool "squashfs"
		default y if USES_SQUASHFS
		depends !TARGET_ROOTFS_INITRAMFS
		help
		  Build a squashfs-lzma root filesystem

	config TARGET_ROOTFS_TGZ
		bool "tgz"
		default y if USES_TGZ
		depends !TARGET_ROOTFS_INITRAMFS
		help
		  Build a compressed tar archive of the the root filesystem
		  
	config TARGET_ROOTFS_CPIOGZ
		bool "cpiogz"
		default y if USES_CPIOGZ
		depends !TARGET_ROOTFS_INITRAMFS
		help
		  Build a compressed cpio archive of the the root filesystem
		  
	config TARGET_ROOTFS_EXT2FS
		bool "ext2"
		default y if USES_EXT2
		depends !TARGET_ROOTFS_INITRAMFS
		help
		  Ext2 file system with some free space for uml images

	config TARGET_ROOTFS_ISO 
		bool "iso" 
		default n 
		depends TARGET_ROOTFS_INITRAMFS && TARGET_x86 
		help 
		  Create some bootable ISO image 

comment "Image Options"

source "target/linux/*/image/Config.in"

    config TARGET_ROOTFS_FSPART
        int "Filesystem part size (in MB)"
        depends X86_GRUB_IMAGES || TARGET_ROOTFS_EXT2FS || TARGET_rb532 || TARGET_olpc
        default 48
        help
            Allows you to change the filesystem partition size

    config TARGET_ROOTFS_MAXINODE
        int "Maximum number of inodes in filesystem"
        depends TARGET_ROOTFS_EXT2FS
        default 6000
        help
            Allows you to change the maximum number of inodes in the filesystem

endmenu

menu "Global build settings"

config ALL
	bool "Select all packages by default"
	default n

comment "General build options"

config CLEAN_IPKG
	bool
	prompt "Disable ipkg/opkg installation on the target"
	default n
	help
		This removes all ipkg data from the target directory before building the root fs

choice
	prompt "Binary stripping method"
	default USE_STRIP   if USE_GLIBC || USE_EGLIBC
	default USE_SSTRIP
	help
	  Select the binary stripping method you wish to use.

	config NO_STRIP
		bool "none"
		help
		  This will install unstripped binaries (useful for native compiling/debugging)

	config USE_STRIP
		bool "strip"
		depends !DEBUG
		help
		  This will install binaries stripped using strip from binutils


	config USE_SSTRIP
		bool "sstrip"
		depends !DEBUG
		depends !USE_GLIBC
		depends !USE_EGLIBC
		help
		  This will install binaries stripped using sstrip

endchoice

comment "Package build options"

config DEBUG
	bool
	prompt "Compile packages with debugging info"
	default n
	help
		Disables stripping and adds -g3 to the CFLAGS

config DEBUG_DIR
	bool "Install debugging binaries into a staging directory"
	default n
	help
		This will install all compiled package binaries into build_dir/target-*/debug-*/,
		useful for cross-debugging via gdb/gdbserver

comment "Kernel build options"

config KERNEL_KALLSYMS
	bool "Compile the kernel with symbol table information"
	default n
	help
		This will give you more information in stack traces from kernel oopses
config KERNEL_PROFILING
	bool "Compile the kernel with profiling enabled"
	default n
	help
		Enable the extended profiling support mechanisms used by profilers such
		as OProfile.

endmenu

menuconfig DEVEL
	bool "Advanced configuration options (for developers)"
	default n
	select TOOLCHAINOPTS if !NATIVE_TOOLCHAIN

config BROKEN
	bool
	prompt "Show broken platforms / packages" if DEVEL
	default n

config DOWNLOAD_FOLDER
	string
	prompt "Download folder" if DEVEL
	default ""

config LOCALMIRROR
	string
	prompt "Local mirror for source packages" if DEVEL

config AUTOREBUILD
	bool
	prompt "Automatic rebuild of packages" if DEVEL
	default y
	help
		Automatically rebuild packages when their files change

config BUILD_SUFFIX
	string
	prompt "Build suffix to append to the BUILD_DIR variable" if DEVEL
	default ""
	help
		Build suffix to append to the BUILD_DIR variable, i.e: build_dir_suffix

config TARGET_ROOTFS_DIR
	string
	prompt "Override the default TARGET_ROOTFS_DIR variable" if DEVEL
	default ""
	help
		Override the default TARGET_ROOTFS_DIR variable content $(BUILD_DIR) with custom path.
		Use this option to re-define the location of the target root file system directory.

config CCACHE
	bool
	prompt "Use ccache" if DEVEL
	default n
	help
		Compiler cache; see http://ccache.samba.org/

config EXTERNAL_KERNEL_TREE
	string
	prompt "Use external kernel tree" if DEVEL
	default ""

config KERNEL_GIT_CLONE_URI
	string
	prompt "Enter git repository to clone" if DEVEL
	default ""
	help
		Enter the full git repository path i.e.:
		git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git
		This will create a git clone of the kernel in your build
		directory.

config KERNEL_GIT_LOCAL_REPOSITORY
	string
	prompt "Enter path to local reference repository" if DEVEL
	default ""
	help
		Enter a full pathname to a local reference git repository.
		In this instance, the --refererence option of git clone will
		be used thus creating a quick local clone of your repo.

source "toolchain/Config.in"

source "target/imagebuilder/Config.in"
source "target/sdk/Config.in"

source "tmp/.config-package.in"
'n763' href='#n763'>763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 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 1273 1274 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 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
#include <stdarg.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <xenctrl.h>
#include <xen/io/xenbus.h>
#include <xen/io/fbif.h>
#include <xen/io/kbdif.h>
#include <xen/io/protocols.h>
#include <stdbool.h>
#include <xen/event_channel.h>
#include <sys/mman.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <xs.h>

#include "xenfb.h"

#ifdef CONFIG_STUBDOM
#include <semaphore.h>
#include <sched.h>
#include <fbfront.h>
#endif

#ifndef BTN_LEFT
#define BTN_LEFT 0x110 /* from <linux/input.h> */
#endif

// FIXME defend against malicious frontend?

struct xenfb;

struct xenfb_device {
	const char *devicetype;
	char nodename[64];	/* backend xenstore dir */
	char otherend[64];	/* frontend xenstore dir */
	int otherend_id;	/* frontend domid */
	enum xenbus_state state; /* backend state */
	void *page;		/* shared page */
	evtchn_port_t port;
	struct xenfb *xenfb;
};

struct xenfb {
	DisplayState *ds;       /* QEMU graphical console state */
	int evt_xch;		/* event channel driver handle */
	int xc;			/* hypervisor interface handle */
	struct xs_handle *xsh;	/* xs daemon handle */
	struct xenfb_device fb, kbd;
	void *pixels;           /* guest framebuffer data */
	size_t fb_len;		/* size of framebuffer */
	int row_stride;         /* width of one row in framebuffer */
	int depth;              /* colour depth of guest framebuffer */
	int width;              /* pixel width of guest framebuffer */
	int height;             /* pixel height of guest framebuffer */
	int abs_pointer_wanted; /* Whether guest supports absolute pointer */
	int button_state;       /* Last seen pointer button state */
	char protocol[64];	/* frontend protocol */
};

/* Functions for frontend/backend state machine*/
static int xenfb_wait_for_frontend(struct xenfb_device *dev, IOHandler *handler);
static int xenfb_wait_for_backend(struct xenfb_device *dev, IOHandler *handler);
static void xenfb_backend_created_kbd(void *opaque);
static void xenfb_backend_created_fb(void *opaque);
static void xenfb_frontend_initialized_kbd(void *opaque);
static void xenfb_frontend_initialized_fb(void *opaque);
static void xenfb_frontend_connected_kbd(void *opaque);

/* Helper functions for checking state of frontend/backend devices */
static int xenfb_frontend_connected(struct xenfb_device *dev);
static int xenfb_frontend_initialized(struct xenfb_device *dev);
static int xenfb_backend_created(struct xenfb_device *dev);

/* Functions which tie the PVFB into the QEMU device model */
static void xenfb_key_event(void *opaque, int keycode);
static void xenfb_mouse_event(void *opaque,
			      int dx, int dy, int dz, int button_state);
static void xenfb_guest_copy(struct xenfb *xenfb, int x, int y, int w, int h);
static void xenfb_update(void *opaque);
static void xenfb_invalidate(void *opaque);
static void xenfb_screen_dump(void *opaque, const char *name);
static int xenfb_register_console(struct xenfb *xenfb);

/*
 * Tables to map from scancode to Linux input layer keycode.
 * Scancodes are hardware-specific.  These maps assumes a 
 * standard AT or PS/2 keyboard which is what QEMU feeds us.
 */
static const unsigned char atkbd_set2_keycode[512] = {

	  0, 67, 65, 63, 61, 59, 60, 88,  0, 68, 66, 64, 62, 15, 41,117,
	  0, 56, 42, 93, 29, 16,  2,  0,  0,  0, 44, 31, 30, 17,  3,  0,
	  0, 46, 45, 32, 18,  5,  4, 95,  0, 57, 47, 33, 20, 19,  6,183,
	  0, 49, 48, 35, 34, 21,  7,184,  0,  0, 50, 36, 22,  8,  9,185,
	  0, 51, 37, 23, 24, 11, 10,  0,  0, 52, 53, 38, 39, 25, 12,  0,
	  0, 89, 40,  0, 26, 13,  0,  0, 58, 54, 28, 27,  0, 43,  0, 85,
	  0, 86, 91, 90, 92,  0, 14, 94,  0, 79,124, 75, 71,121,  0,  0,
	 82, 83, 80, 76, 77, 72,  1, 69, 87, 78, 81, 74, 55, 73, 70, 99,

	  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
	217,100,255,  0, 97,165,  0,  0,156,  0,  0,  0,  0,  0,  0,125,
	173,114,  0,113,  0,  0,  0,126,128,  0,  0,140,  0,  0,  0,127,
	159,  0,115,  0,164,  0,  0,116,158,  0,150,166,  0,  0,  0,142,
	157,  0,  0,  0,  0,  0,  0,  0,155,  0, 98,  0,  0,163,  0,  0,
	226,  0,  0,  0,  0,  0,  0,  0,  0,255, 96,  0,  0,  0,143,  0,
	  0,  0,  0,  0,  0,  0,  0,  0,  0,107,  0,105,102,  0,  0,112,
	110,111,108,112,106,103,  0,119,  0,118,109,  0, 99,104,119,  0,

};

static const unsigned char atkbd_unxlate_table[128] = {

	  0,118, 22, 30, 38, 37, 46, 54, 61, 62, 70, 69, 78, 85,102, 13,
	 21, 29, 36, 45, 44, 53, 60, 67, 68, 77, 84, 91, 90, 20, 28, 27,
	 35, 43, 52, 51, 59, 66, 75, 76, 82, 14, 18, 93, 26, 34, 33, 42,
	 50, 49, 58, 65, 73, 74, 89,124, 17, 41, 88,  5,  6,  4, 12,  3,
	 11,  2, 10,  1,  9,119,126,108,117,125,123,107,115,116,121,105,
	114,122,112,113,127, 96, 97,120,  7, 15, 23, 31, 39, 47, 55, 63,
	 71, 79, 86, 94,  8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 87,111,
	 19, 25, 57, 81, 83, 92, 95, 98, 99,100,101,103,104,106,109,110

};

static unsigned char scancode2linux[512];

static int xenfb_xs_scanf1(struct xs_handle *xsh,
			   const char *dir, const char *node,
			   const char *fmt, void *dest)
{
	char buf[1024];
	char *p;
	int ret;

	if (snprintf(buf, sizeof(buf), "%s/%s", dir, node) >= sizeof(buf)) {
		errno = ENOENT;
		return -1;
        }
	p = xs_read(xsh, XBT_NULL, buf, NULL);
	if (!p) {
		errno = ENOENT;
		return -1;
        }
	ret = sscanf(p, fmt, dest);
	free(p);
	if (ret != 1) {
		errno = EDOM;
		return -1;
        }
	return ret;
}

static int xenfb_xs_printf(struct xs_handle *xsh,
			   const char *dir, const char *node, char *fmt, ...)
{
	va_list ap;
	char key[1024];
	char val[1024];
	int n;

	if (snprintf(key, sizeof(key), "%s/%s", dir, node) >= sizeof(key)) {
		errno = ENOENT;
		return -1;
        }

	va_start(ap, fmt);
	n = vsnprintf(val, sizeof(val), fmt, ap);
	va_end(ap);
	if (n >= sizeof(val)) {
		errno = ENOSPC; /* close enough */
		return -1;
	}

	if (!xs_write(xsh, XBT_NULL, key, val, n))
		return -1;
	return 0;
}

static void xenfb_device_init(struct xenfb_device *dev,
			      const char *type,
			      struct xenfb *xenfb)
{
	dev->devicetype = type;
	dev->otherend_id = -1;
	dev->port = -1;
	dev->xenfb = xenfb;
}

static char *xenfb_path_in_dom(struct xs_handle *xsh,
                               char *buf, size_t size,
                               unsigned domid, const char *fmt, ...)
{
        va_list ap;
        char *domp = xs_get_domain_path(xsh, domid);
        int n;

        if (domp == NULL)
                return NULL;

        n = snprintf(buf, size, "%s/", domp);
        free(domp);
        if (n >= size)
                return NULL;

        va_start(ap, fmt);
        n += vsnprintf(buf + n, size - n, fmt, ap);
        va_end(ap);
        if (n >= size)
                return NULL;

        return buf;
}

static int xenfb_device_set_domain(struct xenfb_device *dev, int domid)
{
        dev->otherend_id = domid;

        if (!xenfb_path_in_dom(dev->xenfb->xsh,
                               dev->otherend, sizeof(dev->otherend),
                               domid, "device/%s/0", dev->devicetype)) {
                errno = ENOENT;
                return -1;
        }
        if (!xenfb_path_in_dom(dev->xenfb->xsh,
                               dev->nodename, sizeof(dev->nodename),
                               0, "backend/%s/%d/0", dev->devicetype, domid)) {
                errno = ENOENT;
                return -1;
        }

        return 0;
}

struct xenfb *xenfb_new(int domid, DisplayState *ds)
{
	struct xenfb *xenfb = qemu_malloc(sizeof(struct xenfb));
	int serrno;
	int i;

	if (xenfb == NULL)
		return NULL;

	/* Prepare scancode mapping table */
	for (i = 0; i < 128; i++) {
		scancode2linux[i] = atkbd_set2_keycode[atkbd_unxlate_table[i]];
		scancode2linux[i | 0x80] = 
			atkbd_set2_keycode[atkbd_unxlate_table[i] | 0x80];
	}

	memset(xenfb, 0, sizeof(*xenfb));
	xenfb->evt_xch = xenfb->xc = -1;
	xenfb_device_init(&xenfb->fb, "vfb", xenfb);
	xenfb_device_init(&xenfb->kbd, "vkbd", xenfb);

	xenfb->evt_xch = xc_evtchn_open();
	if (xenfb->evt_xch == -1)
		goto fail;

	xenfb->xc = xc_interface_open();
	if (xenfb->xc == -1)
		goto fail;

	xenfb->xsh = xs_daemon_open();
	if (!xenfb->xsh)
		goto fail;

	xenfb->ds = ds;
	xenfb_device_set_domain(&xenfb->fb, domid);
	xenfb_device_set_domain(&xenfb->kbd, domid);

	fprintf(stderr, "FB: Waiting for KBD backend creation\n");
	xenfb_wait_for_backend(&xenfb->kbd, xenfb_backend_created_kbd);

	return xenfb;

 fail:
	serrno = errno;
	xenfb_shutdown(xenfb);
	errno = serrno;
	return NULL;
}


static enum xenbus_state xenfb_read_state(struct xs_handle *xsh,
					  const char *dir)
{
	int ret, state;

	ret = xenfb_xs_scanf1(xsh, dir, "state", "%d", &state);
	if (ret < 0)
		return XenbusStateUnknown;

	if ((unsigned)state > XenbusStateClosed)
		state = XenbusStateUnknown;
	return state;
}

static int xenfb_switch_state(struct xenfb_device *dev,
			      enum xenbus_state state)
{
	struct xs_handle *xsh = dev->xenfb->xsh;

	if (xenfb_xs_printf(xsh, dev->nodename, "state", "%d", state) < 0)
		return -1;
	dev->state = state;
	return 0;
}


static int xenfb_hotplug(struct xenfb_device *dev)
{
	if (xenfb_xs_printf(dev->xenfb->xsh, dev->nodename,
			    "hotplug-status", "connected"))
		return -1;
	return 0;
}

static void xenfb_copy_mfns(int mode, int count, unsigned long *dst, void *src)
{
	uint32_t *src32 = src;
	uint64_t *src64 = src;
	int i;

	for (i = 0; i < count; i++)
		dst[i] = (mode == 32) ? src32[i] : src64[i];
}

static int xenfb_map_fb(struct xenfb *xenfb, int domid)
{
	struct xenfb_page *page = xenfb->fb.page;
	int n_fbmfns;
	int n_fbdirs;
	unsigned long *pgmfns = NULL;
	unsigned long *fbmfns = NULL;
	void *map, *pd;
	int mode, ret = -1;

	/* default to native */
	pd = page->pd;
	mode = sizeof(unsigned long) * 8;

	if (0 == strlen(xenfb->protocol)) {
		/*
		 * Undefined protocol, some guesswork needed.
		 *
		 * Old frontends which don't set the protocol use
		 * one page directory only, thus pd[1] must be zero.
		 * pd[1] of the 32bit struct layout and the lower
		 * 32 bits of pd[0] of the 64bit struct layout have
		 * the same location, so we can check that ...
		 */
		uint32_t *ptr32 = NULL;
		uint32_t *ptr64 = NULL;
#if defined(__i386__)
		ptr32 = (void*)page->pd;
		ptr64 = ((void*)page->pd) + 4;
#elif defined(__x86_64__)
		ptr32 = ((void*)page->pd) - 4;
		ptr64 = (void*)page->pd;
#endif
		if (ptr32) {
			if (0 == ptr32[1]) {
				mode = 32;
				pd   = ptr32;
			} else {
				mode = 64;
				pd   = ptr64;
			}
		}
#if defined(__x86_64__)
	} else if (0 == strcmp(xenfb->protocol, XEN_IO_PROTO_ABI_X86_32)) {
		/* 64bit dom0, 32bit domU */
		mode = 32;
		pd   = ((void*)page->pd) - 4;
#elif defined(__i386__)
	} else if (0 == strcmp(xenfb->protocol, XEN_IO_PROTO_ABI_X86_64)) {
		/* 32bit dom0, 64bit domU */
		mode = 64;
		pd   = ((void*)page->pd) + 4;
#endif
	}

	n_fbmfns = (xenfb->fb_len + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE;
	n_fbdirs = n_fbmfns * mode / 8;
	n_fbdirs = (n_fbdirs + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE;

	pgmfns = malloc(sizeof(unsigned long) * n_fbdirs);
	fbmfns = malloc(sizeof(unsigned long) * n_fbmfns);
	if (!pgmfns || !fbmfns)
		goto out;

	xenfb_copy_mfns(mode, n_fbdirs, pgmfns, pd);
	map = xc_map_foreign_pages(xenfb->xc, domid,
				   PROT_READ, pgmfns, n_fbdirs);
	if (map == NULL)
		goto out;
	xenfb_copy_mfns(mode, n_fbmfns, fbmfns, map);
	munmap(map, n_fbdirs * XC_PAGE_SIZE);

	xenfb->pixels = xc_map_foreign_pages(xenfb->xc, domid,
				PROT_READ | PROT_WRITE, fbmfns, n_fbmfns);
	if (xenfb->pixels == NULL)
		goto out;

	ret = 0; /* all is fine */

 out:
	if (pgmfns)
		free(pgmfns);
	if (fbmfns)
		free(fbmfns);
	return ret;
}

static int xenfb_bind(struct xenfb_device *dev)
{
	struct xenfb *xenfb = dev->xenfb;
	unsigned long mfn;
	evtchn_port_t evtchn;

	if (xenfb_xs_scanf1(xenfb->xsh, dev->otherend, "page-ref", "%lu",
			    &mfn) < 0)
		return -1;
	if (xenfb_xs_scanf1(xenfb->xsh, dev->otherend, "event-channel", "%u",
			    &evtchn) < 0)
		return -1;

	dev->port = xc_evtchn_bind_interdomain(xenfb->evt_xch,
					       dev->otherend_id, evtchn);
	if (dev->port == -1)
		return -1;

	dev->page = xc_map_foreign_range(xenfb->xc, dev->otherend_id,
			XC_PAGE_SIZE, PROT_READ | PROT_WRITE, mfn);
	if (dev->page == NULL)
		return -1;

	return 0;
}

static void xenfb_unbind(struct xenfb_device *dev)
{
	if (dev->page) {
		munmap(dev->page, XC_PAGE_SIZE);
		dev->page = NULL;
	}
        if (dev->port >= 0) {
		xc_evtchn_unbind(dev->xenfb->evt_xch, dev->port);
		dev->port = -1;
	}
}


static void xenfb_detach_dom(struct xenfb *xenfb)
{
	xenfb_unbind(&xenfb->fb);
	xenfb_unbind(&xenfb->kbd);
	if (xenfb->pixels) {
		munmap(xenfb->pixels, xenfb->fb_len);
		xenfb->pixels = NULL;
	}
}

/* Remove the backend area in xenbus since the framebuffer really is
   going away. */
void xenfb_shutdown(struct xenfb *xenfb)
{
	fprintf(stderr, "FB: Shutting down backend\n");
	xs_rm(xenfb->xsh, XBT_NULL, xenfb->fb.nodename);
	xs_rm(xenfb->xsh, XBT_NULL, xenfb->kbd.nodename);

	xenfb_detach_dom(xenfb);
	if (xenfb->xc >= 0)
		xc_interface_close(xenfb->xc);
	if (xenfb->evt_xch >= 0)
		xc_evtchn_close(xenfb->evt_xch);
	if (xenfb->xsh)
		xs_daemon_close(xenfb->xsh);
	free(xenfb);
}


static void xenfb_on_fb_event(struct xenfb *xenfb)
{
	uint32_t prod, cons;
	struct xenfb_page *page = xenfb->fb.page;

	prod = page->out_prod;
	if (prod == page->out_cons)
		return;
	xen_rmb();		/* ensure we see ring contents up to prod */
	for (cons = page->out_cons; cons != prod; cons++) {
		union xenfb_out_event *event = &XENFB_OUT_RING_REF(page, cons);
		int x, y, w, h;

		switch (event->type) {
		case XENFB_TYPE_UPDATE:
			x = MAX(event->update.x, 0);
			y = MAX(event->update.y, 0);
			w = MIN(event->update.width, xenfb->width - x);
			h = MIN(event->update.height, xenfb->height - y);
			if (w < 0 || h < 0) {
				fprintf(stderr, "%s bogus update ignored\n",
					xenfb->fb.nodename);
				break;
			}
			if (x != event->update.x || y != event->update.y
			    || w != event->update.width
			    || h != event->update.height) {
				fprintf(stderr, "%s bogus update clipped\n",
					xenfb->fb.nodename);
				break;
			}
			xenfb_guest_copy(xenfb, x, y, w, h);
			break;
		}
	}
	xen_mb();		/* ensure we're done with ring contents */
	page->out_cons = cons;
	xc_evtchn_notify(xenfb->evt_xch, xenfb->fb.port);
}

static void xenfb_on_kbd_event(struct xenfb *xenfb)
{
	struct xenkbd_page *page = xenfb->kbd.page;

	/* We don't understand any keyboard events, so just ignore them. */
	if (page->out_prod == page->out_cons)
		return;
	page->out_cons = page->out_prod;
	xc_evtchn_notify(xenfb->evt_xch, xenfb->kbd.port);
}

static int xenfb_on_state_change(struct xenfb_device *dev)
{
	enum xenbus_state state;

	state = xenfb_read_state(dev->xenfb->xsh, dev->otherend);

	switch (state) {
	case XenbusStateUnknown:
		/* There was an error reading the frontend state.  The
		   domain has probably gone away; in any case, there's
		   not much point in us continuing. */
		return -1;
	case XenbusStateInitialising:
	case XenbusStateInitWait:
	case XenbusStateInitialised:
	case XenbusStateConnected:
		break;
	case XenbusStateClosing:
		xenfb_unbind(dev);
		xenfb_switch_state(dev, state);
		break;
	case XenbusStateClosed:
		xenfb_switch_state(dev, state);
	}
	return 0;
}

/* Send an event to the keyboard frontend driver */
static int xenfb_kbd_event(struct xenfb *xenfb,
			   union xenkbd_in_event *event)
{
	uint32_t prod;
	struct xenkbd_page *page = xenfb->kbd.page;

	if (xenfb->kbd.state != XenbusStateConnected)
		return 0;

	prod = page->in_prod;
	if (prod - page->in_cons == XENKBD_IN_RING_LEN) {
		errno = EAGAIN;
		return -1;
	}

	xen_mb();		/* ensure ring space available */
	XENKBD_IN_RING_REF(page, prod) = *event;
	xen_wmb();		/* ensure ring contents visible */
	page->in_prod = prod + 1;
	return xc_evtchn_notify(xenfb->evt_xch, xenfb->kbd.port);
}

/* Send a keyboard (or mouse button) event */
static int xenfb_send_key(struct xenfb *xenfb, bool down, int keycode)
{
	union xenkbd_in_event event;

	memset(&event, 0, XENKBD_IN_EVENT_SIZE);
	event.type = XENKBD_TYPE_KEY;
	event.key.pressed = down ? 1 : 0;
	event.key.keycode = keycode;

	return xenfb_kbd_event(xenfb, &event);
}

/* Send a relative mouse movement event */
static int xenfb_send_motion(struct xenfb *xenfb,
			     int rel_x, int rel_y, int rel_z)
{
	union xenkbd_in_event event;

	memset(&event, 0, XENKBD_IN_EVENT_SIZE);
	event.type = XENKBD_TYPE_MOTION;
	event.motion.rel_x = rel_x;
	event.motion.rel_y = rel_y;
	event.motion.rel_z = rel_z;

	return xenfb_kbd_event(xenfb, &event);
}

/* Send an absolute mouse movement event */
static int xenfb_send_position(struct xenfb *xenfb,
			       int abs_x, int abs_y, int rel_z)
{
	union xenkbd_in_event event;

	memset(&event, 0, XENKBD_IN_EVENT_SIZE);
	event.type = XENKBD_TYPE_POS;
	event.pos.abs_x = abs_x;
	event.pos.abs_y = abs_y;
	event.pos.rel_z = rel_z;

	return xenfb_kbd_event(xenfb, &event);
}

/* Process events from the frontend event channel */
static void xenfb_dispatch_channel(void *opaque)
{
	struct xenfb *xenfb = (struct xenfb *)opaque;
	evtchn_port_t port;
	port = xc_evtchn_pending(xenfb->evt_xch);
	if (port == -1) {
		xenfb_shutdown(xenfb);
		exit(1);
	}

	if (port == xenfb->fb.port)
		xenfb_on_fb_event(xenfb);
	else if (port == xenfb->kbd.port)
		xenfb_on_kbd_event(xenfb);

	if (xc_evtchn_unmask(xenfb->evt_xch, port) == -1) {
		xenfb_shutdown(xenfb);
		exit(1);
	}
}

/* Process ongoing events from the frontend devices */
static void xenfb_dispatch_store(void *opaque)
{
	struct xenfb *xenfb = (struct xenfb *)opaque;
	unsigned dummy;
	char **vec;
	int r;

	vec = xs_read_watch(xenfb->xsh, &dummy);
	free(vec);
	r = xenfb_on_state_change(&xenfb->fb);
	if (r == 0)
		r = xenfb_on_state_change(&xenfb->kbd);
	if (r < 0) {
		xenfb_shutdown(xenfb);
		exit(1);
	}
}


/****************************************************************
 *
 * Functions for processing frontend config
 *
 ****************************************************************/


/* Process the frontend framebuffer config */
static int xenfb_read_frontend_fb_config(struct xenfb *xenfb) {
	struct xenfb_page *fb_page;
	int val;

        if (xenfb_xs_scanf1(xenfb->xsh, xenfb->fb.otherend, "feature-update",
                            "%d", &val) < 0)
                val = 0;
        if (!val) {
                fprintf(stderr, "feature-update not supported\n");
                errno = ENOTSUP;
                return -1;
        }
        if (xenfb_xs_scanf1(xenfb->xsh, xenfb->fb.otherend, "protocol", "%63s",
                            xenfb->protocol) < 0)
                xenfb->protocol[0] = '\0';
        xenfb_xs_printf(xenfb->xsh, xenfb->fb.nodename, "request-update", "1");

        /* TODO check for permitted ranges */
        fb_page = xenfb->fb.page;
        xenfb->depth = fb_page->depth;
        xenfb->width = fb_page->width;
        xenfb->height = fb_page->height;
        /* TODO check for consistency with the above */
        xenfb->fb_len = fb_page->mem_length;
        xenfb->row_stride = fb_page->line_length;
        fprintf(stderr, "Framebuffer depth %d width %d height %d line %d\n",
                fb_page->depth, fb_page->width, fb_page->height, fb_page->line_length);
        if (xenfb_map_fb(xenfb, xenfb->fb.otherend_id) < 0)
		return -1;

        if (xenfb_switch_state(&xenfb->fb, XenbusStateConnected))
                return -1;
        if (xenfb_switch_state(&xenfb->kbd, XenbusStateConnected))
                return -1;

	return 0;
}

/* Process the frontend keyboard config */
static int xenfb_read_frontend_kbd_config(struct xenfb *xenfb)
{
	int val;

	if (xenfb_xs_scanf1(xenfb->xsh, xenfb->kbd.otherend, "request-abs-pointer",
			    "%d", &val) < 0)
		val = 0;
	xenfb->abs_pointer_wanted = val;

	return 0;
}


/****************************************************************
 *
 * Functions for frontend/backend state machine
 *
 ****************************************************************/

/* Register a watch against a frontend device, and setup
 * QEMU event loop to poll the xenstore FD for notification */
static int xenfb_wait_for_frontend(struct xenfb_device *dev, IOHandler *handler)
{
        fprintf(stderr, "Doing frontend watch on %s\n", dev->otherend);
	if (!xs_watch(dev->xenfb->xsh, dev->otherend, "")) {
		fprintf(stderr, "Watch for dev failed\n");
		return -1;
	}

	if (qemu_set_fd_handler2(xs_fileno(dev->xenfb->xsh), NULL, handler, NULL, dev) < 0)
		return -1;

	return 0;
}

/* Register a watch against a backend device, and setup
 * QEMU event loop to poll the xenstore FD for notification */
static int xenfb_wait_for_backend(struct xenfb_device *dev, IOHandler *handler)
{
	fprintf(stderr, "Doing backend watch on %s\n", dev->nodename);
	if (!xs_watch(dev->xenfb->xsh, dev->nodename, "")) {
		fprintf(stderr, "Watch for dev failed\n");
		return -1;
	}

	if (qemu_set_fd_handler2(xs_fileno(dev->xenfb->xsh), NULL, handler, NULL, dev) < 0)
		return -1;

	return 0;
}

/* Callback invoked while waiting for KBD backend to change
 * to the created state */
static void xenfb_backend_created_kbd(void *opaque)
{
	struct xenfb_device *dev = (struct xenfb_device *)opaque;
	int ret = xenfb_backend_created(dev);
	if (ret < 0) {
		xenfb_shutdown(dev->xenfb);
		exit(1);
	}
	if (ret)
		return; /* Still waiting */

	if (xenfb_xs_printf(dev->xenfb->xsh, dev->nodename, "feature-abs-pointer", "1")) {
		xenfb_shutdown(dev->xenfb);
		exit(1);
	}

	fprintf(stderr, "FB: Waiting for FB backend creation\n");
	xenfb_wait_for_backend(&dev->xenfb->fb, xenfb_backend_created_fb);
}

/* Callback invoked while waiting for FB backend to change
 * to the created state */
static void xenfb_backend_created_fb(void *opaque)
{
	struct xenfb_device *dev = (struct xenfb_device *)opaque;
	int ret = xenfb_backend_created(dev);
	if (ret < 0) {
		xenfb_shutdown(dev->xenfb);
		exit(1);
	}
	if (ret)
		return; /* Still waiting */

	fprintf(stderr, "FB: Waiting for KBD frontend initialization\n");
	xenfb_wait_for_frontend(&dev->xenfb->kbd, xenfb_frontend_initialized_kbd);
}

/* Callback invoked while waiting for KBD frontend to change
 * to the initialized state */
static void xenfb_frontend_initialized_kbd(void *opaque)
{
	struct xenfb_device *dev = (struct xenfb_device *)opaque;
	int ret = xenfb_frontend_initialized(dev);
	if (ret < 0) {
		xenfb_shutdown(dev->xenfb);
		exit(1);
	}
	if (ret)
		return; /* Still waiting */


        fprintf(stderr, "FB: Waiting for FB frontend initialization\n");
	xenfb_wait_for_frontend(&dev->xenfb->fb, xenfb_frontend_initialized_fb);
}

/* Callback invoked while waiting for FB frontend to change
 * to the initialized state */
static void xenfb_frontend_initialized_fb(void *opaque)
{
	struct xenfb_device *dev = (struct xenfb_device *)opaque;
	int ret = xenfb_frontend_initialized(dev);
	if (ret < 0) {
		xenfb_shutdown(dev->xenfb);
		exit(1);
	}
	if (ret)
		return; /* Still waiting */


	if (xenfb_read_frontend_fb_config(dev->xenfb)) {
		xenfb_shutdown(dev->xenfb);
	        exit(1);
	}

        fprintf(stderr, "FB: Waiting for KBD frontend connection\n");
	xenfb_wait_for_frontend(&dev->xenfb->kbd, xenfb_frontend_connected_kbd);
}

/* Callback invoked while waiting for KBD frontend to change
 * to the connected state */
static void xenfb_frontend_connected_kbd(void *opaque)
{
	struct xenfb_device *dev = (struct xenfb_device *)opaque;
	int ret = xenfb_frontend_connected(dev);
	if (ret < 0) {
		xenfb_shutdown(dev->xenfb);
		exit(1);
	}
	if (ret)
		return; /* Still waiting */

	if (xenfb_read_frontend_kbd_config(dev->xenfb) < 0) {
		xenfb_shutdown(dev->xenfb);
	        exit(1);
	}

	xenfb_register_console(dev->xenfb);
}


/****************************************************************
 *
 * Helper functions for checking state of frontend/backend devices
 *
 ****************************************************************/

/* Helper to determine if a frontend device is in Connected state */
static int xenfb_frontend_connected(struct xenfb_device *dev)
{
	unsigned int state;
	unsigned int dummy;
	char **vec;
	vec = xs_read_watch(dev->xenfb->xsh, &dummy);
	if (!vec)
		return -1;
	free(vec);

	state = xenfb_read_state(dev->xenfb->xsh, dev->otherend);
	if (!((1 <<state) & ((1 << XenbusStateUnknown) |
			     (1 << XenbusStateConnected)))) {
		fprintf(stderr, "FB: Carry on waiting\n");
		return 1;
	}

	/* Don't unwatch frontend - we need to detect shutdown */
	/*xs_unwatch(dev->xenfb->xsh, dev->otherend, "");*/

	switch (state) {
	case XenbusStateConnected:
		break;
	default:
		return -1;
	}
	return 0;
}


/* Helper to determine if a frontend device is in Initialized state */
static int xenfb_frontend_initialized(struct xenfb_device *dev)
{
	unsigned int state;
	unsigned int dummy;
	char **vec;
	vec = xs_read_watch(dev->xenfb->xsh, &dummy);
	if (!vec)
		return -1;
	free(vec);

	state = xenfb_read_state(dev->xenfb->xsh, dev->otherend);

	if (!((1 << state) & ((1 << XenbusStateUnknown)
			      | (1 << XenbusStateInitialised)
#if 1 /* TODO fudging state to permit restarting; to be removed */
			      | (1 << XenbusStateConnected)
#endif
			      ))) {
		fprintf(stderr, "FB: Carry on waiting\n");
		return 1;
	}

	xs_unwatch(dev->xenfb->xsh, dev->otherend, "");

	switch (state) {
#if 1
	case XenbusStateConnected:
                printf("Fudging state to %d\n", XenbusStateInitialised); /* FIXME */
#endif
        case XenbusStateInitialised:
                break;
        default:
                return -1;
        }

	if (xenfb_bind(dev) < 0)
		return -1;

	return 0;
}

/* Helper to determine if a backend device is in Created state */
static int xenfb_backend_created(struct xenfb_device *dev)
{
	unsigned int state;
	unsigned int dummy;
	char **vec;
	vec = xs_read_watch(dev->xenfb->xsh, &dummy);
	if (!vec)
		return -1;
	free(vec);

	state = xenfb_read_state(dev->xenfb->xsh, dev->nodename);

	if (!((1 <<state) & ((1 << XenbusStateUnknown)
			     | (1 << XenbusStateInitialising)
			     | (1 << XenbusStateClosed)
#if 1 /* TODO fudging state to permit restarting; to be removed */
			     | (1 << XenbusStateInitWait)
			     | (1 << XenbusStateConnected)
			     | (1 << XenbusStateClosing)
#endif
			     ))) {
		fprintf(stderr, "FB: Carry on waiting\n");
		return 1;
	}

	xs_unwatch(dev->xenfb->xsh, dev->nodename, "");

        switch (state) {
#if 1
        case XenbusStateInitWait:
        case XenbusStateConnected:
                printf("Fudging state to %d\n", XenbusStateInitialising); /* FIXME */
#endif
        case XenbusStateInitialising:
        case XenbusStateClosing:
        case XenbusStateClosed:
                break;
        default:
                fprintf(stderr, "Wrong state %d\n", state);
                return -1;
        }
        xenfb_switch_state(dev, XenbusStateInitWait);
        if (xenfb_hotplug(dev) < 0)
                return -1;

        return 0;
}


/****************************************************************
 * 
 * QEMU device model integration functions
 *
 ****************************************************************/

/* 
 * Send a key event from the client to the guest OS
 * QEMU gives us a raw scancode from an AT / PS/2 style keyboard.
 * We have to turn this into a Linux Input layer keycode.
 * 
 * Extra complexity from the fact that with extended scancodes 
 * (like those produced by arrow keys) this method gets called
 * twice, but we only want to send a single event. So we have to
 * track the '0xe0' scancode state & collapse the extended keys
 * as needed.
 * 
 * Wish we could just send scancodes straight to the guest which
 * already has code for dealing with this...
 */
static void xenfb_key_event(void *opaque, int scancode)
{
    static int extended = 0;
    int down = 1;
    if (scancode == 0xe0) {
        extended = 1;
        return;
    } else if (scancode & 0x80) {
        scancode &= 0x7f;
        down = 0;
    }
    if (extended) {
        scancode |= 0x80;
        extended = 0;
    }
    xenfb_send_key(opaque, down, scancode2linux[scancode]);
}

/*
 * Send a mouse event from the client to the guest OS
 * 
 * The QEMU mouse can be in either relative, or absolute mode.
 * Movement is sent separately from button state, which has to
 * be encoded as virtual key events. We also don't actually get
 * given any button up/down events, so have to track changes in
 * the button state.
 */
static void xenfb_mouse_event(void *opaque,
			      int dx, int dy, int dz, int button_state)
{
    int i;
    struct xenfb *xenfb = opaque;
    if (xenfb->abs_pointer_wanted)
	    xenfb_send_position(xenfb,
				dx * xenfb->ds->width / 0x7fff,
				dy * xenfb->ds->height / 0x7fff,
				dz);
    else
	    xenfb_send_motion(xenfb, dx, dy, dz);

    for (i = 0 ; i < 8 ; i++) {
	    int lastDown = xenfb->button_state & (1 << i);
	    int down = button_state & (1 << i);
	    if (down == lastDown)
		    continue;

	    if (xenfb_send_key(xenfb, down, BTN_LEFT+i) < 0)
		    return;
    }
    xenfb->button_state = button_state;
}

/* A convenient function for munging pixels between different depths */
#define BLT(SRC_T,DST_T,RLS,GLS,BLS,RRS,GRS,BRS,RM,GM,BM)               \
    for (line = y ; line < h ; line++) {                                \
        SRC_T *src = (SRC_T *)(xenfb->pixels                            \
                               + (line * xenfb->row_stride)             \
                               + (x * xenfb->depth / 8));               \
        DST_T *dst = (DST_T *)(xenfb->ds->data                                 \
                               + (line * xenfb->ds->linesize)                  \
                               + (x * xenfb->ds->depth / 8));                  \
        int col;                                                        \
        for (col = x ; col < w ; col++) {                               \
            *dst = (((*src >> RRS) & RM) << RLS) |                      \
                (((*src >> GRS) & GM) << GLS) |                         \
                (((*src >> GRS) & BM) << BLS);                          \
            src++;                                                      \
            dst++;                                                      \
        }                                                               \
    }


/* This copies data from the guest framebuffer region, into QEMU's copy
 * NB. QEMU's copy is stored in the pixel format of a) the local X 
 * server (SDL case) or b) the current VNC client pixel format.
 * When shifting between colour depths we preserve the MSB.
 */
static void xenfb_guest_copy(struct xenfb *xenfb, int x, int y, int w, int h)
{
    int line;

    if (xenfb->depth == xenfb->ds->depth) { /* Perfect match can use fast path */
        for (line = y ; line < (y+h) ; line++) {
            memcpy(xenfb->ds->data + (line * xenfb->ds->linesize) + (x * xenfb->ds->depth / 8),
                   xenfb->pixels + (line * xenfb->row_stride) + (x * xenfb->depth / 8),
                   w * xenfb->depth / 8);
        }
    } else { /* Mismatch requires slow pixel munging */
        if (xenfb->depth == 8) {
            /* 8 bit source == r:3 g:3 b:2 */
            if (xenfb->ds->depth == 16) {
                BLT(uint8_t, uint16_t,   5, 2, 0,   11, 5, 0,   7, 7, 3);
            } else if (xenfb->ds->depth == 32) {
                BLT(uint8_t, uint32_t,   5, 2, 0,   16, 8, 0,   7, 7, 3);
            }
        } else if (xenfb->depth == 16) {
            /* 16 bit source == r:5 g:6 b:5 */
            if (xenfb->ds->depth == 8) {
                BLT(uint16_t, uint8_t,    11, 5, 0,   5, 2, 0,    31, 63, 31);
            } else if (xenfb->ds->depth == 32) {
                BLT(uint16_t, uint32_t,   11, 5, 0,   16, 8, 0,   31, 63, 31);
            }
        } else if (xenfb->depth == 32) {
            /* 32 bit source == r:8 g:8 b:8 (padding:8) */
            if (xenfb->ds->depth == 8) {
                BLT(uint32_t, uint8_t,    16, 8, 0,   5, 2, 0,    255, 255, 255);
            } else if (xenfb->ds->depth == 16) {
                BLT(uint32_t, uint16_t,   16, 8, 0,   11, 5, 0,   255, 255, 255);
            }
        }
    }
    dpy_update(xenfb->ds, x, y, w, h);
}

/* Periodic update of display, no need for any in our case */
static void xenfb_update(void *opaque)
{
    struct xenfb *xenfb = opaque;
}

/* QEMU display state changed, so refresh the framebuffer copy */
static void xenfb_invalidate(void *opaque)
{
    struct xenfb *xenfb = opaque;
    xenfb_guest_copy(xenfb, 0, 0, xenfb->width, xenfb->height);
}

/* Screen dump is not used in Xen, so no need to impl this....yet */
static void xenfb_screen_dump(void *opaque, const char *name) { }


/* Register a QEMU graphical console, and key/mouse handler,
 * connecting up their events to the frontend */
static int xenfb_register_console(struct xenfb *xenfb) {
	/* Register our keyboard & mouse handlers */
	qemu_add_kbd_event_handler(xenfb_key_event, xenfb);
	qemu_add_mouse_event_handler(xenfb_mouse_event, xenfb,
  				     xenfb->abs_pointer_wanted,
  				     "Xen PVFB Mouse");
  
  	/* Tell QEMU to allocate a graphical console */
	graphic_console_init(xenfb->ds,
			     xenfb_update,
			     xenfb_invalidate,
			     xenfb_screen_dump,
			     xenfb);
	dpy_resize(xenfb->ds, xenfb->width, xenfb->height);

	if (qemu_set_fd_handler2(xc_evtchn_fd(xenfb->evt_xch), NULL, xenfb_dispatch_channel, NULL, xenfb) < 0)
	        return -1;
	if (qemu_set_fd_handler2(xs_fileno(xenfb->xsh), NULL, xenfb_dispatch_store, NULL, xenfb) < 0)
		return -1;

        fprintf(stderr, "Xen Framebuffer registered\n");
        return 0;
}

#ifdef CONFIG_STUBDOM
static struct semaphore kbd_sem = __SEMAPHORE_INITIALIZER(kbd_sem, 0);
static struct kbdfront_dev *kbd_dev;
static char *kbd_path, *fb_path;

static unsigned char linux2scancode[KEY_MAX + 1];

#define WIDTH 1024
#define HEIGHT 768
#define DEPTH 32
#define LINESIZE (1280 * (DEPTH / 8))
#define MEMSIZE (LINESIZE * HEIGHT)

int xenfb_connect_vkbd(const char *path)
{
    kbd_path = strdup(path);
    return 0;
}

int xenfb_connect_vfb(const char *path)
{
    fb_path = strdup(path);
    return 0;
}

static void xenfb_pv_update(DisplayState *s, int x, int y, int w, int h)
{
    struct fbfront_dev *fb_dev = s->opaque;
    fbfront_update(fb_dev, x, y, w, h);
}

static void xenfb_pv_resize(DisplayState *s, int w, int h)
{
    struct fbfront_dev *fb_dev = s->opaque;
    fprintf(stderr,"resize to %dx%d required\n", w, h);
    s->width = w;
    s->height = h;
    /* TODO: send resize event if supported */
    memset(s->data, 0, MEMSIZE);
    fbfront_update(fb_dev, 0, 0, WIDTH, HEIGHT);
}

static void xenfb_pv_colourdepth(DisplayState *s, int depth)
{
    /* TODO: send redepth event if supported */
    fprintf(stderr,"redepth to %d required\n", depth);
}

static void xenfb_kbd_handler(void *opaque)
{
#define KBD_NUM_BATCH 64
    union xenkbd_in_event buf[KBD_NUM_BATCH];
    int n, i;
    DisplayState *s = opaque;
    static int buttons;
    static int x, y;

    n = kbdfront_receive(kbd_dev, buf, KBD_NUM_BATCH);
    for (i = 0; i < n; i++) {
        switch (buf[i].type) {

            case XENKBD_TYPE_MOTION:
                fprintf(stderr, "FB backend sent us relative mouse motion event!\n");
                break;

            case XENKBD_TYPE_POS:
            {
                int new_x = buf[i].pos.abs_x;
                int new_y = buf[i].pos.abs_y;
                if (new_x >= s->width)
                    new_x = s->width - 1;
                if (new_y >= s->height)
                    new_y = s->height - 1;
                if (kbd_mouse_is_absolute()) {
                    kbd_mouse_event(
                            new_x * 0x7FFF / (s->width - 1),
                            new_y * 0x7FFF / (s->height - 1),
                            buf[i].pos.rel_z,
                            buttons);
                } else {
                    kbd_mouse_event(
                            new_x - x,
                            new_y - y,
                            buf[i].pos.rel_z,
                            buttons);
                }
                x = new_x;
                y = new_y;
                break;
            }

            case XENKBD_TYPE_KEY:
            {
                int keycode = buf[i].key.keycode;
                int button = 0;

                if (keycode == BTN_LEFT)
                    button = MOUSE_EVENT_LBUTTON;
                else if (keycode == BTN_RIGHT)
                    button = MOUSE_EVENT_RBUTTON;
                else if (keycode == BTN_MIDDLE)
                    button = MOUSE_EVENT_MBUTTON;

                if (button) {
                    if (buf[i].key.pressed)
                        buttons |=  button;
                    else
                        buttons &= ~button;
                    if (kbd_mouse_is_absolute())
                        kbd_mouse_event(
                                x * 0x7FFF / s->width,
                                y * 0x7FFF / s->height,
                                0,
                                buttons);
                    else
                        kbd_mouse_event(0, 0, 0, buttons);
                } else {
                    int scancode = linux2scancode[keycode];
                    if (!scancode) {
                        fprintf(stderr, "Can't convert keycode %x to scancode\n", keycode);
                        break;
                    }
                    if (scancode & 0x80) {
                        kbd_put_keycode(0xe0);
                        scancode &= 0x7f;
                    }
                    if (!buf[i].key.pressed)
                        scancode |= 0x80;
                    kbd_put_keycode(scancode);
                }
                break;
            }
        }
    }
}

static void xenfb_pv_refresh(DisplayState *ds)
{
    vga_hw_update();
}

static void kbdfront_thread(void *p)
{
    int scancode, keycode;
    kbd_dev = init_kbdfront(p, 1);
    if (!kbd_dev) {
        fprintf(stderr,"can't open keyboard\n");
        exit(1);
    }
    up(&kbd_sem);
    for (scancode = 0; scancode < 128; scancode++) {
        keycode = atkbd_set2_keycode[atkbd_unxlate_table[scancode]];
        linux2scancode[keycode] = scancode;
        keycode = atkbd_set2_keycode[atkbd_unxlate_table[scancode] | 0x80];
        linux2scancode[keycode] = scancode | 0x80;
    }
}

int xenfb_pv_display_init(DisplayState *ds)
{
    void *data;
    struct fbfront_dev *fb_dev;
    int kbd_fd;

    if (!fb_path || !kbd_path)
        return -1;

    create_thread("kbdfront", kbdfront_thread, (void*) kbd_path);

    data = qemu_memalign(PAGE_SIZE, VGA_RAM_SIZE);
    fb_dev = init_fbfront(fb_path, data, WIDTH, HEIGHT, DEPTH, LINESIZE, MEMSIZE);
    if (!fb_dev) {
        fprintf(stderr,"can't open frame buffer\n");
        exit(1);
    }
    free(fb_path);

    down(&kbd_sem);
    free(kbd_path);

    kbd_fd = kbdfront_open(kbd_dev);
    qemu_set_fd_handler(kbd_fd, xenfb_kbd_handler, NULL, ds);

    ds->data = data;
    ds->linesize = LINESIZE;
    ds->depth = DEPTH;
    ds->bgr = 0;
    ds->width = WIDTH;
    ds->height = HEIGHT;
    ds->dpy_update = xenfb_pv_update;
    ds->dpy_resize = xenfb_pv_resize;
    ds->dpy_colourdepth = NULL; //xenfb_pv_colourdepth;
    ds->dpy_refresh = xenfb_pv_refresh;
    ds->opaque = fb_dev;
    return 0;
}
#endif

/*
 * Local variables:
 *  c-indent-level: 8
 *  c-basic-offset: 8
 *  tab-width: 8
 * End:
 */