Merge remote-tracking branch 'remotes/kraxel/tags/pull-gtk-20140611-1' into staging

gtk: misc fixes & cleanups.

# gpg: Signature made Wed 11 Jun 2014 13:28:12 BST using RSA key ID D3E87138
# gpg: Good signature from "Gerd Hoffmann (work) <kraxel@redhat.com>"
# gpg:                 aka "Gerd Hoffmann <gerd@kraxel.org>"
# gpg:                 aka "Gerd Hoffmann (private) <kraxel@gmail.com>"

* remotes/kraxel/tags/pull-gtk-20140611-1:
  gtk: update window size after showing/hiding tabs
  gtk: factor out gtk3 grab into the new gd_grab_devices function
  gtk: cleanup backend dependencies
  gtk: factor out keycode mapping

Signed-off-by: Peter Maydell <peter.maydell@linaro.org>
diff --git a/Makefile.target b/Makefile.target
index 8155496..4223283 100644
--- a/Makefile.target
+++ b/Makefile.target
@@ -102,7 +102,8 @@
 
 ifdef CONFIG_BSD_USER
 
-QEMU_CFLAGS+=-I$(SRC_PATH)/bsd-user -I$(SRC_PATH)/bsd-user/$(TARGET_ABI_DIR)
+QEMU_CFLAGS+=-I$(SRC_PATH)/bsd-user -I$(SRC_PATH)/bsd-user/$(TARGET_ABI_DIR) \
+			 -I$(SRC_PATH)/bsd-user/$(HOST_VARIANT_DIR)
 
 obj-y += bsd-user/
 obj-y += gdbstub.o user-exec.o
diff --git a/bsd-user/freebsd/strace.list b/bsd-user/freebsd/strace.list
index 1edf412..2800a2d 100644
--- a/bsd-user/freebsd/strace.list
+++ b/bsd-user/freebsd/strace.list
@@ -1,7 +1,37 @@
-{ TARGET_FREEBSD_NR___getcwd, "__getcwd", NULL, NULL, NULL },
+/*
+ *  FreeBSD strace list
+ *
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+{ TARGET_FREEBSD_NR___acl_aclcheck_fd, "__acl_aclcheck_fd", "%s(%d, %d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_aclcheck_file, "__acl_aclcheck_file", "%s(\"%s\", %d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_aclcheck_link, "__acl_aclcheck_link", "%s(\"%s\", %d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_delete_fd, "__acl_delete_fd", "%s(%d, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_delete_file, "__acl_delete_file", "%s(\"%s\", %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_delete_link, "__acl_delete_link", "%s(\"%s\", %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_get_fd, "__acl_get_fd", "%s(%d, %d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_get_file, "__acl_get_file", "%s(\"%s\", %d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_get_link, "__acl_get_link", "%s(\"%s\", %d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_set_fd, "__acl_set_fd", "%s(%d, %d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_set_file, "__acl_set_file", "%s(\"%s\", %d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR___acl_set_link, "__acl_set_link", "%s(\"%s\", %d, %#x)", NULL, NULL },
 { TARGET_FREEBSD_NR___semctl, "__semctl", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR___syscall, "__syscall", NULL, NULL, NULL },
-{ TARGET_FREEBSD_NR___sysctl, "__sysctl", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR___sysctl, "__sysctl", NULL, print_sysctl, NULL },
+{ TARGET_FREEBSD_NR__umtx_op, "_umtx_op", "%s(%#x, %d, %d, %#x, %#x)", NULL, NULL },
 { TARGET_FREEBSD_NR_accept, "accept", "%s(%d,%#x,%#x)", NULL, NULL },
 { TARGET_FREEBSD_NR_access, "access", "%s(\"%s\",%#o)", NULL, NULL },
 { TARGET_FREEBSD_NR_acct, "acct", NULL, NULL, NULL },
@@ -20,24 +50,41 @@
 { TARGET_FREEBSD_NR_connect, "connect", "%s(%d,%#x,%d)", NULL, NULL },
 { TARGET_FREEBSD_NR_dup, "dup", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_dup2, "dup2", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_eaccess, "eaccess", "%s(\"%s\",%#x)", NULL, NULL },
 { TARGET_FREEBSD_NR_execve, "execve", NULL, print_execve, NULL },
 { TARGET_FREEBSD_NR_exit, "exit", "%s(%d)\n", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattrctl, "extattrctl", "%s(\"%s\", %d, \"%s\", %d, \"%s\"", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_delete_fd, "extattr_delete_fd", "%s(%d, %d, \"%s\")", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_delete_file, "extattr_delete_file", "%s(\"%s\", %d, \"%s\")", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_delete_link, "extattr_delete_link", "%s(\"%s\", %d, \"%s\")", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_get_fd, "extattr_get_fd", "%s(%d, %d, \"%s\", %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_get_file, "extattr_get_file", "%s(\"%s\", %d, \"%s\", %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_get_file, "extattr_get_link", "%s(\"%s\", %d, \"%s\", %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_list_fd, "extattr_list_fd", "%s(%d, %d, %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_list_file, "extattr_list_file", "%s(\"%s\", %d, %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_list_link, "extattr_list_link", "%s(\"%s\", %d, %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_set_fd, "extattr_set_fd", "%s(%d, %d, \"%s\", %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_set_file, "extattr_set_file", "%s(\"%s\", %d, \"%s\", %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_extattr_set_link, "extattr_set_link", "%s(\"%s\", %d, \"%s\", %#x, %d)", NULL, NULL },
 { TARGET_FREEBSD_NR_fchdir, "fchdir", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_fchflags, "fchflags", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_fchmod, "fchmod", "%s(%d,%#o)", NULL, NULL },
-{ TARGET_FREEBSD_NR_fchown, "fchown", "%s(\"%s\",%d,%d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_fchown, "fchown", "%s(%d,%d,%d)", NULL, NULL },
 { TARGET_FREEBSD_NR_fcntl, "fcntl", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_fexecve, "fexecve", NULL, print_execve, NULL },
 { TARGET_FREEBSD_NR_fhopen, "fhopen", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_fhstat, "fhstat", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_fhstatfs, "fhstatfs", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_flock, "flock", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_fork, "fork", "%s()", NULL, NULL },
 { TARGET_FREEBSD_NR_fpathconf, "fpathconf", NULL, NULL, NULL },
-{ TARGET_FREEBSD_NR_fstat, "fstat", "%s(%d,%p)", NULL, NULL },
-{ TARGET_FREEBSD_NR_fstatfs, "fstatfs", "%s(%d,%p)", NULL, NULL },
+{ TARGET_FREEBSD_NR_fstat, "fstat", "%s(%d,%#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR_fstatat, "fstatat", "%s(%d,\"%s\", %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_fstatfs, "fstatfs", "%s(%d,%#x)", NULL, NULL },
 { TARGET_FREEBSD_NR_fsync, "fsync", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_ftruncate, "ftruncate", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_futimes, "futimes", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_getcontext, "getcontext", "%s(%#x)", NULL, NULL },
 { TARGET_FREEBSD_NR_getdirentries, "getdirentries", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_freebsd6_mmap, "freebsd6_mmap", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_getegid, "getegid", "%s()", NULL, NULL },
@@ -63,7 +110,7 @@
 { TARGET_FREEBSD_NR_getsockopt, "getsockopt", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_gettimeofday, "gettimeofday", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_getuid, "getuid", "%s()", NULL, NULL },
-{ TARGET_FREEBSD_NR_ioctl, "ioctl", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_ioctl, "ioctl", NULL, print_ioctl, NULL },
 { TARGET_FREEBSD_NR_issetugid, "issetugid", "%s()", NULL, NULL },
 { TARGET_FREEBSD_NR_kevent, "kevent", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_kill, "kill", NULL, NULL, NULL },
@@ -72,6 +119,7 @@
 { TARGET_FREEBSD_NR_lchown, "lchown", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_link, "link", "%s(\"%s\",\"%s\")", NULL, NULL },
 { TARGET_FREEBSD_NR_listen, "listen", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_lpathconf, "lpathconf", "%s(\"%s\", %d)", NULL, NULL },
 { TARGET_FREEBSD_NR_lseek, "lseek", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_lstat, "lstat", "%s(\"%s\",%p)", NULL, NULL },
 { TARGET_FREEBSD_NR_madvise, "madvise", NULL, NULL, NULL },
@@ -96,7 +144,8 @@
 { TARGET_FREEBSD_NR_nanosleep, "nanosleep", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_nfssvc, "nfssvc", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_open, "open", "%s(\"%s\",%#x,%#o)", NULL, NULL },
-{ TARGET_FREEBSD_NR_pathconf, "pathconf", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_openat, "openat", "%s(%d, \"%s\",%#x,%#o)", NULL, NULL },
+{ TARGET_FREEBSD_NR_pathconf, "pathconf", "%s(\"%s\", %d)", NULL, NULL },
 { TARGET_FREEBSD_NR_pipe, "pipe", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_poll, "poll", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_pread, "pread", NULL, NULL, NULL },
@@ -116,6 +165,7 @@
 { TARGET_FREEBSD_NR_revoke, "revoke", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_rfork, "rfork", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_rmdir, "rmdir", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_rtprio_thread, "rtprio_thread", "%s(%d, %d, %p)", NULL, NULL },
 { TARGET_FREEBSD_NR_sbrk, "sbrk", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_sched_yield, "sched_yield", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_select, "select", NULL, NULL, NULL },
@@ -123,6 +173,7 @@
 { TARGET_FREEBSD_NR_semop, "semop", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_sendmsg, "sendmsg", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_sendto, "sendto", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_setcontext, "setcontext", "%s(%#x)", NULL, NULL },
 { TARGET_FREEBSD_NR_setegid, "setegid", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_seteuid, "seteuid", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_setgid, "setgid", NULL, NULL, NULL },
@@ -151,7 +202,7 @@
 { TARGET_FREEBSD_NR_sigprocmask, "sigprocmask", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_sigreturn, "sigreturn", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_sigsuspend, "sigsuspend", NULL, NULL, NULL },
-{ TARGET_FREEBSD_NR_socket, "socket", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_socket, "socket", "%s(%d,%d,%d)", NULL, NULL },
 { TARGET_FREEBSD_NR_socketpair, "socketpair", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_sstk, "sstk", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_stat, "stat", "%s(\"%s\",%p)", NULL, NULL },
@@ -160,6 +211,15 @@
 { TARGET_FREEBSD_NR_sync, "sync", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_sysarch, "sysarch", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_syscall, "syscall", NULL, NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_create, "thr_create", "%s(%#x, %#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_exit, "thr_exit", "%s(%#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_kill, "thr_kill", "%s(%d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_kill2, "thr_kill2", "%s(%d, %d, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_new, "thr_new", "%s(%#x, %d)", NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_self, "thr_self", "%s(%#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_set_name, "thr_set_name", "%s(%d, \"%s\")", NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_suspend, "thr_suspend", "%s(%d, %#x)", NULL, NULL },
+{ TARGET_FREEBSD_NR_thr_wake, "thr_wake", "%s(%d)", NULL, NULL },
 { TARGET_FREEBSD_NR_truncate, "truncate", NULL, NULL, NULL },
 { TARGET_FREEBSD_NR_umask, "umask", "%s(%#o)", NULL, NULL },
 { TARGET_FREEBSD_NR_unlink, "unlink", "%s(\"%s\")", NULL, NULL },
diff --git a/bsd-user/freebsd/syscall_nr.h b/bsd-user/freebsd/syscall_nr.h
index 36336ab..d849024 100644
--- a/bsd-user/freebsd/syscall_nr.h
+++ b/bsd-user/freebsd/syscall_nr.h
@@ -1,373 +1,450 @@
 /*
  * System call numbers.
  *
- * $FreeBSD: src/sys/sys/syscall.h,v 1.224 2008/08/24 21:23:08 rwatson Exp $
- * created from FreeBSD: head/sys/kern/syscalls.master 182123 2008-08-24 21:20:35Z rwatson
+ * created from FreeBSD: releng/9.1/sys/kern/syscalls.master 229723
+ * 2012-01-06 19:29:16Z jhb
  */
 
-#define TARGET_FREEBSD_NR_syscall     0
-#define TARGET_FREEBSD_NR_exit        1
-#define TARGET_FREEBSD_NR_fork        2
-#define TARGET_FREEBSD_NR_read        3
-#define TARGET_FREEBSD_NR_write       4
-#define TARGET_FREEBSD_NR_open        5
-#define TARGET_FREEBSD_NR_close       6
-#define TARGET_FREEBSD_NR_wait4       7
-#define TARGET_FREEBSD_NR_link        9
-#define TARGET_FREEBSD_NR_unlink      10
-#define TARGET_FREEBSD_NR_chdir       12
-#define TARGET_FREEBSD_NR_fchdir      13
-#define TARGET_FREEBSD_NR_mknod       14
-#define TARGET_FREEBSD_NR_chmod       15
-#define TARGET_FREEBSD_NR_chown       16
-#define TARGET_FREEBSD_NR_break       17
-#define TARGET_FREEBSD_NR_freebsd4_getfsstat  18
-#define TARGET_FREEBSD_NR_getpid      20
-#define TARGET_FREEBSD_NR_mount       21
-#define TARGET_FREEBSD_NR_unmount     22
-#define TARGET_FREEBSD_NR_setuid      23
-#define TARGET_FREEBSD_NR_getuid      24
-#define TARGET_FREEBSD_NR_geteuid     25
-#define TARGET_FREEBSD_NR_ptrace      26
-#define TARGET_FREEBSD_NR_recvmsg     27
-#define TARGET_FREEBSD_NR_sendmsg     28
-#define TARGET_FREEBSD_NR_recvfrom    29
-#define TARGET_FREEBSD_NR_accept      30
-#define TARGET_FREEBSD_NR_getpeername 31
-#define TARGET_FREEBSD_NR_getsockname 32
-#define TARGET_FREEBSD_NR_access      33
-#define TARGET_FREEBSD_NR_chflags     34
-#define TARGET_FREEBSD_NR_fchflags    35
-#define TARGET_FREEBSD_NR_sync        36
-#define TARGET_FREEBSD_NR_kill        37
-#define TARGET_FREEBSD_NR_getppid     39
-#define TARGET_FREEBSD_NR_dup 41
-#define TARGET_FREEBSD_NR_pipe        42
-#define TARGET_FREEBSD_NR_getegid     43
-#define TARGET_FREEBSD_NR_profil      44
-#define TARGET_FREEBSD_NR_ktrace      45
-#define TARGET_FREEBSD_NR_getgid      47
-#define TARGET_FREEBSD_NR_getlogin    49
-#define TARGET_FREEBSD_NR_setlogin    50
-#define TARGET_FREEBSD_NR_acct        51
-#define TARGET_FREEBSD_NR_sigaltstack 53
-#define TARGET_FREEBSD_NR_ioctl       54
-#define TARGET_FREEBSD_NR_reboot      55
-#define TARGET_FREEBSD_NR_revoke      56
-#define TARGET_FREEBSD_NR_symlink     57
-#define TARGET_FREEBSD_NR_readlink    58
-#define TARGET_FREEBSD_NR_execve      59
-#define TARGET_FREEBSD_NR_umask       60
-#define TARGET_FREEBSD_NR_chroot      61
-#define TARGET_FREEBSD_NR_msync       65
-#define TARGET_FREEBSD_NR_vfork       66
-#define TARGET_FREEBSD_NR_sbrk        69
-#define TARGET_FREEBSD_NR_sstk        70
-#define TARGET_FREEBSD_NR_vadvise     72
-#define TARGET_FREEBSD_NR_munmap      73
-#define TARGET_FREEBSD_NR_mprotect    74
-#define TARGET_FREEBSD_NR_madvise     75
-#define TARGET_FREEBSD_NR_mincore     78
-#define TARGET_FREEBSD_NR_getgroups   79
-#define TARGET_FREEBSD_NR_setgroups   80
-#define TARGET_FREEBSD_NR_getpgrp     81
-#define TARGET_FREEBSD_NR_setpgid     82
-#define TARGET_FREEBSD_NR_setitimer   83
-#define TARGET_FREEBSD_NR_swapon      85
-#define TARGET_FREEBSD_NR_getitimer   86
-#define TARGET_FREEBSD_NR_getdtablesize       89
-#define TARGET_FREEBSD_NR_dup2        90
-#define TARGET_FREEBSD_NR_fcntl       92
-#define TARGET_FREEBSD_NR_select      93
-#define TARGET_FREEBSD_NR_fsync       95
-#define TARGET_FREEBSD_NR_setpriority 96
-#define TARGET_FREEBSD_NR_socket      97
-#define TARGET_FREEBSD_NR_connect     98
-#define TARGET_FREEBSD_NR_getpriority 100
-#define TARGET_FREEBSD_NR_bind        104
-#define TARGET_FREEBSD_NR_setsockopt  105
-#define TARGET_FREEBSD_NR_listen      106
-#define TARGET_FREEBSD_NR_gettimeofday        116
-#define TARGET_FREEBSD_NR_getrusage   117
-#define TARGET_FREEBSD_NR_getsockopt  118
-#define TARGET_FREEBSD_NR_readv       120
-#define TARGET_FREEBSD_NR_writev      121
-#define TARGET_FREEBSD_NR_settimeofday        122
-#define TARGET_FREEBSD_NR_fchown      123
-#define TARGET_FREEBSD_NR_fchmod      124
-#define TARGET_FREEBSD_NR_setreuid    126
-#define TARGET_FREEBSD_NR_setregid    127
-#define TARGET_FREEBSD_NR_rename      128
-#define TARGET_FREEBSD_NR_flock       131
-#define TARGET_FREEBSD_NR_mkfifo      132
-#define TARGET_FREEBSD_NR_sendto      133
-#define TARGET_FREEBSD_NR_shutdown    134
-#define TARGET_FREEBSD_NR_socketpair  135
-#define TARGET_FREEBSD_NR_mkdir       136
-#define TARGET_FREEBSD_NR_rmdir       137
-#define TARGET_FREEBSD_NR_utimes      138
-#define TARGET_FREEBSD_NR_adjtime     140
-#define TARGET_FREEBSD_NR_setsid      147
-#define TARGET_FREEBSD_NR_quotactl    148
-#define TARGET_FREEBSD_NR_nlm_syscall 154
-#define TARGET_FREEBSD_NR_nfssvc      155
-#define TARGET_FREEBSD_NR_freebsd4_statfs     157
-#define TARGET_FREEBSD_NR_freebsd4_fstatfs    158
-#define TARGET_FREEBSD_NR_lgetfh      160
-#define TARGET_FREEBSD_NR_getfh       161
-#define TARGET_FREEBSD_NR_getdomainname       162
-#define TARGET_FREEBSD_NR_setdomainname       163
-#define TARGET_FREEBSD_NR_uname       164
-#define TARGET_FREEBSD_NR_sysarch     165
-#define TARGET_FREEBSD_NR_rtprio      166
-#define TARGET_FREEBSD_NR_semsys      169
-#define TARGET_FREEBSD_NR_msgsys      170
-#define TARGET_FREEBSD_NR_shmsys      171
-#define TARGET_FREEBSD_NR_freebsd6_pread      173
-#define TARGET_FREEBSD_NR_freebsd6_pwrite     174
-#define TARGET_FREEBSD_NR_setfib      175
-#define TARGET_FREEBSD_NR_ntp_adjtime 176
-#define TARGET_FREEBSD_NR_setgid      181
-#define TARGET_FREEBSD_NR_setegid     182
-#define TARGET_FREEBSD_NR_seteuid     183
-#define TARGET_FREEBSD_NR_stat        188
-#define TARGET_FREEBSD_NR_fstat       189
-#define TARGET_FREEBSD_NR_lstat       190
-#define TARGET_FREEBSD_NR_pathconf    191
-#define TARGET_FREEBSD_NR_fpathconf   192
-#define TARGET_FREEBSD_NR_getrlimit   194
-#define TARGET_FREEBSD_NR_setrlimit   195
-#define TARGET_FREEBSD_NR_getdirentries       196
-#define TARGET_FREEBSD_NR_freebsd6_mmap       197
-#define TARGET_FREEBSD_NR___syscall   198
-#define TARGET_FREEBSD_NR_freebsd6_lseek      199
-#define TARGET_FREEBSD_NR_freebsd6_truncate   200
-#define TARGET_FREEBSD_NR_freebsd6_ftruncate  201
-#define TARGET_FREEBSD_NR___sysctl    202
-#define TARGET_FREEBSD_NR_mlock       203
-#define TARGET_FREEBSD_NR_munlock     204
-#define TARGET_FREEBSD_NR_undelete    205
-#define TARGET_FREEBSD_NR_futimes     206
-#define TARGET_FREEBSD_NR_getpgid     207
-#define TARGET_FREEBSD_NR_poll        209
-#define TARGET_FREEBSD_NR___semctl    220
-#define TARGET_FREEBSD_NR_semget      221
-#define TARGET_FREEBSD_NR_semop       222
-#define TARGET_FREEBSD_NR_msgctl      224
-#define TARGET_FREEBSD_NR_msgget      225
-#define TARGET_FREEBSD_NR_msgsnd      226
-#define TARGET_FREEBSD_NR_msgrcv      227
-#define TARGET_FREEBSD_NR_shmat       228
-#define TARGET_FREEBSD_NR_shmctl      229
-#define TARGET_FREEBSD_NR_shmdt       230
-#define TARGET_FREEBSD_NR_shmget      231
-#define TARGET_FREEBSD_NR_clock_gettime       232
-#define TARGET_FREEBSD_NR_clock_settime       233
-#define TARGET_FREEBSD_NR_clock_getres        234
-#define TARGET_FREEBSD_NR_ktimer_create       235
-#define TARGET_FREEBSD_NR_ktimer_delete       236
-#define TARGET_FREEBSD_NR_ktimer_settime      237
-#define TARGET_FREEBSD_NR_ktimer_gettime      238
-#define TARGET_FREEBSD_NR_ktimer_getoverrun   239
-#define TARGET_FREEBSD_NR_nanosleep   240
-#define TARGET_FREEBSD_NR_ntp_gettime 248
-#define TARGET_FREEBSD_NR_minherit    250
-#define TARGET_FREEBSD_NR_rfork       251
-#define TARGET_FREEBSD_NR_openbsd_poll        252
-#define TARGET_FREEBSD_NR_issetugid   253
-#define TARGET_FREEBSD_NR_lchown      254
-#define TARGET_FREEBSD_NR_aio_read    255
-#define TARGET_FREEBSD_NR_aio_write   256
-#define TARGET_FREEBSD_NR_lio_listio  257
-#define TARGET_FREEBSD_NR_getdents    272
-#define TARGET_FREEBSD_NR_lchmod      274
-#define TARGET_FREEBSD_NR_netbsd_lchown       275
-#define TARGET_FREEBSD_NR_lutimes     276
-#define TARGET_FREEBSD_NR_netbsd_msync        277
-#define TARGET_FREEBSD_NR_nstat       278
-#define TARGET_FREEBSD_NR_nfstat      279
-#define TARGET_FREEBSD_NR_nlstat      280
-#define TARGET_FREEBSD_NR_preadv      289
-#define TARGET_FREEBSD_NR_pwritev     290
-#define TARGET_FREEBSD_NR_freebsd4_fhstatfs   297
-#define TARGET_FREEBSD_NR_fhopen      298
-#define TARGET_FREEBSD_NR_fhstat      299
-#define TARGET_FREEBSD_NR_modnext     300
-#define TARGET_FREEBSD_NR_modstat     301
-#define TARGET_FREEBSD_NR_modfnext    302
-#define TARGET_FREEBSD_NR_modfind     303
-#define TARGET_FREEBSD_NR_kldload     304
-#define TARGET_FREEBSD_NR_kldunload   305
-#define TARGET_FREEBSD_NR_kldfind     306
-#define TARGET_FREEBSD_NR_kldnext     307
-#define TARGET_FREEBSD_NR_kldstat     308
-#define TARGET_FREEBSD_NR_kldfirstmod 309
-#define TARGET_FREEBSD_NR_getsid      310
-#define TARGET_FREEBSD_NR_setresuid   311
-#define TARGET_FREEBSD_NR_setresgid   312
-#define TARGET_FREEBSD_NR_aio_return  314
-#define TARGET_FREEBSD_NR_aio_suspend 315
-#define TARGET_FREEBSD_NR_aio_cancel  316
-#define TARGET_FREEBSD_NR_aio_error   317
-#define TARGET_FREEBSD_NR_oaio_read   318
-#define TARGET_FREEBSD_NR_oaio_write  319
-#define TARGET_FREEBSD_NR_olio_listio 320
-#define TARGET_FREEBSD_NR_yield       321
-#define TARGET_FREEBSD_NR_mlockall    324
-#define TARGET_FREEBSD_NR_munlockall  325
-#define TARGET_FREEBSD_NR___getcwd    326
-#define TARGET_FREEBSD_NR_sched_setparam      327
-#define TARGET_FREEBSD_NR_sched_getparam      328
-#define TARGET_FREEBSD_NR_sched_setscheduler  329
-#define TARGET_FREEBSD_NR_sched_getscheduler  330
-#define TARGET_FREEBSD_NR_sched_yield 331
-#define TARGET_FREEBSD_NR_sched_get_priority_max      332
-#define TARGET_FREEBSD_NR_sched_get_priority_min      333
-#define TARGET_FREEBSD_NR_sched_rr_get_interval       334
-#define TARGET_FREEBSD_NR_utrace      335
-#define TARGET_FREEBSD_NR_freebsd4_sendfile   336
-#define TARGET_FREEBSD_NR_kldsym      337
-#define TARGET_FREEBSD_NR_jail        338
-#define TARGET_FREEBSD_NR_sigprocmask 340
-#define TARGET_FREEBSD_NR_sigsuspend  341
-#define TARGET_FREEBSD_NR_freebsd4_sigaction  342
-#define TARGET_FREEBSD_NR_sigpending  343
-#define TARGET_FREEBSD_NR_freebsd4_sigreturn  344
-#define TARGET_FREEBSD_NR_sigtimedwait        345
-#define TARGET_FREEBSD_NR_sigwaitinfo 346
-#define TARGET_FREEBSD_NR___acl_get_file      347
-#define TARGET_FREEBSD_NR___acl_set_file      348
-#define TARGET_FREEBSD_NR___acl_get_fd        349
-#define TARGET_FREEBSD_NR___acl_set_fd        350
-#define TARGET_FREEBSD_NR___acl_delete_file   351
-#define TARGET_FREEBSD_NR___acl_delete_fd     352
-#define TARGET_FREEBSD_NR___acl_aclcheck_file 353
-#define TARGET_FREEBSD_NR___acl_aclcheck_fd   354
-#define TARGET_FREEBSD_NR_extattrctl  355
-#define TARGET_FREEBSD_NR_extattr_set_file    356
-#define TARGET_FREEBSD_NR_extattr_get_file    357
-#define TARGET_FREEBSD_NR_extattr_delete_file 358
-#define TARGET_FREEBSD_NR_aio_waitcomplete    359
-#define TARGET_FREEBSD_NR_getresuid   360
-#define TARGET_FREEBSD_NR_getresgid   361
-#define TARGET_FREEBSD_NR_kqueue      362
-#define TARGET_FREEBSD_NR_kevent      363
-#define TARGET_FREEBSD_NR_extattr_set_fd      371
-#define TARGET_FREEBSD_NR_extattr_get_fd      372
-#define TARGET_FREEBSD_NR_extattr_delete_fd   373
-#define TARGET_FREEBSD_NR___setugid   374
-#define TARGET_FREEBSD_NR_nfsclnt     375
-#define TARGET_FREEBSD_NR_eaccess     376
-#define TARGET_FREEBSD_NR_nmount      378
-#define TARGET_FREEBSD_NR___mac_get_proc      384
-#define TARGET_FREEBSD_NR___mac_set_proc      385
-#define TARGET_FREEBSD_NR___mac_get_fd        386
-#define TARGET_FREEBSD_NR___mac_get_file      387
-#define TARGET_FREEBSD_NR___mac_set_fd        388
-#define TARGET_FREEBSD_NR___mac_set_file      389
-#define TARGET_FREEBSD_NR_kenv        390
-#define TARGET_FREEBSD_NR_lchflags    391
-#define TARGET_FREEBSD_NR_uuidgen     392
-#define TARGET_FREEBSD_NR_sendfile    393
-#define TARGET_FREEBSD_NR_mac_syscall 394
-#define TARGET_FREEBSD_NR_getfsstat   395
-#define TARGET_FREEBSD_NR_statfs      396
-#define TARGET_FREEBSD_NR_fstatfs     397
-#define TARGET_FREEBSD_NR_fhstatfs    398
-#define TARGET_FREEBSD_NR_ksem_close  400
-#define TARGET_FREEBSD_NR_ksem_post   401
-#define TARGET_FREEBSD_NR_ksem_wait   402
-#define TARGET_FREEBSD_NR_ksem_trywait        403
-#define TARGET_FREEBSD_NR_ksem_init   404
-#define TARGET_FREEBSD_NR_ksem_open   405
-#define TARGET_FREEBSD_NR_ksem_unlink 406
-#define TARGET_FREEBSD_NR_ksem_getvalue       407
-#define TARGET_FREEBSD_NR_ksem_destroy        408
-#define TARGET_FREEBSD_NR___mac_get_pid       409
-#define TARGET_FREEBSD_NR___mac_get_link      410
-#define TARGET_FREEBSD_NR___mac_set_link      411
-#define TARGET_FREEBSD_NR_extattr_set_link    412
-#define TARGET_FREEBSD_NR_extattr_get_link    413
-#define TARGET_FREEBSD_NR_extattr_delete_link 414
-#define TARGET_FREEBSD_NR___mac_execve        415
-#define TARGET_FREEBSD_NR_sigaction   416
-#define TARGET_FREEBSD_NR_sigreturn   417
-#define TARGET_FREEBSD_NR_getcontext  421
-#define TARGET_FREEBSD_NR_setcontext  422
-#define TARGET_FREEBSD_NR_swapcontext 423
-#define TARGET_FREEBSD_NR_swapoff     424
-#define TARGET_FREEBSD_NR___acl_get_link      425
-#define TARGET_FREEBSD_NR___acl_set_link      426
-#define TARGET_FREEBSD_NR___acl_delete_link   427
-#define TARGET_FREEBSD_NR___acl_aclcheck_link 428
-#define TARGET_FREEBSD_NR_sigwait     429
-#define TARGET_FREEBSD_NR_thr_create  430
-#define TARGET_FREEBSD_NR_thr_exit    431
-#define TARGET_FREEBSD_NR_thr_self    432
-#define TARGET_FREEBSD_NR_thr_kill    433
-#define TARGET_FREEBSD_NR__umtx_lock  434
-#define TARGET_FREEBSD_NR__umtx_unlock        435
-#define TARGET_FREEBSD_NR_jail_attach 436
-#define TARGET_FREEBSD_NR_extattr_list_fd     437
-#define TARGET_FREEBSD_NR_extattr_list_file   438
-#define TARGET_FREEBSD_NR_extattr_list_link   439
-#define TARGET_FREEBSD_NR_ksem_timedwait      441
-#define TARGET_FREEBSD_NR_thr_suspend 442
-#define TARGET_FREEBSD_NR_thr_wake    443
-#define TARGET_FREEBSD_NR_kldunloadf  444
-#define TARGET_FREEBSD_NR_audit       445
-#define TARGET_FREEBSD_NR_auditon     446
-#define TARGET_FREEBSD_NR_getauid     447
-#define TARGET_FREEBSD_NR_setauid     448
-#define TARGET_FREEBSD_NR_getaudit    449
-#define TARGET_FREEBSD_NR_setaudit    450
-#define TARGET_FREEBSD_NR_getaudit_addr       451
-#define TARGET_FREEBSD_NR_setaudit_addr       452
-#define TARGET_FREEBSD_NR_auditctl    453
-#define TARGET_FREEBSD_NR__umtx_op    454
-#define TARGET_FREEBSD_NR_thr_new     455
-#define TARGET_FREEBSD_NR_sigqueue    456
-#define TARGET_FREEBSD_NR_kmq_open    457
-#define TARGET_FREEBSD_NR_kmq_setattr 458
-#define TARGET_FREEBSD_NR_kmq_timedreceive    459
-#define TARGET_FREEBSD_NR_kmq_timedsend       460
-#define TARGET_FREEBSD_NR_kmq_notify  461
-#define TARGET_FREEBSD_NR_kmq_unlink  462
-#define TARGET_FREEBSD_NR_abort2      463
-#define TARGET_FREEBSD_NR_thr_set_name        464
-#define TARGET_FREEBSD_NR_aio_fsync   465
-#define TARGET_FREEBSD_NR_rtprio_thread       466
-#define TARGET_FREEBSD_NR_sctp_peeloff        471
-#define TARGET_FREEBSD_NR_sctp_generic_sendmsg        472
-#define TARGET_FREEBSD_NR_sctp_generic_sendmsg_iov    473
-#define TARGET_FREEBSD_NR_sctp_generic_recvmsg        474
-#define TARGET_FREEBSD_NR_pread       475
-#define TARGET_FREEBSD_NR_pwrite      476
-#define TARGET_FREEBSD_NR_mmap        477
-#define TARGET_FREEBSD_NR_lseek       478
-#define TARGET_FREEBSD_NR_truncate    479
-#define TARGET_FREEBSD_NR_ftruncate   480
-#define TARGET_FREEBSD_NR_thr_kill2   481
-#define TARGET_FREEBSD_NR_shm_open    482
-#define TARGET_FREEBSD_NR_shm_unlink  483
-#define TARGET_FREEBSD_NR_cpuset      484
-#define TARGET_FREEBSD_NR_cpuset_setid        485
-#define TARGET_FREEBSD_NR_cpuset_getid        486
-#define TARGET_FREEBSD_NR_cpuset_getaffinity  487
-#define TARGET_FREEBSD_NR_cpuset_setaffinity  488
-#define TARGET_FREEBSD_NR_faccessat   489
-#define TARGET_FREEBSD_NR_fchmodat    490
-#define TARGET_FREEBSD_NR_fchownat    491
-#define TARGET_FREEBSD_NR_fexecve     492
-#define TARGET_FREEBSD_NR_fstatat     493
-#define TARGET_FREEBSD_NR_futimesat   494
-#define TARGET_FREEBSD_NR_linkat      495
-#define TARGET_FREEBSD_NR_mkdirat     496
-#define TARGET_FREEBSD_NR_mkfifoat    497
-#define TARGET_FREEBSD_NR_mknodat     498
-#define TARGET_FREEBSD_NR_openat      499
-#define TARGET_FREEBSD_NR_readlinkat  500
-#define TARGET_FREEBSD_NR_renameat    501
-#define TARGET_FREEBSD_NR_symlinkat   502
-#define TARGET_FREEBSD_NR_unlinkat    503
-#define TARGET_FREEBSD_NR_posix_openpt        504
+#define TARGET_FREEBSD_NR_syscall   0
+#define TARGET_FREEBSD_NR_exit  1
+#define TARGET_FREEBSD_NR_fork  2
+#define TARGET_FREEBSD_NR_read  3
+#define TARGET_FREEBSD_NR_write 4
+#define TARGET_FREEBSD_NR_open  5
+#define TARGET_FREEBSD_NR_close 6
+#define TARGET_FREEBSD_NR_wait4 7
+                /* 8 is old creat */
+#define TARGET_FREEBSD_NR_link  9
+#define TARGET_FREEBSD_NR_unlink    10
+                /* 11 is obsolete execv */
+#define TARGET_FREEBSD_NR_chdir 12
+#define TARGET_FREEBSD_NR_fchdir    13
+#define TARGET_FREEBSD_NR_mknod 14
+#define TARGET_FREEBSD_NR_chmod 15
+#define TARGET_FREEBSD_NR_chown 16
+#define TARGET_FREEBSD_NR_break 17
+#define TARGET_FREEBSD_NR_freebsd4_getfsstat    18
+                /* 19 is old lseek */
+#define TARGET_FREEBSD_NR_getpid    20
+#define TARGET_FREEBSD_NR_mount 21
+#define TARGET_FREEBSD_NR_unmount   22
+#define TARGET_FREEBSD_NR_setuid    23
+#define TARGET_FREEBSD_NR_getuid    24
+#define TARGET_FREEBSD_NR_geteuid   25
+#define TARGET_FREEBSD_NR_ptrace    26
+#define TARGET_FREEBSD_NR_recvmsg   27
+#define TARGET_FREEBSD_NR_sendmsg   28
+#define TARGET_FREEBSD_NR_recvfrom  29
+#define TARGET_FREEBSD_NR_accept    30
+#define TARGET_FREEBSD_NR_getpeername   31
+#define TARGET_FREEBSD_NR_getsockname   32
+#define TARGET_FREEBSD_NR_access    33
+#define TARGET_FREEBSD_NR_chflags   34
+#define TARGET_FREEBSD_NR_fchflags  35
+#define TARGET_FREEBSD_NR_sync  36
+#define TARGET_FREEBSD_NR_kill  37
+                /* 38 is old stat */
+#define TARGET_FREEBSD_NR_getppid   39
+                /* 40 is old lstat */
+#define TARGET_FREEBSD_NR_dup   41
+#define TARGET_FREEBSD_NR_pipe  42
+#define TARGET_FREEBSD_NR_getegid   43
+#define TARGET_FREEBSD_NR_profil    44
+#define TARGET_FREEBSD_NR_ktrace    45
+                /* 46 is old sigaction */
+#define TARGET_FREEBSD_NR_getgid    47
+                /* 48 is old sigprocmask */
+#define TARGET_FREEBSD_NR_getlogin  49
+#define TARGET_FREEBSD_NR_setlogin  50
+#define TARGET_FREEBSD_NR_acct  51
+                /* 52 is old sigpending */
+#define TARGET_FREEBSD_NR_sigaltstack   53
+#define TARGET_FREEBSD_NR_ioctl 54
+#define TARGET_FREEBSD_NR_reboot    55
+#define TARGET_FREEBSD_NR_revoke    56
+#define TARGET_FREEBSD_NR_symlink   57
+#define TARGET_FREEBSD_NR_readlink  58
+#define TARGET_FREEBSD_NR_execve    59
+#define TARGET_FREEBSD_NR_umask 60
+#define TARGET_FREEBSD_NR_chroot    61
+                /* 62 is old fstat */
+                /* 63 is old getkerninfo */
+                /* 64 is old getpagesize */
+#define TARGET_FREEBSD_NR_msync 65
+#define TARGET_FREEBSD_NR_vfork 66
+                /* 67 is obsolete vread */
+                /* 68 is obsolete vwrite */
+#define TARGET_FREEBSD_NR_sbrk  69
+#define TARGET_FREEBSD_NR_sstk  70
+                /* 71 is old mmap */
+#define TARGET_FREEBSD_NR_vadvise   72
+#define TARGET_FREEBSD_NR_munmap    73
+#define TARGET_FREEBSD_NR_mprotect  74
+#define TARGET_FREEBSD_NR_madvise   75
+                /* 76 is obsolete vhangup */
+                /* 77 is obsolete vlimit */
+#define TARGET_FREEBSD_NR_mincore   78
+#define TARGET_FREEBSD_NR_getgroups 79
+#define TARGET_FREEBSD_NR_setgroups 80
+#define TARGET_FREEBSD_NR_getpgrp   81
+#define TARGET_FREEBSD_NR_setpgid   82
+#define TARGET_FREEBSD_NR_setitimer 83
+                /* 84 is old wait */
+#define TARGET_FREEBSD_NR_swapon    85
+#define TARGET_FREEBSD_NR_getitimer 86
+                /* 87 is old gethostname */
+                /* 88 is old sethostname */
+#define TARGET_FREEBSD_NR_getdtablesize 89
+#define TARGET_FREEBSD_NR_dup2  90
+#define TARGET_FREEBSD_NR_fcntl 92
+#define TARGET_FREEBSD_NR_select    93
+#define TARGET_FREEBSD_NR_fsync 95
+#define TARGET_FREEBSD_NR_setpriority   96
+#define TARGET_FREEBSD_NR_socket    97
+#define TARGET_FREEBSD_NR_connect   98
+                /* 99 is old accept */
+#define TARGET_FREEBSD_NR_getpriority   100
+                /* 101 is old send */
+                /* 102 is old recv */
+                /* 103 is old sigreturn */
+#define TARGET_FREEBSD_NR_bind  104
+#define TARGET_FREEBSD_NR_setsockopt    105
+#define TARGET_FREEBSD_NR_listen    106
+                /* 107 is obsolete vtimes */
+                /* 108 is old sigvec */
+                /* 109 is old sigblock */
+                /* 110 is old sigsetmask */
+                /* 111 is old sigsuspend */
+                /* 112 is old sigstack */
+                /* 113 is old recvmsg */
+                /* 114 is old sendmsg */
+                /* 115 is obsolete vtrace */
+#define TARGET_FREEBSD_NR_gettimeofday  116
+#define TARGET_FREEBSD_NR_getrusage 117
+#define TARGET_FREEBSD_NR_getsockopt    118
+#define TARGET_FREEBSD_NR_readv 120
+#define TARGET_FREEBSD_NR_writev    121
+#define TARGET_FREEBSD_NR_settimeofday  122
+#define TARGET_FREEBSD_NR_fchown    123
+#define TARGET_FREEBSD_NR_fchmod    124
+                /* 125 is old recvfrom */
+#define TARGET_FREEBSD_NR_setreuid  126
+#define TARGET_FREEBSD_NR_setregid  127
+#define TARGET_FREEBSD_NR_rename    128
+                /* 129 is old truncate */
+                /* 130 is old ftruncate */
+#define TARGET_FREEBSD_NR_flock 131
+#define TARGET_FREEBSD_NR_mkfifo    132
+#define TARGET_FREEBSD_NR_sendto    133
+#define TARGET_FREEBSD_NR_shutdown  134
+#define TARGET_FREEBSD_NR_socketpair    135
+#define TARGET_FREEBSD_NR_mkdir 136
+#define TARGET_FREEBSD_NR_rmdir 137
+#define TARGET_FREEBSD_NR_utimes    138
+                /* 139 is obsolete 4.2 sigreturn */
+#define TARGET_FREEBSD_NR_adjtime   140
+                /* 141 is old getpeername */
+                /* 142 is old gethostid */
+                /* 143 is old sethostid */
+                /* 144 is old getrlimit */
+                /* 145 is old setrlimit */
+                /* 146 is old killpg */
+#define TARGET_FREEBSD_NR_killpg    146 /* COMPAT */
+#define TARGET_FREEBSD_NR_setsid    147
+#define TARGET_FREEBSD_NR_quotactl  148
+                /* 149 is old quota */
+                /* 150 is old getsockname */
+#define TARGET_FREEBSD_NR_nlm_syscall   154
+#define TARGET_FREEBSD_NR_nfssvc    155
+                /* 156 is old getdirentries */
+#define TARGET_FREEBSD_NR_freebsd4_statfs   157
+#define TARGET_FREEBSD_NR_freebsd4_fstatfs  158
+#define TARGET_FREEBSD_NR_lgetfh    160
+#define TARGET_FREEBSD_NR_getfh 161
+#define TARGET_FREEBSD_NR_freebsd4_getdomainname    162
+#define TARGET_FREEBSD_NR_freebsd4_setdomainname    163
+#define TARGET_FREEBSD_NR_freebsd4_uname    164
+#define TARGET_FREEBSD_NR_sysarch   165
+#define TARGET_FREEBSD_NR_rtprio    166
+#define TARGET_FREEBSD_NR_semsys    169
+#define TARGET_FREEBSD_NR_msgsys    170
+#define TARGET_FREEBSD_NR_shmsys    171
+#define TARGET_FREEBSD_NR_freebsd6_pread    173
+#define TARGET_FREEBSD_NR_freebsd6_pwrite   174
+#define TARGET_FREEBSD_NR_setfib    175
+#define TARGET_FREEBSD_NR_ntp_adjtime   176
+#define TARGET_FREEBSD_NR_setgid    181
+#define TARGET_FREEBSD_NR_setegid   182
+#define TARGET_FREEBSD_NR_seteuid   183
+#define TARGET_FREEBSD_NR_stat  188
+#define TARGET_FREEBSD_NR_fstat 189
+#define TARGET_FREEBSD_NR_lstat 190
+#define TARGET_FREEBSD_NR_pathconf  191
+#define TARGET_FREEBSD_NR_fpathconf 192
+#define TARGET_FREEBSD_NR_getrlimit 194
+#define TARGET_FREEBSD_NR_setrlimit 195
+#define TARGET_FREEBSD_NR_getdirentries 196
+#define TARGET_FREEBSD_NR_freebsd6_mmap 197
+#define TARGET_FREEBSD_NR___syscall 198
+#define TARGET_FREEBSD_NR_freebsd6_lseek    199
+#define TARGET_FREEBSD_NR_freebsd6_truncate 200
+#define TARGET_FREEBSD_NR_freebsd6_ftruncate    201
+#define TARGET_FREEBSD_NR___sysctl  202
+#define TARGET_FREEBSD_NR_mlock 203
+#define TARGET_FREEBSD_NR_munlock   204
+#define TARGET_FREEBSD_NR_undelete  205
+#define TARGET_FREEBSD_NR_futimes   206
+#define TARGET_FREEBSD_NR_getpgid   207
+#define TARGET_FREEBSD_NR_poll  209
+#define TARGET_FREEBSD_NR_freebsd7___semctl 220
+#define TARGET_FREEBSD_NR_semget    221
+#define TARGET_FREEBSD_NR_semop 222
+#define TARGET_FREEBSD_NR_freebsd7_msgctl   224
+#define TARGET_FREEBSD_NR_msgget    225
+#define TARGET_FREEBSD_NR_msgsnd    226
+#define TARGET_FREEBSD_NR_msgrcv    227
+#define TARGET_FREEBSD_NR_shmat 228
+#define TARGET_FREEBSD_NR_freebsd7_shmctl   229
+#define TARGET_FREEBSD_NR_shmdt 230
+#define TARGET_FREEBSD_NR_shmget    231
+#define TARGET_FREEBSD_NR_clock_gettime 232
+#define TARGET_FREEBSD_NR_clock_settime 233
+#define TARGET_FREEBSD_NR_clock_getres  234
+#define TARGET_FREEBSD_NR_ktimer_create 235
+#define TARGET_FREEBSD_NR_ktimer_delete 236
+#define TARGET_FREEBSD_NR_ktimer_settime    237
+#define TARGET_FREEBSD_NR_ktimer_gettime    238
+#define TARGET_FREEBSD_NR_ktimer_getoverrun 239
+#define TARGET_FREEBSD_NR_nanosleep 240
+#define TARGET_FREEBSD_NR_ntp_gettime   248
+#define TARGET_FREEBSD_NR_minherit  250
+#define TARGET_FREEBSD_NR_rfork 251
+#define TARGET_FREEBSD_NR_openbsd_poll  252
+#define TARGET_FREEBSD_NR_issetugid 253
+#define TARGET_FREEBSD_NR_lchown    254
+#define TARGET_FREEBSD_NR_aio_read  255
+#define TARGET_FREEBSD_NR_aio_write 256
+#define TARGET_FREEBSD_NR_lio_listio    257
+#define TARGET_FREEBSD_NR_getdents  272
+#define TARGET_FREEBSD_NR_lchmod    274
+#define TARGET_FREEBSD_NR_netbsd_lchown 275
+#define TARGET_FREEBSD_NR_lutimes   276
+#define TARGET_FREEBSD_NR_netbsd_msync  277
+#define TARGET_FREEBSD_NR_nstat 278
+#define TARGET_FREEBSD_NR_nfstat    279
+#define TARGET_FREEBSD_NR_nlstat    280
+#define TARGET_FREEBSD_NR_preadv    289
+#define TARGET_FREEBSD_NR_pwritev   290
+#define TARGET_FREEBSD_NR_freebsd4_fhstatfs 297
+#define TARGET_FREEBSD_NR_fhopen    298
+#define TARGET_FREEBSD_NR_fhstat    299
+#define TARGET_FREEBSD_NR_modnext   300
+#define TARGET_FREEBSD_NR_modstat   301
+#define TARGET_FREEBSD_NR_modfnext  302
+#define TARGET_FREEBSD_NR_modfind   303
+#define TARGET_FREEBSD_NR_kldload   304
+#define TARGET_FREEBSD_NR_kldunload 305
+#define TARGET_FREEBSD_NR_kldfind   306
+#define TARGET_FREEBSD_NR_kldnext   307
+#define TARGET_FREEBSD_NR_kldstat   308
+#define TARGET_FREEBSD_NR_kldfirstmod   309
+#define TARGET_FREEBSD_NR_getsid    310
+#define TARGET_FREEBSD_NR_setresuid 311
+#define TARGET_FREEBSD_NR_setresgid 312
+                /* 313 is obsolete signanosleep */
+#define TARGET_FREEBSD_NR_aio_return    314
+#define TARGET_FREEBSD_NR_aio_suspend   315
+#define TARGET_FREEBSD_NR_aio_cancel    316
+#define TARGET_FREEBSD_NR_aio_error 317
+#define TARGET_FREEBSD_NR_oaio_read 318
+#define TARGET_FREEBSD_NR_oaio_write    319
+#define TARGET_FREEBSD_NR_olio_listio   320
+#define TARGET_FREEBSD_NR_yield 321
+                /* 322 is obsolete thr_sleep */
+                /* 323 is obsolete thr_wakeup */
+#define TARGET_FREEBSD_NR_mlockall  324
+#define TARGET_FREEBSD_NR_munlockall    325
+#define TARGET_FREEBSD_NR___getcwd  326
+#define TARGET_FREEBSD_NR_sched_setparam    327
+#define TARGET_FREEBSD_NR_sched_getparam    328
+#define TARGET_FREEBSD_NR_sched_setscheduler    329
+#define TARGET_FREEBSD_NR_sched_getscheduler    330
+#define TARGET_FREEBSD_NR_sched_yield   331
+#define TARGET_FREEBSD_NR_sched_get_priority_max    332
+#define TARGET_FREEBSD_NR_sched_get_priority_min    333
+#define TARGET_FREEBSD_NR_sched_rr_get_interval 334
+#define TARGET_FREEBSD_NR_utrace    335
+#define TARGET_FREEBSD_NR_freebsd4_sendfile 336
+#define TARGET_FREEBSD_NR_kldsym    337
+#define TARGET_FREEBSD_NR_jail  338
+#define TARGET_FREEBSD_NR_nnpfs_syscall 339
+#define TARGET_FREEBSD_NR_sigprocmask   340
+#define TARGET_FREEBSD_NR_sigsuspend    341
+#define TARGET_FREEBSD_NR_freebsd4_sigaction    342
+#define TARGET_FREEBSD_NR_sigpending    343
+#define TARGET_FREEBSD_NR_freebsd4_sigreturn    344
+#define TARGET_FREEBSD_NR_sigtimedwait  345
+#define TARGET_FREEBSD_NR_sigwaitinfo   346
+#define TARGET_FREEBSD_NR___acl_get_file    347
+#define TARGET_FREEBSD_NR___acl_set_file    348
+#define TARGET_FREEBSD_NR___acl_get_fd  349
+#define TARGET_FREEBSD_NR___acl_set_fd  350
+#define TARGET_FREEBSD_NR___acl_delete_file 351
+#define TARGET_FREEBSD_NR___acl_delete_fd   352
+#define TARGET_FREEBSD_NR___acl_aclcheck_file   353
+#define TARGET_FREEBSD_NR___acl_aclcheck_fd 354
+#define TARGET_FREEBSD_NR_extattrctl    355
+#define TARGET_FREEBSD_NR_extattr_set_file  356
+#define TARGET_FREEBSD_NR_extattr_get_file  357
+#define TARGET_FREEBSD_NR_extattr_delete_file   358
+#define TARGET_FREEBSD_NR_aio_waitcomplete  359
+#define TARGET_FREEBSD_NR_getresuid 360
+#define TARGET_FREEBSD_NR_getresgid 361
+#define TARGET_FREEBSD_NR_kqueue    362
+#define TARGET_FREEBSD_NR_kevent    363
+#define TARGET_FREEBSD_NR_extattr_set_fd    371
+#define TARGET_FREEBSD_NR_extattr_get_fd    372
+#define TARGET_FREEBSD_NR_extattr_delete_fd 373
+#define TARGET_FREEBSD_NR___setugid 374
+#define TARGET_FREEBSD_NR_eaccess   376
+#define TARGET_FREEBSD_NR_afs3_syscall  377
+#define TARGET_FREEBSD_NR_nmount    378
+#define TARGET_FREEBSD_NR___mac_get_proc    384
+#define TARGET_FREEBSD_NR___mac_set_proc    385
+#define TARGET_FREEBSD_NR___mac_get_fd  386
+#define TARGET_FREEBSD_NR___mac_get_file    387
+#define TARGET_FREEBSD_NR___mac_set_fd  388
+#define TARGET_FREEBSD_NR___mac_set_file    389
+#define TARGET_FREEBSD_NR_kenv  390
+#define TARGET_FREEBSD_NR_lchflags  391
+#define TARGET_FREEBSD_NR_uuidgen   392
+#define TARGET_FREEBSD_NR_sendfile  393
+#define TARGET_FREEBSD_NR_mac_syscall   394
+#define TARGET_FREEBSD_NR_getfsstat 395
+#define TARGET_FREEBSD_NR_statfs    396
+#define TARGET_FREEBSD_NR_fstatfs   397
+#define TARGET_FREEBSD_NR_fhstatfs  398
+#define TARGET_FREEBSD_NR_ksem_close    400
+#define TARGET_FREEBSD_NR_ksem_post 401
+#define TARGET_FREEBSD_NR_ksem_wait 402
+#define TARGET_FREEBSD_NR_ksem_trywait  403
+#define TARGET_FREEBSD_NR_ksem_init 404
+#define TARGET_FREEBSD_NR_ksem_open 405
+#define TARGET_FREEBSD_NR_ksem_unlink   406
+#define TARGET_FREEBSD_NR_ksem_getvalue 407
+#define TARGET_FREEBSD_NR_ksem_destroy  408
+#define TARGET_FREEBSD_NR___mac_get_pid 409
+#define TARGET_FREEBSD_NR___mac_get_link    410
+#define TARGET_FREEBSD_NR___mac_set_link    411
+#define TARGET_FREEBSD_NR_extattr_set_link  412
+#define TARGET_FREEBSD_NR_extattr_get_link  413
+#define TARGET_FREEBSD_NR_extattr_delete_link   414
+#define TARGET_FREEBSD_NR___mac_execve  415
+#define TARGET_FREEBSD_NR_sigaction 416
+#define TARGET_FREEBSD_NR_sigreturn 417
+#define TARGET_FREEBSD_NR_getcontext    421
+#define TARGET_FREEBSD_NR_setcontext    422
+#define TARGET_FREEBSD_NR_swapcontext   423
+#define TARGET_FREEBSD_NR_swapoff   424
+#define TARGET_FREEBSD_NR___acl_get_link    425
+#define TARGET_FREEBSD_NR___acl_set_link    426
+#define TARGET_FREEBSD_NR___acl_delete_link 427
+#define TARGET_FREEBSD_NR___acl_aclcheck_link   428
+#define TARGET_FREEBSD_NR_sigwait   429
+#define TARGET_FREEBSD_NR_thr_create    430
+#define TARGET_FREEBSD_NR_thr_exit  431
+#define TARGET_FREEBSD_NR_thr_self  432
+#define TARGET_FREEBSD_NR_thr_kill  433
+#define TARGET_FREEBSD_NR__umtx_lock    434
+#define TARGET_FREEBSD_NR__umtx_unlock  435
+#define TARGET_FREEBSD_NR_jail_attach   436
+#define TARGET_FREEBSD_NR_extattr_list_fd   437
+#define TARGET_FREEBSD_NR_extattr_list_file 438
+#define TARGET_FREEBSD_NR_extattr_list_link 439
+#define TARGET_FREEBSD_NR_ksem_timedwait    441
+#define TARGET_FREEBSD_NR_thr_suspend   442
+#define TARGET_FREEBSD_NR_thr_wake  443
+#define TARGET_FREEBSD_NR_kldunloadf    444
+#define TARGET_FREEBSD_NR_audit 445
+#define TARGET_FREEBSD_NR_auditon   446
+#define TARGET_FREEBSD_NR_getauid   447
+#define TARGET_FREEBSD_NR_setauid   448
+#define TARGET_FREEBSD_NR_getaudit  449
+#define TARGET_FREEBSD_NR_setaudit  450
+#define TARGET_FREEBSD_NR_getaudit_addr 451
+#define TARGET_FREEBSD_NR_setaudit_addr 452
+#define TARGET_FREEBSD_NR_auditctl  453
+#define TARGET_FREEBSD_NR__umtx_op  454
+#define TARGET_FREEBSD_NR_thr_new   455
+#define TARGET_FREEBSD_NR_sigqueue  456
+#define TARGET_FREEBSD_NR_kmq_open  457
+#define TARGET_FREEBSD_NR_kmq_setattr   458
+#define TARGET_FREEBSD_NR_kmq_timedreceive  459
+#define TARGET_FREEBSD_NR_kmq_timedsend 460
+#define TARGET_FREEBSD_NR_kmq_notify    461
+#define TARGET_FREEBSD_NR_kmq_unlink    462
+#define TARGET_FREEBSD_NR_abort2    463
+#define TARGET_FREEBSD_NR_thr_set_name  464
+#define TARGET_FREEBSD_NR_aio_fsync 465
+#define TARGET_FREEBSD_NR_rtprio_thread 466
+#define TARGET_FREEBSD_NR_sctp_peeloff  471
+#define TARGET_FREEBSD_NR_sctp_generic_sendmsg  472
+#define TARGET_FREEBSD_NR_sctp_generic_sendmsg_iov  473
+#define TARGET_FREEBSD_NR_sctp_generic_recvmsg  474
+#define TARGET_FREEBSD_NR_pread 475
+#define TARGET_FREEBSD_NR_pwrite    476
+#define TARGET_FREEBSD_NR_mmap  477
+#define TARGET_FREEBSD_NR_lseek 478
+#define TARGET_FREEBSD_NR_truncate  479
+#define TARGET_FREEBSD_NR_ftruncate 480
+#define TARGET_FREEBSD_NR_thr_kill2 481
+#define TARGET_FREEBSD_NR_shm_open  482
+#define TARGET_FREEBSD_NR_shm_unlink    483
+#define TARGET_FREEBSD_NR_cpuset    484
+#define TARGET_FREEBSD_NR_cpuset_setid  485
+#define TARGET_FREEBSD_NR_cpuset_getid  486
+#define TARGET_FREEBSD_NR_cpuset_getaffinity    487
+#define TARGET_FREEBSD_NR_cpuset_setaffinity    488
+#define TARGET_FREEBSD_NR_faccessat 489
+#define TARGET_FREEBSD_NR_fchmodat  490
+#define TARGET_FREEBSD_NR_fchownat  491
+#define TARGET_FREEBSD_NR_fexecve   492
+#define TARGET_FREEBSD_NR_fstatat   493
+#define TARGET_FREEBSD_NR_futimesat 494
+#define TARGET_FREEBSD_NR_linkat    495
+#define TARGET_FREEBSD_NR_mkdirat   496
+#define TARGET_FREEBSD_NR_mkfifoat  497
+#define TARGET_FREEBSD_NR_mknodat   498
+#define TARGET_FREEBSD_NR_openat    499
+#define TARGET_FREEBSD_NR_readlinkat    500
+#define TARGET_FREEBSD_NR_renameat  501
+#define TARGET_FREEBSD_NR_symlinkat 502
+#define TARGET_FREEBSD_NR_unlinkat  503
+#define TARGET_FREEBSD_NR_posix_openpt  504
+#define TARGET_FREEBSD_NR_gssd_syscall  505
+#define TARGET_FREEBSD_NR_jail_get  506
+#define TARGET_FREEBSD_NR_jail_set  507
+#define TARGET_FREEBSD_NR_jail_remove   508
+#define TARGET_FREEBSD_NR_closefrom 509
+#define TARGET_FREEBSD_NR___semctl  510
+#define TARGET_FREEBSD_NR_msgctl    511
+#define TARGET_FREEBSD_NR_shmctl    512
+#define TARGET_FREEBSD_NR_lpathconf 513
+#define TARGET_FREEBSD_NR_cap_new   514
+#define TARGET_FREEBSD_NR_cap_getrights 515
+#define TARGET_FREEBSD_NR_cap_enter 516
+#define TARGET_FREEBSD_NR_cap_getmode   517
+#define TARGET_FREEBSD_NR_pdfork    518
+#define TARGET_FREEBSD_NR_pdkill    519
+#define TARGET_FREEBSD_NR_pdgetpid  520
+#define TARGET_FREEBSD_NR_pselect   522
+#define TARGET_FREEBSD_NR_getloginclass 523
+#define TARGET_FREEBSD_NR_setloginclass 524
+#define TARGET_FREEBSD_NR_rctl_get_racct    525
+#define TARGET_FREEBSD_NR_rctl_get_rules    526
+#define TARGET_FREEBSD_NR_rctl_get_limits   527
+#define TARGET_FREEBSD_NR_rctl_add_rule 528
+#define TARGET_FREEBSD_NR_rctl_remove_rule  529
+#define TARGET_FREEBSD_NR_posix_fallocate   530
+#define TARGET_FREEBSD_NR_posix_fadvise 531
+#define TARGET_FREEBSD_NR_MAXSYSCALL    532
diff --git a/bsd-user/mmap.c b/bsd-user/mmap.c
index aae8ea1..092bf7f 100644
--- a/bsd-user/mmap.c
+++ b/bsd-user/mmap.c
@@ -74,66 +74,6 @@
 }
 #endif
 
-static void *bsd_vmalloc(size_t size)
-{
-    void *p;
-    mmap_lock();
-    /* Use map and mark the pages as used.  */
-    p = mmap(NULL, size, PROT_READ | PROT_WRITE,
-             MAP_PRIVATE | MAP_ANON, -1, 0);
-
-    if (h2g_valid(p)) {
-        /* Allocated region overlaps guest address space.
-           This may recurse.  */
-        abi_ulong addr = h2g(p);
-        page_set_flags(addr & TARGET_PAGE_MASK, TARGET_PAGE_ALIGN(addr + size),
-                       PAGE_RESERVED);
-    }
-
-    mmap_unlock();
-    return p;
-}
-
-void *g_malloc(size_t size)
-{
-    char * p;
-    size += 16;
-    p = bsd_vmalloc(size);
-    *(size_t *)p = size;
-    return p + 16;
-}
-
-/* We use map, which is always zero initialized.  */
-void * g_malloc0(size_t size)
-{
-    return g_malloc(size);
-}
-
-void g_free(void *ptr)
-{
-    /* FIXME: We should unmark the reserved pages here.  However this gets
-       complicated when one target page spans multiple host pages, so we
-       don't bother.  */
-    size_t *p;
-    p = (size_t *)((char *)ptr - 16);
-    munmap(p, *p);
-}
-
-void *g_realloc(void *ptr, size_t size)
-{
-    size_t old_size, copy;
-    void *new_ptr;
-
-    if (!ptr)
-        return g_malloc(size);
-    old_size = *(size_t *)((char *)ptr - 16);
-    copy = old_size < size ? old_size : size;
-    new_ptr = g_malloc(size);
-    memcpy(new_ptr, ptr, copy);
-    g_free(ptr);
-    return new_ptr;
-}
-
 /* NOTE: all the constants are the HOST ones, but addresses are target. */
 int target_mprotect(abi_ulong start, abi_ulong len, int prot)
 {
diff --git a/bsd-user/qemu.h b/bsd-user/qemu.h
index 9d90668..5362297 100644
--- a/bsd-user/qemu.h
+++ b/bsd-user/qemu.h
@@ -1,3 +1,19 @@
+/*
+ *  qemu bsd user mode definition
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
 #ifndef QEMU_H
 #define QEMU_H
 
@@ -150,6 +166,16 @@
 #include "qemu/log.h"
 
 /* strace.c */
+struct syscallname {
+    int nr;
+    const char *name;
+    const char *format;
+    void (*call)(const struct syscallname *,
+                 abi_long, abi_long, abi_long,
+                 abi_long, abi_long, abi_long);
+    void (*result)(const struct syscallname *, abi_long);
+};
+
 void
 print_freebsd_syscall(int num,
                       abi_long arg1, abi_long arg2, abi_long arg3,
diff --git a/bsd-user/strace.c b/bsd-user/strace.c
index d73bbca..e33dd4d 100644
--- a/bsd-user/strace.c
+++ b/bsd-user/strace.c
@@ -1,37 +1,71 @@
+/*
+ *  System call tracing and debugging
+ *
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
 #include <stdio.h>
 #include <errno.h>
 #include <sys/select.h>
 #include <sys/types.h>
 #include <unistd.h>
 #include <sys/syscall.h>
+#include <sys/ioccom.h>
+#include <ctype.h>
+
 #include "qemu.h"
 
-int do_strace=0;
-
-struct syscallname {
-    int nr;
-    const char *name;
-    const char *format;
-    void (*call)(const struct syscallname *,
-                 abi_long, abi_long, abi_long,
-                 abi_long, abi_long, abi_long);
-    void (*result)(const struct syscallname *, abi_long);
-};
+int do_strace;
 
 /*
  * Utility functions
  */
 
-static void
-print_execve(const struct syscallname *name,
-             abi_long arg1, abi_long arg2, abi_long arg3,
-             abi_long arg4, abi_long arg5, abi_long arg6)
+static void print_sysctl(const struct syscallname *name, abi_long arg1,
+        abi_long arg2, abi_long arg3, abi_long arg4, abi_long arg5,
+        abi_long arg6)
+{
+    uint32_t i;
+    int32_t *namep;
+
+    gemu_log("%s({ ", name->name);
+    namep = lock_user(VERIFY_READ, arg1, sizeof(int32_t) * arg2, 1);
+    if (namep) {
+        int32_t *p = namep;
+
+        for (i = 0; i < (uint32_t)arg2; i++) {
+            gemu_log("%d ", tswap32(*p++));
+        }
+        unlock_user(namep, arg1, 0);
+    }
+    gemu_log("}, %u, 0x" TARGET_ABI_FMT_lx ", 0x" TARGET_ABI_FMT_lx ", 0x"
+        TARGET_ABI_FMT_lx ", 0x" TARGET_ABI_FMT_lx ")",
+        (uint32_t)arg2, arg3, arg4, arg5, arg6);
+}
+
+static void print_execve(const struct syscallname *name, abi_long arg1,
+        abi_long arg2, abi_long arg3, abi_long arg4, abi_long arg5,
+        abi_long arg6)
 {
     abi_ulong arg_ptr_addr;
     char *s;
 
-    if (!(s = lock_user_string(arg1)))
+    s = lock_user_string(arg1);
+    if (s == NULL) {
         return;
+    }
     gemu_log("%s(\"%s\",{", name->name, s);
     unlock_user(s, arg1, 0);
 
@@ -39,29 +73,48 @@
         abi_ulong *arg_ptr, arg_addr;
 
         arg_ptr = lock_user(VERIFY_READ, arg_ptr_addr, sizeof(abi_ulong), 1);
-        if (!arg_ptr)
+        if (!arg_ptr) {
             return;
+        }
         arg_addr = tswapl(*arg_ptr);
         unlock_user(arg_ptr, arg_ptr_addr, 0);
-        if (!arg_addr)
+        if (!arg_addr) {
             break;
+        }
         if ((s = lock_user_string(arg_addr))) {
             gemu_log("\"%s\",", s);
             unlock_user(s, arg_addr, 0);
         }
     }
-
     gemu_log("NULL})");
 }
 
+static void print_ioctl(const struct syscallname *name,
+        abi_long arg1, abi_long arg2, abi_long arg3, abi_long arg4,
+        abi_long arg5, abi_long arg6)
+{
+    /* Decode the ioctl request */
+    gemu_log("%s(%d, 0x%0lx { IO%s%s GRP:0x%x('%c') CMD:%d LEN:%d }, 0x"
+            TARGET_ABI_FMT_lx ", ...)",
+            name->name,
+            (int)arg1,
+            (unsigned long)arg2,
+            arg2 & IOC_OUT ? "R" : "",
+            arg2 & IOC_IN ? "W" : "",
+            (unsigned)IOCGROUP(arg2),
+            isprint(IOCGROUP(arg2)) ? (char)IOCGROUP(arg2) : '?',
+            (int)arg2 & 0xFF,
+            (int)IOCPARM_LEN(arg2),
+            arg3);
+}
+
 /*
  * Variants for the return value output function
  */
 
-static void
-print_syscall_ret_addr(const struct syscallname *name, abi_long ret)
+static void print_syscall_ret_addr(const struct syscallname *name, abi_long ret)
 {
-if( ret == -1 ) {
+    if (ret == -1) {
         gemu_log(" = -1 errno=%d (%s)\n", errno, strerror(errno));
     } else {
         gemu_log(" = 0x" TARGET_ABI_FMT_lx "\n", ret);
@@ -90,10 +143,9 @@
 #include "openbsd/strace.list"
 };
 
-static void
-print_syscall(int num, const struct syscallname *scnames, unsigned int nscnames,
-              abi_long arg1, abi_long arg2, abi_long arg3,
-              abi_long arg4, abi_long arg5, abi_long arg6)
+static void print_syscall(int num, const struct syscallname *scnames,
+        unsigned int nscnames, abi_long arg1, abi_long arg2, abi_long arg3,
+        abi_long arg4, abi_long arg5, abi_long arg6)
 {
     unsigned int i;
     const char *format="%s(" TARGET_ABI_FMT_ld "," TARGET_ABI_FMT_ld ","
@@ -102,36 +154,37 @@
 
     gemu_log("%d ", getpid() );
 
-    for (i = 0; i < nscnames; i++)
+    for (i = 0; i < nscnames; i++) {
         if (scnames[i].nr == num) {
             if (scnames[i].call != NULL) {
                 scnames[i].call(&scnames[i], arg1, arg2, arg3, arg4, arg5,
-                                arg6);
+                        arg6);
             } else {
                 /* XXX: this format system is broken because it uses
                    host types and host pointers for strings */
-                if (scnames[i].format != NULL)
+                if (scnames[i].format != NULL) {
                     format = scnames[i].format;
-                gemu_log(format, scnames[i].name, arg1, arg2, arg3, arg4,
-                         arg5, arg6);
+                }
+                gemu_log(format, scnames[i].name, arg1, arg2, arg3, arg4, arg5,
+                        arg6);
             }
             return;
         }
+    }
     gemu_log("Unknown syscall %d\n", num);
 }
 
-static void
-print_syscall_ret(int num, abi_long ret, const struct syscallname *scnames,
-                  unsigned int nscnames)
+static void print_syscall_ret(int num, abi_long ret,
+        const struct syscallname *scnames, unsigned int nscnames)
 {
     unsigned int i;
 
-    for (i = 0; i < nscnames; i++)
+    for (i = 0; i < nscnames; i++) {
         if (scnames[i].nr == num) {
             if (scnames[i].result != NULL) {
                 scnames[i].result(&scnames[i], ret);
             } else {
-                if( ret < 0 ) {
+                if (ret < 0) {
                     gemu_log(" = -1 errno=" TARGET_ABI_FMT_ld " (%s)\n", -ret,
                              strerror(-ret));
                 } else {
@@ -140,52 +193,50 @@
             }
             break;
         }
+    }
 }
 
 /*
  * The public interface to this module.
  */
-void
-print_freebsd_syscall(int num,
-                      abi_long arg1, abi_long arg2, abi_long arg3,
-                      abi_long arg4, abi_long arg5, abi_long arg6)
+void print_freebsd_syscall(int num, abi_long arg1, abi_long arg2, abi_long arg3,
+        abi_long arg4, abi_long arg5, abi_long arg6)
 {
-    print_syscall(num, freebsd_scnames, ARRAY_SIZE(freebsd_scnames),
-                  arg1, arg2, arg3, arg4, arg5, arg6);
+
+    print_syscall(num, freebsd_scnames, ARRAY_SIZE(freebsd_scnames), arg1, arg2,
+            arg3, arg4, arg5, arg6);
 }
 
-void
-print_freebsd_syscall_ret(int num, abi_long ret)
+void print_freebsd_syscall_ret(int num, abi_long ret)
 {
+
     print_syscall_ret(num, ret, freebsd_scnames, ARRAY_SIZE(freebsd_scnames));
 }
 
-void
-print_netbsd_syscall(int num,
-                      abi_long arg1, abi_long arg2, abi_long arg3,
-                      abi_long arg4, abi_long arg5, abi_long arg6)
+void print_netbsd_syscall(int num, abi_long arg1, abi_long arg2, abi_long arg3,
+        abi_long arg4, abi_long arg5, abi_long arg6)
 {
+
     print_syscall(num, netbsd_scnames, ARRAY_SIZE(netbsd_scnames),
                   arg1, arg2, arg3, arg4, arg5, arg6);
 }
 
-void
-print_netbsd_syscall_ret(int num, abi_long ret)
+void print_netbsd_syscall_ret(int num, abi_long ret)
 {
+
     print_syscall_ret(num, ret, netbsd_scnames, ARRAY_SIZE(netbsd_scnames));
 }
 
-void
-print_openbsd_syscall(int num,
-                      abi_long arg1, abi_long arg2, abi_long arg3,
-                      abi_long arg4, abi_long arg5, abi_long arg6)
+void print_openbsd_syscall(int num, abi_long arg1, abi_long arg2, abi_long arg3,
+        abi_long arg4, abi_long arg5, abi_long arg6)
 {
-    print_syscall(num, openbsd_scnames, ARRAY_SIZE(openbsd_scnames),
-                  arg1, arg2, arg3, arg4, arg5, arg6);
+
+    print_syscall(num, openbsd_scnames, ARRAY_SIZE(openbsd_scnames), arg1, arg2,
+            arg3, arg4, arg5, arg6);
 }
 
-void
-print_openbsd_syscall_ret(int num, abi_long ret)
+void print_openbsd_syscall_ret(int num, abi_long ret)
 {
+
     print_syscall_ret(num, ret, openbsd_scnames, ARRAY_SIZE(openbsd_scnames));
 }
diff --git a/configure b/configure
index 23514ec..dfbe75e 100755
--- a/configure
+++ b/configure
@@ -3,6 +3,11 @@
 # qemu configure script (c) 2003 Fabrice Bellard
 #
 
+# Unset some variables known to interfere with behavior of common tools,
+# just as autoconf does.
+CLICOLOR_FORCE= GREP_OPTIONS=
+unset CLICOLOR_FORCE GREP_OPTIONS
+
 # Temporary directory used for files created while
 # configure runs. Since it is in the build directory
 # we can safely blow away any previous version of it
@@ -541,6 +546,9 @@
 
 # OS specific
 
+# host *BSD for user mode
+HOST_VARIANT_DIR=""
+
 case $targetos in
 CYGWIN*)
   mingw32="yes"
@@ -566,12 +574,14 @@
   # needed for kinfo_getvmmap(3) in libutil.h
   LIBS="-lutil $LIBS"
   netmap=""  # enable netmap autodetect
+  HOST_VARIANT_DIR="freebsd"
 ;;
 DragonFly)
   bsd="yes"
   make="${MAKE-gmake}"
   audio_drv_list="oss"
   audio_possible_drivers="oss sdl esd pa"
+  HOST_VARIANT_DIR="dragonfly"
 ;;
 NetBSD)
   bsd="yes"
@@ -579,12 +589,14 @@
   audio_drv_list="oss"
   audio_possible_drivers="oss sdl esd"
   oss_lib="-lossaudio"
+  HOST_VARIANT_DIR="netbsd"
 ;;
 OpenBSD)
   bsd="yes"
   make="${MAKE-gmake}"
   audio_drv_list="sdl"
   audio_possible_drivers="sdl esd"
+  HOST_VARIANT_DIR="openbsd"
 ;;
 Darwin)
   bsd="yes"
@@ -602,6 +614,7 @@
   # Disable attempts to use ObjectiveC features in os/object.h since they
   # won't work when we're compiling with gcc as a C compiler.
   QEMU_CFLAGS="-DOS_OBJECT_USE_OBJC=0 $QEMU_CFLAGS"
+  HOST_VARIANT_DIR="darwin"
 ;;
 SunOS)
   solaris="yes"
@@ -3456,9 +3469,9 @@
 if compile_prog "" "" ; then
   :
 # we need pthread for static linking. use previous pthread test result
-elif compile_prog "" "-lrt $pthread_lib" ; then
-  LIBS="-lrt $LIBS"
-  libs_qga="-lrt $libs_qga"
+elif compile_prog "" "$pthread_lib -lrt" ; then
+  LIBS="$LIBS -lrt"
+  libs_qga="$libs_qga -lrt"
 fi
 
 if test "$darwin" != "yes" -a "$mingw32" != "yes" -a "$solaris" != yes -a \
@@ -4985,6 +4998,9 @@
   TARGET_ABI_DIR=$TARGET_ARCH
 fi
 echo "TARGET_ABI_DIR=$TARGET_ABI_DIR" >> $config_target_mak
+if [ "$HOST_VARIANT_DIR" != "" ]; then
+    echo "HOST_VARIANT_DIR=$HOST_VARIANT_DIR" >> $config_target_mak
+fi
 case "$target_name" in
   i386|x86_64)
     if test "$xen" = "yes" -a "$target_softmmu" = "yes" ; then
diff --git a/coroutine-gthread.c b/coroutine-gthread.c
index a61efe0..6bd6d6b 100644
--- a/coroutine-gthread.c
+++ b/coroutine-gthread.c
@@ -30,20 +30,14 @@
     CoroutineAction action;
 } CoroutineGThread;
 
-static GStaticMutex coroutine_lock = G_STATIC_MUTEX_INIT;
+static CompatGMutex coroutine_lock;
+static CompatGCond coroutine_cond;
 
 /* GLib 2.31 and beyond deprecated various parts of the thread API,
  * but the new interfaces are not available in older GLib versions
  * so we have to cope with both.
  */
 #if GLIB_CHECK_VERSION(2, 31, 0)
-/* Default zero-initialisation is sufficient for 2.31+ GCond */
-static GCond the_coroutine_cond;
-static GCond *coroutine_cond = &the_coroutine_cond;
-static inline void init_coroutine_cond(void)
-{
-}
-
 /* Awkwardly, the GPrivate API doesn't provide a way to update the
  * GDestroyNotify handler for the coroutine key dynamically. So instead
  * we track whether or not the CoroutineGThread should be freed on
@@ -84,11 +78,6 @@
 #else
 
 /* Handle older GLib versions */
-static GCond *coroutine_cond;
-static inline void init_coroutine_cond(void)
-{
-    coroutine_cond = g_cond_new();
-}
 
 static GStaticPrivate coroutine_key = G_STATIC_PRIVATE_INIT;
 
@@ -120,22 +109,20 @@
         g_thread_init(NULL);
     }
 #endif
-
-    init_coroutine_cond();
 }
 
 static void coroutine_wait_runnable_locked(CoroutineGThread *co)
 {
     while (!co->runnable) {
-        g_cond_wait(coroutine_cond, g_static_mutex_get_mutex(&coroutine_lock));
+        g_cond_wait(&coroutine_cond, &coroutine_lock);
     }
 }
 
 static void coroutine_wait_runnable(CoroutineGThread *co)
 {
-    g_static_mutex_lock(&coroutine_lock);
+    g_mutex_lock(&coroutine_lock);
     coroutine_wait_runnable_locked(co);
-    g_static_mutex_unlock(&coroutine_lock);
+    g_mutex_unlock(&coroutine_lock);
 }
 
 static gpointer coroutine_thread(gpointer opaque)
@@ -177,17 +164,17 @@
     CoroutineGThread *from = DO_UPCAST(CoroutineGThread, base, from_);
     CoroutineGThread *to = DO_UPCAST(CoroutineGThread, base, to_);
 
-    g_static_mutex_lock(&coroutine_lock);
+    g_mutex_lock(&coroutine_lock);
     from->runnable = false;
     from->action = action;
     to->runnable = true;
     to->action = action;
-    g_cond_broadcast(coroutine_cond);
+    g_cond_broadcast(&coroutine_cond);
 
     if (action != COROUTINE_TERMINATE) {
         coroutine_wait_runnable_locked(from);
     }
-    g_static_mutex_unlock(&coroutine_lock);
+    g_mutex_unlock(&coroutine_lock);
     return from->action;
 }
 
diff --git a/docs/ccid.txt b/docs/ccid.txt
index 83c174d..c7fda6d 100644
--- a/docs/ccid.txt
+++ b/docs/ccid.txt
@@ -47,6 +47,7 @@
 Configuring and building:
     ./configure --enable-smartcard && make
 
+
 3. Using ccid-card-emulated with hardware
 
 Assuming you have a working smartcard on the host with the current
@@ -54,19 +55,55 @@
 
     qemu -usb -device usb-ccid -device ccid-card-emulated
 
-4. Using ccid-card-emulated with certificates
 
-You must create the certificates. This is a one time process. We use NSS
-certificates:
+4. Using ccid-card-emulated with certificates stored in files
 
-    certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=cert1" -n cert1
+You must create the CA and card certificates. This is a one time process.
+We use NSS certificates:
+
+    mkdir fake-smartcard
+    cd fake-smartcard
+    certutil -N -d sql:$PWD
+    certutil -S -d sql:$PWD -s "CN=Fake Smart Card CA" -x -t TC,TC,TC -n fake-smartcard-ca
+    certutil -S -d sql:$PWD -t ,, -s "CN=John Doe" -n id-cert -c fake-smartcard-ca
+    certutil -S -d sql:$PWD -t ,, -s "CN=John Doe (signing)" --nsCertType smime -n signing-cert -c fake-smartcard-ca
+    certutil -S -d sql:$PWD -t ,, -s "CN=John Doe (encryption)" --nsCertType sslClient -n encryption-cert -c fake-smartcard-ca
 
 Note: you must have exactly three certificates.
 
-Assuming the current user can access the certificates (use certutil -L to
-verify), you can use the emulated card type with the certificates backend:
+You can use the emulated card type with the certificates backend:
 
-    qemu -usb -device usb-ccid -device ccid-card-emulated,backend=certificates,cert1=cert1,cert2=cert2,cert3=cert3
+    qemu -usb -device usb-ccid -device ccid-card-emulated,backend=certificates,db=sql:$PWD,cert1=id-cert,cert2=signing-cert,cert3=encryption-cert
+
+To use the certificates in the guest, export the CA certificate:
+
+    certutil -L -r -d sql:$PWD -o fake-smartcard-ca.cer -n fake-smartcard-ca
+
+and import it in the guest:
+
+    certutil -A -d /etc/pki/nssdb -i fake-smartcard-ca.cer -t TC,TC,TC -n fake-smartcard-ca
+
+In a Linux guest you can then use the CoolKey PKCS #11 module to access
+the card:
+
+    certutil -d /etc/pki/nssdb -L -h all
+
+It will prompt you for the PIN (which is the password you assigned to the
+certificate database early on), and then show you all three certificates
+together with the manually imported CA cert:
+
+    Certificate Nickname                        Trust Attributes
+    fake-smartcard-ca                           CT,C,C
+    John Doe:CAC ID Certificate                 u,u,u
+    John Doe:CAC Email Signature Certificate    u,u,u
+    John Doe:CAC Email Encryption Certificate   u,u,u
+
+If this does not happen, CoolKey is not installed or not registered with
+NSS.  Registration can be done from Firefox or the command line:
+
+    modutil -dbdir /etc/pki/nssdb -add "CAC Module" -libfile /usr/lib64/pkcs11/libcoolkeypk11.so
+    modutil -dbdir /etc/pki/nssdb -list
+
 
 5. Using ccid-card-passthru with client side hardware
 
@@ -74,15 +111,23 @@
 
     qemu -chardev socket,server,host=0.0.0.0,port=2001,id=ccid,nowait -usb -device usb-ccid -device ccid-card-passthru,chardev=ccid
 
-on the client run vscclient, built when you built the libcacard library:
-    libcacard/vscclient <qemu-host> 2001
+on the client run vscclient, built when you built QEMU:
+
+    vscclient <qemu-host> 2001
+
 
 6. Using ccid-card-passthru with client side certificates
 
-Run qemu as per #5, and run vscclient as follows:
-(Note: vscclient command line interface is in a state of change)
+This case is not particularly useful, but you can use it to debug
+your setup if #4 works but #5 does not.
 
-    libcacard/vscclient -e "db=\"/etc/pki/nssdb\" use_hw=no soft=(,Test,CAC,,cert1,cert2,cert3)" <qemu-host> 2001
+Follow instructions as per #4, except run QEMU and vscclient as follows:
+Run qemu as per #5, and run vscclient from the "fake-smartcard"
+directory as follows:
+
+    qemu -chardev socket,server,host=0.0.0.0,port=2001,id=ccid,nowait -usb -device usb-ccid -device ccid-card-passthru,chardev=ccid
+    vscclient -e "db=\"sql:$PWD\" use_hw=no soft=(,Test,CAC,,id-cert,signing-cert,encryption-cert)" <qemu-host> 2001
+
 
 7. Passthrough protocol scenario
 
@@ -126,10 +171,11 @@
 
 8. libcacard
 
-ccid-card-passthru and vscclient use libcacard as the card emulator.
-libcacard implements a completely virtual CAC (DoD standard for smart cards)
-compliant card and uses NSS to actually retrive certificates and do any
-encryption using the backend (real reader + card or file backed certificates).
+Both ccid-card-emulated and vscclient use libcacard as the card emulator.
+libcacard implements a completely virtual CAC (DoD standard for smart
+cards) compliant card and uses NSS to retrieve certificates and do
+any encryption.  The backend can then be a real reader and card, or
+certificates stored in files.
 
-For documentation of cac_card see README in libcacard subdirectory.
+For documentation of the library see docs/libcacard.txt.
 
diff --git a/dump.c b/dump.c
index e56b7cf..97d2c8d 100644
--- a/dump.c
+++ b/dump.c
@@ -90,8 +90,6 @@
     uint8_t *note_buf;          /* buffer for notes */
     size_t note_buf_offset;     /* the writing place in note_buf */
     uint32_t nr_cpus;           /* number of guest's cpu */
-    size_t page_size;           /* guest's page size */
-    uint32_t page_shift;        /* guest's page shift */
     uint64_t max_mapnr;         /* the biggest guest's phys-mem's number */
     size_t len_dump_bitmap;     /* the size of the place used to store
                                    dump_bitmap in vmcore */
@@ -711,27 +709,25 @@
 
 static int write_start_flat_header(int fd)
 {
-    uint8_t *buf;
-    MakedumpfileHeader mh;
+    MakedumpfileHeader *mh;
     int ret = 0;
 
-    memset(&mh, 0, sizeof(mh));
-    strncpy(mh.signature, MAKEDUMPFILE_SIGNATURE,
-            strlen(MAKEDUMPFILE_SIGNATURE));
+    QEMU_BUILD_BUG_ON(sizeof *mh > MAX_SIZE_MDF_HEADER);
+    mh = g_malloc0(MAX_SIZE_MDF_HEADER);
 
-    mh.type = cpu_to_be64(TYPE_FLAT_HEADER);
-    mh.version = cpu_to_be64(VERSION_FLAT_HEADER);
+    memcpy(mh->signature, MAKEDUMPFILE_SIGNATURE,
+           MIN(sizeof mh->signature, sizeof MAKEDUMPFILE_SIGNATURE));
 
-    buf = g_malloc0(MAX_SIZE_MDF_HEADER);
-    memcpy(buf, &mh, sizeof(mh));
+    mh->type = cpu_to_be64(TYPE_FLAT_HEADER);
+    mh->version = cpu_to_be64(VERSION_FLAT_HEADER);
 
     size_t written_size;
-    written_size = qemu_write_full(fd, buf, MAX_SIZE_MDF_HEADER);
+    written_size = qemu_write_full(fd, mh, MAX_SIZE_MDF_HEADER);
     if (written_size != MAX_SIZE_MDF_HEADER) {
         ret = -1;
     }
 
-    g_free(buf);
+    g_free(mh);
     return ret;
 }
 
@@ -808,7 +804,7 @@
 
     strncpy(dh->signature, KDUMP_SIGNATURE, strlen(KDUMP_SIGNATURE));
     dh->header_version = cpu_convert_to_target32(6, endian);
-    block_size = s->page_size;
+    block_size = TARGET_PAGE_SIZE;
     dh->block_size = cpu_convert_to_target32(block_size, endian);
     sub_hdr_size = sizeof(struct KdumpSubHeader32) + s->note_size;
     sub_hdr_size = DIV_ROUND_UP(sub_hdr_size, block_size);
@@ -915,7 +911,7 @@
 
     strncpy(dh->signature, KDUMP_SIGNATURE, strlen(KDUMP_SIGNATURE));
     dh->header_version = cpu_convert_to_target32(6, endian);
-    block_size = s->page_size;
+    block_size = TARGET_PAGE_SIZE;
     dh->block_size = cpu_convert_to_target32(block_size, endian);
     sub_hdr_size = sizeof(struct KdumpSubHeader64) + s->note_size;
     sub_hdr_size = DIV_ROUND_UP(sub_hdr_size, block_size);
@@ -1004,7 +1000,7 @@
 
 static int write_dump_header(DumpState *s)
 {
-    if (s->dump_info.d_machine == EM_386) {
+    if (s->dump_info.d_class == ELFCLASS32) {
         return create_header32(s);
     } else {
         return create_header64(s);
@@ -1086,9 +1082,9 @@
     if (!block) {
         block = QTAILQ_FIRST(&s->guest_phys_blocks.head);
         *blockptr = block;
-        assert(block->target_start % s->page_size == 0);
-        assert(block->target_end % s->page_size == 0);
-        *pfnptr = paddr_to_pfn(block->target_start, s->page_shift);
+        assert((block->target_start & ~TARGET_PAGE_MASK) == 0);
+        assert((block->target_end & ~TARGET_PAGE_MASK) == 0);
+        *pfnptr = paddr_to_pfn(block->target_start);
         if (bufptr) {
             *bufptr = block->host_addr;
         }
@@ -1096,10 +1092,10 @@
     }
 
     *pfnptr = *pfnptr + 1;
-    addr = pfn_to_paddr(*pfnptr, s->page_shift);
+    addr = pfn_to_paddr(*pfnptr);
 
     if ((addr >= block->target_start) &&
-        (addr + s->page_size <= block->target_end)) {
+        (addr + TARGET_PAGE_SIZE <= block->target_end)) {
         buf = block->host_addr + (addr - block->target_start);
     } else {
         /* the next page is in the next block */
@@ -1108,9 +1104,9 @@
         if (!block) {
             return false;
         }
-        assert(block->target_start % s->page_size == 0);
-        assert(block->target_end % s->page_size == 0);
-        *pfnptr = paddr_to_pfn(block->target_start, s->page_shift);
+        assert((block->target_start & ~TARGET_PAGE_MASK) == 0);
+        assert((block->target_end & ~TARGET_PAGE_MASK) == 0);
+        *pfnptr = paddr_to_pfn(block->target_start);
         buf = block->host_addr;
     }
 
@@ -1224,42 +1220,24 @@
 
 static size_t get_len_buf_out(size_t page_size, uint32_t flag_compress)
 {
-    size_t len_buf_out_zlib, len_buf_out_lzo, len_buf_out_snappy;
-    size_t len_buf_out;
+    switch (flag_compress) {
+    case DUMP_DH_COMPRESSED_ZLIB:
+        return compressBound(page_size);
 
-    /* init buf_out */
-    len_buf_out_zlib = len_buf_out_lzo = len_buf_out_snappy = 0;
-
-    /* buf size for zlib */
-    len_buf_out_zlib = compressBound(page_size);
-
-    /* buf size for lzo */
-#ifdef CONFIG_LZO
-    if (flag_compress & DUMP_DH_COMPRESSED_LZO) {
-        if (lzo_init() != LZO_E_OK) {
-            /* return 0 to indicate lzo is unavailable */
-            return 0;
-        }
-    }
-
-    /*
-     * LZO will expand incompressible data by a little amount. please check the
-     * following URL to see the expansion calculation:
-     * http://www.oberhumer.com/opensource/lzo/lzofaq.php
-     */
-    len_buf_out_lzo = page_size + page_size / 16 + 64 + 3;
-#endif
+    case DUMP_DH_COMPRESSED_LZO:
+        /*
+         * LZO will expand incompressible data by a little amount. Please check
+         * the following URL to see the expansion calculation:
+         * http://www.oberhumer.com/opensource/lzo/lzofaq.php
+         */
+        return page_size + page_size / 16 + 64 + 3;
 
 #ifdef CONFIG_SNAPPY
-    /* buf size for snappy */
-    len_buf_out_snappy = snappy_max_compressed_length(page_size);
+    case DUMP_DH_COMPRESSED_SNAPPY:
+        return snappy_max_compressed_length(page_size);
 #endif
-
-    /* get the biggest that can store all kinds of compressed page */
-    len_buf_out = MAX(len_buf_out_zlib,
-                      MAX(len_buf_out_lzo, len_buf_out_snappy));
-
-    return len_buf_out;
+    }
+    return 0;
 }
 
 /*
@@ -1294,11 +1272,8 @@
     prepare_data_cache(&page_data, s, offset_data);
 
     /* prepare buffer to store compressed data */
-    len_buf_out = get_len_buf_out(s->page_size, s->flag_compress);
-    if (len_buf_out == 0) {
-        dump_error(s, "dump: failed to get length of output buffer.\n");
-        goto out;
-    }
+    len_buf_out = get_len_buf_out(TARGET_PAGE_SIZE, s->flag_compress);
+    assert(len_buf_out != 0);
 
 #ifdef CONFIG_LZO
     wrkmem = g_malloc(LZO1X_1_MEM_COMPRESS);
@@ -1310,19 +1285,19 @@
      * init zero page's page_desc and page_data, because every zero page
      * uses the same page_data
      */
-    pd_zero.size = cpu_convert_to_target32(s->page_size, endian);
+    pd_zero.size = cpu_convert_to_target32(TARGET_PAGE_SIZE, endian);
     pd_zero.flags = cpu_convert_to_target32(0, endian);
     pd_zero.offset = cpu_convert_to_target64(offset_data, endian);
     pd_zero.page_flags = cpu_convert_to_target64(0, endian);
-    buf = g_malloc0(s->page_size);
-    ret = write_cache(&page_data, buf, s->page_size, false);
+    buf = g_malloc0(TARGET_PAGE_SIZE);
+    ret = write_cache(&page_data, buf, TARGET_PAGE_SIZE, false);
     g_free(buf);
     if (ret < 0) {
         dump_error(s, "dump: failed to write page data(zero page).\n");
         goto out;
     }
 
-    offset_data += s->page_size;
+    offset_data += TARGET_PAGE_SIZE;
 
     /*
      * dump memory to vmcore page by page. zero page will all be resided in the
@@ -1330,7 +1305,7 @@
      */
     while (get_next_page(&block_iter, &pfn_iter, &buf, s)) {
         /* check zero page */
-        if (is_zero_page(buf, s->page_size)) {
+        if (is_zero_page(buf, TARGET_PAGE_SIZE)) {
             ret = write_cache(&page_desc, &pd_zero, sizeof(PageDescriptor),
                               false);
             if (ret < 0) {
@@ -1351,8 +1326,9 @@
              */
              size_out = len_buf_out;
              if ((s->flag_compress & DUMP_DH_COMPRESSED_ZLIB) &&
-                    (compress2(buf_out, (uLongf *)&size_out, buf, s->page_size,
-                    Z_BEST_SPEED) == Z_OK) && (size_out < s->page_size)) {
+                 (compress2(buf_out, (uLongf *)&size_out, buf,
+                            TARGET_PAGE_SIZE, Z_BEST_SPEED) == Z_OK) &&
+                 (size_out < TARGET_PAGE_SIZE)) {
                 pd.flags = cpu_convert_to_target32(DUMP_DH_COMPRESSED_ZLIB,
                                                    endian);
                 pd.size  = cpu_convert_to_target32(size_out, endian);
@@ -1364,9 +1340,9 @@
                 }
 #ifdef CONFIG_LZO
             } else if ((s->flag_compress & DUMP_DH_COMPRESSED_LZO) &&
-                    (lzo1x_1_compress(buf, s->page_size, buf_out,
+                    (lzo1x_1_compress(buf, TARGET_PAGE_SIZE, buf_out,
                     (lzo_uint *)&size_out, wrkmem) == LZO_E_OK) &&
-                    (size_out < s->page_size)) {
+                    (size_out < TARGET_PAGE_SIZE)) {
                 pd.flags = cpu_convert_to_target32(DUMP_DH_COMPRESSED_LZO,
                                                    endian);
                 pd.size  = cpu_convert_to_target32(size_out, endian);
@@ -1379,9 +1355,9 @@
 #endif
 #ifdef CONFIG_SNAPPY
             } else if ((s->flag_compress & DUMP_DH_COMPRESSED_SNAPPY) &&
-                    (snappy_compress((char *)buf, s->page_size,
+                    (snappy_compress((char *)buf, TARGET_PAGE_SIZE,
                     (char *)buf_out, &size_out) == SNAPPY_OK) &&
-                    (size_out < s->page_size)) {
+                    (size_out < TARGET_PAGE_SIZE)) {
                 pd.flags = cpu_convert_to_target32(
                                         DUMP_DH_COMPRESSED_SNAPPY, endian);
                 pd.size  = cpu_convert_to_target32(size_out, endian);
@@ -1395,13 +1371,13 @@
             } else {
                 /*
                  * fall back to save in plaintext, size_out should be
-                 * assigned to s->page_size
+                 * assigned TARGET_PAGE_SIZE
                  */
                 pd.flags = cpu_convert_to_target32(0, endian);
-                size_out = s->page_size;
+                size_out = TARGET_PAGE_SIZE;
                 pd.size = cpu_convert_to_target32(size_out, endian);
 
-                ret = write_cache(&page_data, buf, s->page_size, false);
+                ret = write_cache(&page_data, buf, TARGET_PAGE_SIZE, false);
                 if (ret < 0) {
                     dump_error(s, "dump: failed to write page data.\n");
                     goto out;
@@ -1536,7 +1512,7 @@
     GuestPhysBlock *last_block;
 
     last_block = QTAILQ_LAST(&s->guest_phys_blocks.head, GuestPhysBlockHead);
-    s->max_mapnr = paddr_to_pfn(last_block->target_end, s->page_shift);
+    s->max_mapnr = paddr_to_pfn(last_block->target_end);
 }
 
 static int dump_init(DumpState *s, int fd, bool has_format,
@@ -1613,14 +1589,12 @@
     }
 
     s->nr_cpus = nr_cpus;
-    s->page_size = TARGET_PAGE_SIZE;
-    s->page_shift = ffs(s->page_size) - 1;
 
     get_max_mapnr(s);
 
     uint64_t tmp;
-    tmp = DIV_ROUND_UP(DIV_ROUND_UP(s->max_mapnr, CHAR_BIT), s->page_size);
-    s->len_dump_bitmap = tmp * s->page_size;
+    tmp = DIV_ROUND_UP(DIV_ROUND_UP(s->max_mapnr, CHAR_BIT), TARGET_PAGE_SIZE);
+    s->len_dump_bitmap = tmp * TARGET_PAGE_SIZE;
 
     /* init for kdump-compressed format */
     if (has_format && format != DUMP_GUEST_MEMORY_FORMAT_ELF) {
@@ -1630,6 +1604,12 @@
             break;
 
         case DUMP_GUEST_MEMORY_FORMAT_KDUMP_LZO:
+#ifdef CONFIG_LZO
+            if (lzo_init() != LZO_E_OK) {
+                error_setg(errp, "failed to initialize the LZO library");
+                goto cleanup;
+            }
+#endif
             s->flag_compress = DUMP_DH_COMPRESSED_LZO;
             break;
 
diff --git a/hmp-commands.hx b/hmp-commands.hx
index 2e462c0..5f1a677 100644
--- a/hmp-commands.hx
+++ b/hmp-commands.hx
@@ -335,6 +335,7 @@
         .params     = "tag|id",
         .help       = "restore a VM snapshot from its tag or id",
         .mhandler.cmd = do_loadvm,
+        .command_completion = loadvm_completion,
     },
 
 STEXI
@@ -350,6 +351,7 @@
         .params     = "tag|id",
         .help       = "delete a VM snapshot from its tag or id",
         .mhandler.cmd = do_delvm,
+        .command_completion = delvm_completion,
     },
 
 STEXI
@@ -852,6 +854,7 @@
         .params     = "device data",
         .help       = "Write to a ring buffer character device",
         .mhandler.cmd = hmp_ringbuf_write,
+        .command_completion = ringbuf_write_completion,
     },
 
 STEXI
@@ -868,6 +871,7 @@
         .params     = "device size",
         .help       = "Read from a ring buffer character device",
         .mhandler.cmd = hmp_ringbuf_read,
+        .command_completion = ringbuf_write_completion,
     },
 
 STEXI
@@ -973,6 +977,7 @@
         .params     = "capability state",
         .help       = "Enable/Disable the usage of a capability for migration",
         .mhandler.cmd = hmp_migrate_set_capability,
+        .command_completion = migrate_set_capability_completion,
     },
 
 STEXI
@@ -1206,9 +1211,10 @@
     {
         .name       = "host_net_add",
         .args_type  = "device:s,opts:s?",
-        .params     = "tap|user|socket|vde|netmap|dump [options]",
+        .params     = "tap|user|socket|vde|netmap|bridge|dump [options]",
         .help       = "add host VLAN client",
         .mhandler.cmd = net_host_device_add,
+        .command_completion = host_net_add_completion,
     },
 
 STEXI
@@ -1223,6 +1229,7 @@
         .params     = "vlan_id name",
         .help       = "remove host VLAN client",
         .mhandler.cmd = net_host_device_remove,
+        .command_completion = host_net_remove_completion,
     },
 
 STEXI
@@ -1357,6 +1364,7 @@
         .params     = "[reset|shutdown|poweroff|pause|debug|none]",
         .help       = "change watchdog action",
         .mhandler.cmd = do_watchdog_action,
+        .command_completion = watchdog_action_completion,
     },
 
 STEXI
diff --git a/hmp.h b/hmp.h
index aba59e9..2d9b0a2 100644
--- a/hmp.h
+++ b/hmp.h
@@ -103,5 +103,16 @@
 void set_link_completion(ReadLineState *rs, int nb_args, const char *str);
 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str);
 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str);
+void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str);
+void ringbuf_read_completion(ReadLineState *rs, int nb_args, const char *str);
+void watchdog_action_completion(ReadLineState *rs, int nb_args,
+                                const char *str);
+void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
+                                       const char *str);
+void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str);
+void host_net_remove_completion(ReadLineState *rs, int nb_args,
+                                const char *str);
+void delvm_completion(ReadLineState *rs, int nb_args, const char *str);
+void loadvm_completion(ReadLineState *rs, int nb_args, const char *str);
 
 #endif
diff --git a/hw/virtio/vhost.c b/hw/virtio/vhost.c
index 9e336ad..f62cfaf 100644
--- a/hw/virtio/vhost.c
+++ b/hw/virtio/vhost.c
@@ -41,7 +41,6 @@
 
     for (;from < to; ++from) {
         vhost_log_chunk_t log;
-        int bit;
         /* We first check with non-atomic: much cheaper,
          * and we expect non-dirty to be the common case. */
         if (!*from) {
@@ -51,12 +50,11 @@
         /* Data must be read atomically. We don't really need barrier semantics
          * but it's easier to use atomic_* than roll our own. */
         log = atomic_xchg(from, 0);
-        while ((bit = sizeof(log) > sizeof(int) ?
-                ffsll(log) : ffs(log))) {
+        while (log) {
+            int bit = ctzl(log);
             hwaddr page_addr;
             hwaddr section_offset;
             hwaddr mr_offset;
-            bit -= 1;
             page_addr = addr + bit * VHOST_LOG_PAGE;
             section_offset = page_addr - section->offset_within_address_space;
             mr_offset = section_offset + section->offset_within_region;
diff --git a/include/exec/ram_addr.h b/include/exec/ram_addr.h
index 2edfa96..b94de02 100644
--- a/include/exec/ram_addr.h
+++ b/include/exec/ram_addr.h
@@ -117,7 +117,7 @@
             if (bitmap[i] != 0) {
                 c = leul_to_cpu(bitmap[i]);
                 do {
-                    j = ffsl(c) - 1;
+                    j = ctzl(c);
                     c &= ~(1ul << j);
                     page_number = (i * HOST_LONG_BITS + j) * hpratio;
                     addr = page_number * TARGET_PAGE_SIZE;
diff --git a/include/glib-compat.h b/include/glib-compat.h
index 1280fb2..4ae0671 100644
--- a/include/glib-compat.h
+++ b/include/glib-compat.h
@@ -5,6 +5,8 @@
  *
  * Authors:
  *  Anthony Liguori   <aliguori@us.ibm.com>
+ *  Michael Tokarev   <mjt@tls.msk.ru>
+ *  Paolo Bonzini     <pbonzini@redhat.com>
  *
  * This work is licensed under the terms of the GNU GPL, version 2 or later.
  * See the COPYING file in the top-level directory.
@@ -43,4 +45,121 @@
 }
 #endif
 
+#if !GLIB_CHECK_VERSION(2, 31, 0)
+/* before glib-2.31, GMutex and GCond was dynamic-only (there was a separate
+ * GStaticMutex, but it didn't work with condition variables).
+ *
+ * Our implementation uses GOnce to fake a static implementation that does
+ * not require separate initialization.
+ * We need to rename the types to avoid passing our CompatGMutex/CompatGCond
+ * by mistake to a function that expects GMutex/GCond.  However, for ease
+ * of use we keep the GLib function names.  GLib uses macros for the
+ * implementation, we use inline functions instead and undefine the macros.
+ */
+
+typedef struct CompatGMutex {
+    GOnce once;
+} CompatGMutex;
+
+typedef struct CompatGCond {
+    GOnce once;
+} CompatGCond;
+
+static inline gpointer do_g_mutex_new(gpointer unused)
+{
+    return (gpointer) g_mutex_new();
+}
+
+static inline void g_mutex_init(CompatGMutex *mutex)
+{
+    mutex->once = (GOnce) G_ONCE_INIT;
+}
+
+static inline void g_mutex_clear(CompatGMutex *mutex)
+{
+    assert(mutex->once.status != G_ONCE_STATUS_PROGRESS);
+    if (mutex->once.retval) {
+        g_mutex_free((GMutex *) mutex->once.retval);
+    }
+    mutex->once = (GOnce) G_ONCE_INIT;
+}
+
+static inline void (g_mutex_lock)(CompatGMutex *mutex)
+{
+    g_once(&mutex->once, do_g_mutex_new, NULL);
+    g_mutex_lock((GMutex *) mutex->once.retval);
+}
+#undef g_mutex_lock
+
+static inline gboolean (g_mutex_trylock)(CompatGMutex *mutex)
+{
+    g_once(&mutex->once, do_g_mutex_new, NULL);
+    return g_mutex_trylock((GMutex *) mutex->once.retval);
+}
+#undef g_mutex_trylock
+
+
+static inline void (g_mutex_unlock)(CompatGMutex *mutex)
+{
+    g_mutex_unlock((GMutex *) mutex->once.retval);
+}
+#undef g_mutex_unlock
+
+static inline gpointer do_g_cond_new(gpointer unused)
+{
+    return (gpointer) g_cond_new();
+}
+
+static inline void g_cond_init(CompatGCond *cond)
+{
+    cond->once = (GOnce) G_ONCE_INIT;
+}
+
+static inline void g_cond_clear(CompatGCond *cond)
+{
+    assert(cond->once.status != G_ONCE_STATUS_PROGRESS);
+    if (cond->once.retval) {
+        g_cond_free((GCond *) cond->once.retval);
+    }
+    cond->once = (GOnce) G_ONCE_INIT;
+}
+
+static inline void (g_cond_wait)(CompatGCond *cond, CompatGMutex *mutex)
+{
+    assert(mutex->once.status != G_ONCE_STATUS_PROGRESS);
+    g_once(&cond->once, do_g_cond_new, NULL);
+    g_cond_wait((GCond *) cond->once.retval, (GMutex *) mutex->once.retval);
+}
+#undef g_cond_wait
+
+static inline void (g_cond_broadcast)(CompatGCond *cond)
+{
+    g_once(&cond->once, do_g_cond_new, NULL);
+    g_cond_broadcast((GCond *) cond->once.retval);
+}
+#undef g_cond_broadcast
+
+static inline void (g_cond_signal)(CompatGCond *cond)
+{
+    g_once(&cond->once, do_g_cond_new, NULL);
+    g_cond_signal((GCond *) cond->once.retval);
+}
+#undef g_cond_signal
+
+
+/* before 2.31 there was no g_thread_new() */
+static inline GThread *g_thread_new(const char *name,
+                                    GThreadFunc func, gpointer data)
+{
+    GThread *thread = g_thread_create(func, data, TRUE, NULL);
+    if (!thread) {
+        g_error("creating thread");
+    }
+    return thread;
+}
+#else
+#define CompatGMutex GMutex
+#define CompatGCond GCond
+#endif /* glib 2.31 */
+
 #endif
diff --git a/include/net/net.h b/include/net/net.h
index 8166345..8b189da 100644
--- a/include/net/net.h
+++ b/include/net/net.h
@@ -177,6 +177,7 @@
 extern int nb_nics;
 extern NICInfo nd_table[MAX_NICS];
 extern int default_net;
+extern const char *host_net_devices[];
 
 /* from net.c */
 extern const char *legacy_tftp_prefix;
diff --git a/include/sysemu/char.h b/include/sysemu/char.h
index b81a6ff..7f5eeb3 100644
--- a/include/sysemu/char.h
+++ b/include/sysemu/char.h
@@ -286,9 +286,8 @@
 void qemu_chr_be_generic_open(CharDriverState *s);
 void qemu_chr_accept_input(CharDriverState *s);
 int qemu_chr_add_client(CharDriverState *s, int fd);
-void qemu_chr_info_print(Monitor *mon, const QObject *ret_data);
-void qemu_chr_info(Monitor *mon, QObject **ret_data);
 CharDriverState *qemu_chr_find(const char *name);
+bool chr_is_ringbuf(const CharDriverState *chr);
 
 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename);
 
diff --git a/include/sysemu/dump.h b/include/sysemu/dump.h
index efab7a3..12af557 100644
--- a/include/sysemu/dump.h
+++ b/include/sysemu/dump.h
@@ -22,10 +22,10 @@
 
 #define ARCH_PFN_OFFSET             (0)
 
-#define paddr_to_pfn(X, page_shift) \
-    (((unsigned long long)(X) >> (page_shift)) - ARCH_PFN_OFFSET)
-#define pfn_to_paddr(X, page_shift) \
-    (((unsigned long long)(X) + ARCH_PFN_OFFSET) << (page_shift))
+#define paddr_to_pfn(X) \
+    (((unsigned long long)(X) >> TARGET_PAGE_BITS) - ARCH_PFN_OFFSET)
+#define pfn_to_paddr(X) \
+    (((unsigned long long)(X) + ARCH_PFN_OFFSET) << TARGET_PAGE_BITS)
 
 /*
  * flag for compressed format
diff --git a/libcacard/Makefile b/libcacard/Makefile
index 881b222..0e7903f 100644
--- a/libcacard/Makefile
+++ b/libcacard/Makefile
@@ -3,13 +3,7 @@
 TOOLS += vscclient$(EXESUF)
 
 # objects linked into a shared library, built with libtool with -fPIC if required
-libcacard-obj-y = $(stub-obj-y) $(libcacard-y)
-libcacard-obj-y += util/osdep.o util/cutils.o util/qemu-timer-common.o
-libcacard-obj-y += util/error.o util/qemu-error.o
-libcacard-obj-$(CONFIG_WIN32) += util/oslib-win32.o util/qemu-thread-win32.o
-libcacard-obj-$(CONFIG_POSIX) += util/oslib-posix.o util/qemu-thread-posix.o
-libcacard-obj-y += $(filter trace/%, $(util-obj-y))
-
+libcacard-obj-y = $(libcacard-y)
 libcacard-lobj-y=$(patsubst %.o,%.lo,$(libcacard-obj-y))
 
 # libtool will build the .o files, too
@@ -24,7 +18,7 @@
 # Rules for building libcacard standalone library
 
 libcacard.la: LDFLAGS += -rpath $(libdir) -no-undefined \
-	-export-syms $(SRC_PATH)/libcacard/libcacard.syms
+	-export-symbols $(SRC_PATH)/libcacard/libcacard.syms
 libcacard.la: $(libcacard-lobj-y)
 	$(call LINK,$^)
 
diff --git a/libcacard/event.c b/libcacard/event.c
index a2e6c7d..4c551e4 100644
--- a/libcacard/event.c
+++ b/libcacard/event.c
@@ -6,7 +6,6 @@
  */
 
 #include "qemu-common.h"
-#include "qemu/thread.h"
 
 #include "vcard.h"
 #include "vreader.h"
@@ -43,13 +42,11 @@
 
 static VEvent *vevent_queue_head;
 static VEvent *vevent_queue_tail;
-static QemuMutex vevent_queue_lock;
-static QemuCond vevent_queue_condition;
+static CompatGMutex vevent_queue_lock;
+static CompatGCond vevent_queue_condition;
 
 void vevent_queue_init(void)
 {
-    qemu_mutex_init(&vevent_queue_lock);
-    qemu_cond_init(&vevent_queue_condition);
     vevent_queue_head = vevent_queue_tail = NULL;
 }
 
@@ -57,7 +54,7 @@
 vevent_queue_vevent(VEvent *vevent)
 {
     vevent->next = NULL;
-    qemu_mutex_lock(&vevent_queue_lock);
+    g_mutex_lock(&vevent_queue_lock);
     if (vevent_queue_head) {
         assert(vevent_queue_tail);
         vevent_queue_tail->next = vevent;
@@ -65,8 +62,8 @@
         vevent_queue_head = vevent;
     }
     vevent_queue_tail = vevent;
-    qemu_cond_signal(&vevent_queue_condition);
-    qemu_mutex_unlock(&vevent_queue_lock);
+    g_cond_signal(&vevent_queue_condition);
+    g_mutex_unlock(&vevent_queue_lock);
 }
 
 /* must have lock */
@@ -86,11 +83,11 @@
 {
     VEvent *vevent;
 
-    qemu_mutex_lock(&vevent_queue_lock);
+    g_mutex_lock(&vevent_queue_lock);
     while ((vevent = vevent_dequeue_vevent()) == NULL) {
-        qemu_cond_wait(&vevent_queue_condition, &vevent_queue_lock);
+        g_cond_wait(&vevent_queue_condition, &vevent_queue_lock);
     }
-    qemu_mutex_unlock(&vevent_queue_lock);
+    g_mutex_unlock(&vevent_queue_lock);
     return vevent;
 }
 
@@ -98,9 +95,9 @@
 {
     VEvent *vevent;
 
-    qemu_mutex_lock(&vevent_queue_lock);
+    g_mutex_lock(&vevent_queue_lock);
     vevent = vevent_dequeue_vevent();
-    qemu_mutex_unlock(&vevent_queue_lock);
+    g_mutex_unlock(&vevent_queue_lock);
     return vevent;
 }
 
diff --git a/libcacard/vreader.c b/libcacard/vreader.c
index 9f42f0f..0315dd8 100644
--- a/libcacard/vreader.c
+++ b/libcacard/vreader.c
@@ -9,10 +9,8 @@
 #undef G_LOG_DOMAIN
 #endif
 #define G_LOG_DOMAIN "libcacard"
-#include <glib.h>
 
 #include "qemu-common.h"
-#include "qemu/thread.h"
 
 #include "vcard.h"
 #include "vcard_emul.h"
@@ -28,7 +26,7 @@
     VCard *card;
     char *name;
     vreader_id_t id;
-    QemuMutex lock;
+    CompatGMutex lock;
     VReaderEmul  *reader_private;
     VReaderEmulFree reader_private_free;
 };
@@ -97,13 +95,13 @@
 static inline void
 vreader_lock(VReader *reader)
 {
-    qemu_mutex_lock(&reader->lock);
+    g_mutex_lock(&reader->lock);
 }
 
 static inline void
 vreader_unlock(VReader *reader)
 {
-    qemu_mutex_unlock(&reader->lock);
+    g_mutex_unlock(&reader->lock);
 }
 
 /*
@@ -116,7 +114,7 @@
     VReader *reader;
 
     reader = g_new(VReader, 1);
-    qemu_mutex_init(&reader->lock);
+    g_mutex_init(&reader->lock);
     reader->reference_count = 1;
     reader->name = g_strdup(name);
     reader->card = NULL;
@@ -152,6 +150,7 @@
         return;
     }
     vreader_unlock(reader);
+    g_mutex_clear(&reader->lock);
     if (reader->card) {
         vcard_free(reader->card);
     }
@@ -402,25 +401,24 @@
 }
 
 static VReaderList *vreader_list;
-static QemuMutex vreader_list_mutex;
+static CompatGMutex vreader_list_mutex;
 
 static void
 vreader_list_init(void)
 {
     vreader_list = vreader_list_new();
-    qemu_mutex_init(&vreader_list_mutex);
 }
 
 static void
 vreader_list_lock(void)
 {
-    qemu_mutex_lock(&vreader_list_mutex);
+    g_mutex_lock(&vreader_list_mutex);
 }
 
 static void
 vreader_list_unlock(void)
 {
-    qemu_mutex_unlock(&vreader_list_mutex);
+    g_mutex_unlock(&vreader_list_mutex);
 }
 
 static VReaderList *
diff --git a/libcacard/vscclient.c b/libcacard/vscclient.c
index 6693900..ab9b2b8 100644
--- a/libcacard/vscclient.c
+++ b/libcacard/vscclient.c
@@ -12,12 +12,10 @@
 
 #ifndef _WIN32
 #include <netdb.h>
+#define closesocket(x) close(x)
 #endif
-#include <glib.h>
 
 #include "qemu-common.h"
-#include "qemu/thread.h"
-#include "qemu/sockets.h"
 
 #include "vscard_common.h"
 
@@ -54,7 +52,7 @@
 
 static GIOChannel *channel_socket;
 static GByteArray *socket_to_send;
-static QemuMutex socket_to_send_lock;
+static CompatGMutex socket_to_send_lock;
 static guint socket_tag;
 
 static void
@@ -103,7 +101,7 @@
 ) {
     VSCMsgHeader mhHeader;
 
-    qemu_mutex_lock(&socket_to_send_lock);
+    g_mutex_lock(&socket_to_send_lock);
 
     if (verbose > 10) {
         printf("sending type=%d id=%u, len =%u (0x%x)\n",
@@ -117,18 +115,18 @@
     g_byte_array_append(socket_to_send, (guint8 *)msg, length);
     g_idle_add(socket_prepare_sending, NULL);
 
-    qemu_mutex_unlock(&socket_to_send_lock);
+    g_mutex_unlock(&socket_to_send_lock);
 
     return 0;
 }
 
 static VReader *pending_reader;
-static QemuMutex pending_reader_lock;
-static QemuCond pending_reader_condition;
+static CompatGMutex pending_reader_lock;
+static CompatGCond pending_reader_condition;
 
 #define MAX_ATR_LEN 40
-static void *
-event_thread(void *arg)
+static gpointer
+event_thread(gpointer arg)
 {
     unsigned char atr[MAX_ATR_LEN];
     int atr_len;
@@ -149,20 +147,20 @@
             /* ignore events from readers qemu has rejected */
             /* if qemu is still deciding on this reader, wait to see if need to
              * forward this event */
-            qemu_mutex_lock(&pending_reader_lock);
+            g_mutex_lock(&pending_reader_lock);
             if (!pending_reader || (pending_reader != event->reader)) {
                 /* wasn't for a pending reader, this reader has already been
                  * rejected by qemu */
-                qemu_mutex_unlock(&pending_reader_lock);
+                g_mutex_unlock(&pending_reader_lock);
                 vevent_delete(event);
                 continue;
             }
             /* this reader hasn't been told its status from qemu yet, wait for
              * that status */
             while (pending_reader != NULL) {
-                qemu_cond_wait(&pending_reader_condition, &pending_reader_lock);
+                g_cond_wait(&pending_reader_condition, &pending_reader_lock);
             }
-            qemu_mutex_unlock(&pending_reader_lock);
+            g_mutex_unlock(&pending_reader_lock);
             /* now recheck the id */
             reader_id = vreader_get_id(event->reader);
             if (reader_id == VSCARD_UNDEFINED_READER_ID) {
@@ -178,12 +176,12 @@
             /* wait until qemu has responded to our first reader insert
              * before we send a second. That way we won't confuse the responses
              * */
-            qemu_mutex_lock(&pending_reader_lock);
+            g_mutex_lock(&pending_reader_lock);
             while (pending_reader != NULL) {
-                qemu_cond_wait(&pending_reader_condition, &pending_reader_lock);
+                g_cond_wait(&pending_reader_condition, &pending_reader_lock);
             }
             pending_reader = vreader_reference(event->reader);
-            qemu_mutex_unlock(&pending_reader_lock);
+            g_mutex_unlock(&pending_reader_lock);
             reader_name = vreader_get_name(event->reader);
             if (verbose > 10) {
                 printf(" READER INSERT: %s\n", reader_name);
@@ -246,7 +244,6 @@
     int num_capabilities =
         1 + ((mhHeader->length - sizeof(VSCMsgInit)) / sizeof(uint32_t));
     int i;
-    QemuThread thread_id;
 
     incoming->version = ntohl(incoming->version);
     if (incoming->version != VSCARD_VERSION) {
@@ -269,7 +266,7 @@
     send_msg(VSC_ReaderRemove, VSCARD_MINIMAL_READER_ID, NULL, 0);
     /* launch the event_thread. This will trigger reader adds for all the
      * existing readers */
-    qemu_thread_create(&thread_id, "vsc/event", event_thread, NULL, 0);
+    g_thread_new("vsc/event", event_thread, NULL);
     return 0;
 }
 
@@ -379,26 +376,26 @@
         case VSC_Error:
             error_msg = (VSCMsgError *) pbSendBuffer;
             if (error_msg->code == VSC_SUCCESS) {
-                qemu_mutex_lock(&pending_reader_lock);
+                g_mutex_lock(&pending_reader_lock);
                 if (pending_reader) {
                     vreader_set_id(pending_reader, mhHeader.reader_id);
                     vreader_free(pending_reader);
                     pending_reader = NULL;
-                    qemu_cond_signal(&pending_reader_condition);
+                    g_cond_signal(&pending_reader_condition);
                 }
-                qemu_mutex_unlock(&pending_reader_lock);
+                g_mutex_unlock(&pending_reader_lock);
                 break;
             }
             printf("warning: qemu refused to add reader\n");
             if (error_msg->code == VSC_CANNOT_ADD_MORE_READERS) {
                 /* clear pending reader, qemu can't handle any more */
-                qemu_mutex_lock(&pending_reader_lock);
+                g_mutex_lock(&pending_reader_lock);
                 if (pending_reader) {
                     pending_reader = NULL;
                     /* make sure the event loop doesn't hang */
-                    qemu_cond_signal(&pending_reader_condition);
+                    g_cond_signal(&pending_reader_condition);
                 }
-                qemu_mutex_unlock(&pending_reader_lock);
+                g_mutex_unlock(&pending_reader_lock);
             }
             break;
         case VSC_Init:
@@ -601,7 +598,7 @@
     struct addrinfo *server;
     int ret, sock;
 
-    sock = qemu_socket(AF_INET, SOCK_STREAM, 0);
+    sock = socket(AF_INET, SOCK_STREAM, 0);
     if (sock < 0) {
         /* Error */
         fprintf(stderr, "Error opening socket!\n");
@@ -654,8 +651,20 @@
     int cert_count = 0;
     int c, sock;
 
-    if (socket_init() != 0)
+#ifdef _WIN32
+    WSADATA Data;
+
+    if (WSAStartup(MAKEWORD(2, 2), &Data) != 0) {
+        c = WSAGetLastError();
+        fprintf(stderr, "WSAStartup: %d\n", c);
         return 1;
+    }
+#endif
+#if !GLIB_CHECK_VERSION(2, 31, 0)
+    if (!g_thread_supported()) {
+         g_thread_init(NULL);
+    }
+#endif
 
     while ((c = getopt(argc, argv, "c:e:pd:")) != -1) {
         switch (c) {
@@ -722,13 +731,8 @@
     }
 
     socket_to_send = g_byte_array_new();
-    qemu_mutex_init(&socket_to_send_lock);
-    qemu_mutex_init(&pending_reader_lock);
-    qemu_cond_init(&pending_reader_condition);
-
     vcard_emul_init(command_line_options);
-
-    loop = g_main_loop_new(NULL, true);
+    loop = g_main_loop_new(NULL, TRUE);
 
     printf("> ");
     fflush(stdout);
diff --git a/monitor.c b/monitor.c
index 0565816..ee9390f 100644
--- a/monitor.c
+++ b/monitor.c
@@ -70,6 +70,7 @@
 #include "qmp-commands.h"
 #include "hmp.h"
 #include "qemu/thread.h"
+#include "block/qapi.h"
 
 /* for pic/irq_info */
 #if defined(TARGET_SPARC)
@@ -4412,6 +4413,45 @@
     qapi_free_ChardevInfoList(start);
 }
 
+static void ringbuf_completion(ReadLineState *rs, const char *str)
+{
+    size_t len;
+    ChardevInfoList *list, *start;
+
+    len = strlen(str);
+    readline_set_completion_index(rs, len);
+
+    start = list = qmp_query_chardev(NULL);
+    while (list) {
+        ChardevInfo *chr_info = list->value;
+
+        if (!strncmp(chr_info->label, str, len)) {
+            CharDriverState *chr = qemu_chr_find(chr_info->label);
+            if (chr && chr_is_ringbuf(chr)) {
+                readline_add_completion(rs, chr_info->label);
+            }
+        }
+        list = list->next;
+    }
+    qapi_free_ChardevInfoList(start);
+}
+
+void ringbuf_read_completion(ReadLineState *rs, int nb_args, const char *str)
+{
+    if (nb_args != 2) {
+        return;
+    }
+    ringbuf_completion(rs, str);
+}
+
+void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
+{
+    if (nb_args != 2) {
+        return;
+    }
+    ringbuf_completion(rs, str);
+}
+
 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
 {
     size_t len;
@@ -4520,6 +4560,142 @@
     }
 }
 
+void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
+{
+    if (nb_args != 2) {
+        return;
+    }
+    readline_set_completion_index(rs, strlen(str));
+    add_completion_option(rs, str, "reset");
+    add_completion_option(rs, str, "shutdown");
+    add_completion_option(rs, str, "poweroff");
+    add_completion_option(rs, str, "pause");
+    add_completion_option(rs, str, "debug");
+    add_completion_option(rs, str, "none");
+}
+
+void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
+                                       const char *str)
+{
+    size_t len;
+
+    len = strlen(str);
+    readline_set_completion_index(rs, len);
+    if (nb_args == 2) {
+        int i;
+        for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
+            const char *name = MigrationCapability_lookup[i];
+            if (!strncmp(str, name, len)) {
+                readline_add_completion(rs, name);
+            }
+        }
+    } else if (nb_args == 3) {
+        add_completion_option(rs, str, "on");
+        add_completion_option(rs, str, "off");
+    }
+}
+
+void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
+{
+    int i;
+    size_t len;
+    if (nb_args != 2) {
+        return;
+    }
+    len = strlen(str);
+    readline_set_completion_index(rs, len);
+    for (i = 0; host_net_devices[i]; i++) {
+        if (!strncmp(host_net_devices[i], str, len)) {
+            readline_add_completion(rs, host_net_devices[i]);
+        }
+    }
+}
+
+void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
+{
+    NetClientState *ncs[255];
+    int count, i, len;
+
+    len = strlen(str);
+    readline_set_completion_index(rs, len);
+    if (nb_args == 2) {
+        count = qemu_find_net_clients_except(NULL, ncs,
+                                             NET_CLIENT_OPTIONS_KIND_NONE, 255);
+        for (i = 0; i < count; i++) {
+            int id;
+            char name[16];
+
+            if (net_hub_id_for_client(ncs[i], &id)) {
+                continue;
+            }
+            snprintf(name, sizeof(name), "%d", id);
+            if (!strncmp(str, name, len)) {
+                readline_add_completion(rs, name);
+            }
+        }
+        return;
+    } else if (nb_args == 3) {
+        count = qemu_find_net_clients_except(NULL, ncs,
+                                             NET_CLIENT_OPTIONS_KIND_NIC, 255);
+        for (i = 0; i < count; i++) {
+            const char *name;
+
+            name = ncs[i]->name;
+            if (!strncmp(str, name, len)) {
+                readline_add_completion(rs, name);
+            }
+        }
+        return;
+    }
+}
+
+static void vm_completion(ReadLineState *rs, const char *str)
+{
+    size_t len;
+    BlockDriverState *bs = NULL;
+
+    len = strlen(str);
+    readline_set_completion_index(rs, len);
+    while ((bs = bdrv_next(bs))) {
+        SnapshotInfoList *snapshots, *snapshot;
+
+        if (!bdrv_can_snapshot(bs)) {
+            continue;
+        }
+        if (bdrv_query_snapshot_info_list(bs, &snapshots, NULL)) {
+            continue;
+        }
+        snapshot = snapshots;
+        while (snapshot) {
+            char *completion = snapshot->value->name;
+            if (!strncmp(str, completion, len)) {
+                readline_add_completion(rs, completion);
+            }
+            completion = snapshot->value->id;
+            if (!strncmp(str, completion, len)) {
+                readline_add_completion(rs, completion);
+            }
+            snapshot = snapshot->next;
+        }
+        qapi_free_SnapshotInfoList(snapshots);
+    }
+
+}
+
+void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
+{
+    if (nb_args == 2) {
+        vm_completion(rs, str);
+    }
+}
+
+void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
+{
+    if (nb_args == 2) {
+        vm_completion(rs, str);
+    }
+}
+
 static void monitor_find_completion_by_table(Monitor *mon,
                                              const mon_cmd_t *cmd_table,
                                              char **args,
diff --git a/net/net.c b/net/net.c
index 0ff2e40..6344160 100644
--- a/net/net.c
+++ b/net/net.c
@@ -49,6 +49,22 @@
 
 static QTAILQ_HEAD(, NetClientState) net_clients;
 
+const char *host_net_devices[] = {
+    "tap",
+    "socket",
+    "dump",
+#ifdef CONFIG_NET_BRIDGE
+    "bridge",
+#endif
+#ifdef CONFIG_SLIRP
+    "user",
+#endif
+#ifdef CONFIG_VDE
+    "vde",
+#endif
+    NULL,
+};
+
 int default_net = 1;
 
 /***********************************************************/
@@ -897,21 +913,11 @@
 static int net_host_check_device(const char *device)
 {
     int i;
-    const char *valid_param_list[] = { "tap", "socket", "dump"
-#ifdef CONFIG_NET_BRIDGE
-                                       , "bridge"
-#endif
-#ifdef CONFIG_SLIRP
-                                       ,"user"
-#endif
-#ifdef CONFIG_VDE
-                                       ,"vde"
-#endif
-    };
-    for (i = 0; i < ARRAY_SIZE(valid_param_list); i++) {
-        if (!strncmp(valid_param_list[i], device,
-                     strlen(valid_param_list[i])))
+    for (i = 0; host_net_devices[i]; i++) {
+        if (!strncmp(host_net_devices[i], device,
+                     strlen(host_net_devices[i]))) {
             return 1;
+        }
     }
 
     return 0;
diff --git a/qemu-char.c b/qemu-char.c
index 17b476e..4c04bbc 100644
--- a/qemu-char.c
+++ b/qemu-char.c
@@ -2849,7 +2849,7 @@
     return NULL;
 }
 
-static bool chr_is_ringbuf(const CharDriverState *chr)
+bool chr_is_ringbuf(const CharDriverState *chr)
 {
     return chr->chr_write == ringbuf_chr_write;
 }
diff --git a/qobject/json-parser.c b/qobject/json-parser.c
index e46c264..4288267 100644
--- a/qobject/json-parser.c
+++ b/qobject/json-parser.c
@@ -423,7 +423,6 @@
     if (!token_is_operator(token, '{')) {
         goto out;
     }
-    token = NULL;
 
     dict = qdict_new();
 
@@ -449,7 +448,6 @@
                 parse_error(ctxt, token, "expected separator in dict");
                 goto out;
             }
-            token = NULL;
 
             if (parse_pair(ctxt, dict, ap) == -1) {
                 goto out;
@@ -461,10 +459,8 @@
                 goto out;
             }
         }
-        token = NULL;
     } else {
-        token = parser_context_pop_token(ctxt);
-        token = NULL;
+        (void)parser_context_pop_token(ctxt);
     }
 
     return QOBJECT(dict);
@@ -487,10 +483,8 @@
     }
 
     if (!token_is_operator(token, '[')) {
-        token = NULL;
         goto out;
     }
-    token = NULL;
 
     list = qlist_new();
 
@@ -523,8 +517,6 @@
                 goto out;
             }
 
-            token = NULL;
-
             obj = parse_value(ctxt, ap);
             if (obj == NULL) {
                 parse_error(ctxt, token, "expecting value");
@@ -539,11 +531,8 @@
                 goto out;
             }
         }
-
-        token = NULL;
     } else {
-        token = parser_context_pop_token(ctxt);
-        token = NULL;
+        (void)parser_context_pop_token(ctxt);
     }
 
     return QOBJECT(list);
diff --git a/rules.mak b/rules.mak
index b12d312..dde8e00 100644
--- a/rules.mak
+++ b/rules.mak
@@ -22,9 +22,7 @@
 # Same as -I$(SRC_PATH) -I., but for the nested source/object directories
 QEMU_INCLUDES += -I$(<D) -I$(@D)
 
-maybe-add = $(filter-out $1, $2) $1
-extract-libs = $(strip $(sort $(foreach o,$1,$($o-libs))) \
-                  $(foreach o,$(call expand-objs,$1),$($o-libs)))
+extract-libs = $(strip $(sort $(foreach o,$1,$($o-libs))))
 expand-objs = $(strip $(sort $(filter %.o,$1)) \
                   $(foreach o,$(filter %.mo,$1),$($o-objs)) \
                   $(filter-out %.o %.mo,$1))
@@ -39,9 +37,8 @@
 LINKPROG = $(or $(CXX),$(CC))
 
 ifeq ($(LIBTOOL),)
-LINK = $(call quiet-command,$(LINKPROG) $(QEMU_CFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ \
-       $(call expand-objs,$1) $(version-obj-y) \
-       $(call extract-libs,$1) $(LIBS),"  LINK  $(TARGET_DIR)$@")
+LINK = $(call quiet-command, $(LINKPROG) $(QEMU_CFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ \
+       $1 $(version-obj-y) $(call extract-libs,$1) $(LIBS),"  LINK  $(TARGET_DIR)$@")
 else
 LIBTOOL += $(if $(V),,--quiet)
 %.lo: %.c
@@ -53,8 +50,7 @@
 
 LINK = $(call quiet-command,\
        $(if $(filter %.lo %.la,$1),$(LIBTOOL) --mode=link --tag=CC \
-       )$(LINKPROG) $(QEMU_CFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ \
-       $(call expand-objs,$1) \
+       )$(LINKPROG) $(QEMU_CFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $1 \
        $(if $(filter %.lo %.la,$1),$(version-lobj-y),$(version-obj-y)) \
        $(if $(filter %.lo %.la,$1),$(LIBTOOLFLAGS)) \
        $(call extract-libs,$(1:.lo=.o)) $(LIBS),$(if $(filter %.lo %.la,$1),"lt LINK ", "  LINK  ")"$(TARGET_DIR)$@")
@@ -78,9 +74,9 @@
 %.o: %.dtrace
 	$(call quiet-command,dtrace -o $@ -G -s $<, "  GEN   $(TARGET_DIR)$@")
 
-DSO_CFLAGS := -fPIC -DBUILD_DSO
+%$(DSOSUF): CFLAGS += -fPIC -DBUILD_DSO
 %$(DSOSUF): LDFLAGS += $(LDFLAGS_SHARED)
-%$(DSOSUF): %.mo libqemustub.a
+%$(DSOSUF):
 	$(call LINK,$^)
 	@# Copy to build root so modules can be loaded when program started without install
 	$(if $(findstring /,$@),$(call quiet-command,cp $@ $(subst /,-,$@), "  CP    $(subst /,-,$@)"))
@@ -161,82 +157,165 @@
 # will delete the target of a rule if commands exit with a nonzero exit status
 .DELETE_ON_ERROR:
 
-# magic to descend into other directories
-
-define push-var
-$(eval save-$2-$1 = $(value $1))
-$(eval $1 :=)
+# save-vars
+# Usage: $(call save-vars, vars)
+# Save each variable $v in $vars as save-vars-$v, save their object's
+# variables, then clear $v.
+define save-vars
+    $(foreach v,$1,
+        $(eval save-vars-$v := $(value $v))
+        $(foreach o,$($v),
+            $(foreach k,cflags libs objs,
+                $(if $($o-$k),
+                    $(eval save-vars-$o-$k := $($o-$k))
+                    $(eval $o-$k := ))))
+        $(eval $v := ))
 endef
 
-define pop-var
-$(eval subdir-$2-$1 := $(if $(filter $2,$(save-$2-$1)),$(addprefix $2,$($1))))
-$(eval $1 = $(value save-$2-$1) $$(subdir-$2-$1))
-$(eval save-$2-$1 :=)
+# load-vars
+# Usage: $(call load-vars, vars, add_var)
+# Load the saved value for each variable in @vars, and the per object
+# variables.
+# Append @add_var's current value to the loaded value.
+define load-vars
+    $(eval $2-new-value := $(value $2))
+    $(foreach v,$1,
+        $(eval $v := $(value save-vars-$v))
+        $(foreach o,$($v),
+            $(foreach k,cflags libs objs,
+                $(if $(save-vars-$o-$k),
+                    $(eval $o-$k := $(save-vars-$o-$k))
+                    $(eval save-vars-$o-$k := ))))
+        $(eval save-vars-$v := ))
+    $(eval $2 := $(value $2) $($2-new-value))
 endef
 
-define fix-obj-vars
-$(if $2, $(foreach v,$($1), \
-	$(if $($v-cflags), \
-		$(eval $2/$v-cflags := $($v-cflags)) \
-		$(eval $v-cflags := )) \
-	$(if $($v-libs), \
-		$(eval $2/$v-libs := $($v-libs)) \
-		$(eval $v-libs := )) \
-	$(if $($v-objs), \
-		$(eval $2/$v-objs := $(addprefix $2/,$($v-objs))) \
-		$(eval $v-objs := ))))
+# fix-paths
+# Usage: $(call fix-paths, obj_path, src_path, vars)
+# Add prefix @obj_path to all objects in @vars, and add prefix @src_path to all
+# directories in @vars.
+define fix-paths
+    $(foreach v,$3,
+        $(foreach o,$($v),
+            $(if $($o-libs),
+                $(eval $1$o-libs := $($o-libs)))
+            $(if $($o-cflags),
+                $(eval $1$o-cflags := $($o-cflags)))
+            $(if $($o-objs),
+                $(eval $1$o-objs := $(addprefix $1,$($o-objs)))))
+        $(eval $v := $(addprefix $1,$(filter-out %/,$($v))) \
+                     $(addprefix $2,$(filter %/,$($v)))))
 endef
 
-define unnest-dir
-$(foreach var,$(nested-vars),$(call push-var,$(var),$1/))
-$(eval obj-parent-$1 := $(obj))
-$(eval obj := $(if $(obj),$(obj)/$1,$1))
-$(eval include $(SRC_PATH)/$1/Makefile.objs)
-$(foreach v,$(nested-vars),$(call fix-obj-vars,$v,$(obj)))
-$(eval obj := $(obj-parent-$1))
-$(eval obj-parent-$1 := )
-$(foreach var,$(nested-vars),$(call pop-var,$(var),$1/))
+# unnest-var-recursive
+# Usage: $(call unnest-var-recursive, obj_prefix, vars, var)
+#
+# Unnest @var by including subdir Makefile.objs, while protect others in @vars
+# unchanged.
+#
+# @obj_prefix is the starting point of object path prefix.
+#
+define unnest-var-recursive
+    $(eval dirs := $(sort $(filter %/,$($3))))
+    $(eval $3 := $(filter-out %/,$($3)))
+    $(foreach d,$(dirs:%/=%),
+            $(call save-vars,$2)
+            $(eval obj := $(if $1,$1/)$d)
+            $(eval -include $(SRC_PATH)/$d/Makefile.objs)
+            $(call fix-paths,$(if $1,$1/)$d/,$d/,$2)
+            $(call load-vars,$2,$3)
+            $(call unnest-var-recursive,$1,$2,$3))
 endef
 
-define unnest-vars-1
-$(eval nested-dirs := $(filter-out \
-    $(old-nested-dirs), \
-    $(sort $(foreach var,$(nested-vars), $(filter %/, $($(var)))))))
-$(if $(nested-dirs),
-  $(foreach dir,$(nested-dirs),$(call unnest-dir,$(patsubst %/,%,$(dir))))
-  $(eval old-nested-dirs := $(old-nested-dirs) $(nested-dirs))
-  $(call unnest-vars-1))
-endef
-
-define process-modules
-$(foreach o,$(filter %.o,$($1)),
-	$(eval $(patsubst %.o,%.mo,$o): $o) \
-	$(eval $(patsubst %.o,%.mo,$o)-objs := $o))
-$(foreach o,$(filter-out $(modules-m), $(patsubst %.o,%.mo,$($1))), \
-    $(eval $o-objs += module-common.o)
-    $(eval $o: $($o-objs))
-    $(eval modules-objs-m += $($o-objs))
-    $(eval modules-m += $o)
-    $(eval $o:; $$(call quiet-command,touch $$@,"  GEN   $$(TARGET_DIR)$$@"))
-    $(if $(CONFIG_MODULES),$(eval modules: $(patsubst %.mo,%$(DSOSUF),$o)))) \
-$(eval modules-objs-m := $(sort $(modules-objs-m)))
-$(foreach o,$(modules-objs-m), \
-    $(if $(CONFIG_MODULES),$(eval $o-cflags := $(call maybe-add, $(DSO_CFLAGS), $($o-cflags)))))
-$(eval $(patsubst %-m,%-$(call lnot,$(CONFIG_MODULES)),$1) += $($1))
-endef
-
+# unnest-vars
+# Usage: $(call unnest-vars, obj_prefix, vars)
+#
+# @obj_prefix: object path prefix, can be empty, or '..', etc. Don't include
+# ending '/'.
+#
+# @vars: the list of variable names to unnest.
+#
+# This macro will scan subdirectories's Makefile.objs, include them, to build
+# up each variable listed in @vars.
+#
+# Per object and per module cflags and libs are saved with relative path fixed
+# as well, those variables include -libs, -cflags and -objs. Items in -objs are
+# also fixed to relative path against SRC_PATH plus the prefix @obj_prefix.
+#
+# All nested variables postfixed by -m in names are treated as DSO variables,
+# and will be built as modules, if enabled.
+#
+# A simple example of the unnest:
+#
+#     obj_prefix = ..
+#     vars = hot cold
+#     hot  = fire.o sun.o season/
+#     cold = snow.o water/ season/
+#
+# Unnest through a faked source directory structure:
+#
+#     SRC_PATH
+#        ├── water
+#        │   └── Makefile.objs──────────────────┐
+#        │       │ hot += steam.o               │
+#        │       │ cold += ice.mo               │
+#        │       │ ice.mo-libs := -licemaker    │
+#        │       │ ice.mo-objs := ice1.o ice2.o │
+#        │       └──────────────────────────────┘
+#        │
+#        └── season
+#            └── Makefile.objs──────┐
+#                │ hot += summer.o  │
+#                │ cold += winter.o │
+#                └──────────────────┘
+#
+# In the end, the result will be:
+#
+#     hot  = ../fire.o ../sun.o ../season/summer.o
+#     cold = ../snow.o ../water/ice.mo ../season/winter.o
+#     ../water/ice.mo-libs = -licemaker
+#     ../water/ice.mo-objs = ../water/ice1.o ../water/ice2.o
+#
+# Note that 'hot' didn't include 'season/' in the input, so 'summer.o' is not
+# included.
+#
 define unnest-vars
-$(eval obj := $1)
-$(eval nested-vars := $2)
-$(foreach v,$(nested-vars),$(call fix-obj-vars,$v,$(obj)))
-$(eval old-nested-dirs := )
-$(call unnest-vars-1)
-$(if $1,$(foreach v,$(nested-vars),$(eval \
-	$v := $(addprefix $1/,$($v)))))
-$(foreach var,$(nested-vars),$(eval $(var) := $(filter-out %/, $($(var)))))
-$(shell mkdir -p $(sort $(foreach var,$(nested-vars),$(dir $($(var))))))
-$(foreach var,$(nested-vars), $(eval \
-  -include $(addsuffix *.d, $(sort $(dir $($(var)))))))
-$(foreach v,$(filter %-m,$(nested-vars)), \
-    $(call process-modules,$v))
+    # In the case of target build (i.e. $1 == ..), fix path for top level
+    # Makefile.objs objects
+    $(if $1,$(call fix-paths,$1/,,$2))
+
+    # Descend and include every subdir Makefile.objs
+    $(foreach v, $2, $(call unnest-var-recursive,$1,$2,$v))
+
+    $(foreach v,$(filter %-m,$2),
+        # All .o found in *-m variables are single object modules, create .mo
+        # for them
+        $(foreach o,$(filter %.o,$($v)),
+            $(eval $(o:%.o=%.mo)-objs := $o))
+        # Now unify .o in -m variable to .mo
+        $(eval $v := $($v:%.o=%.mo))
+        $(eval modules-m += $($v))
+
+        # For module build, build shared libraries during "make modules"
+        # For non-module build, add -m to -y
+        $(if $(CONFIG_MODULES),
+             $(eval modules: $($v:%.mo=%$(DSOSUF))),
+             $(eval $(patsubst %-m,%-y,$v) += $(call expand-objs, $($v)))))
+
+    # Post-process all the unnested vars
+    $(foreach v,$2,
+        $(foreach o, $(filter %.mo,$($v)),
+            # Find all the .mo objects in variables and add dependency rules
+            # according to .mo-objs. Report error if not set
+            $(if $($o-objs),
+                $(eval $(o:%.mo=%$(DSOSUF)): module-common.o $($o-objs)),
+                $(error $o added in $v but $o-objs is not set))
+            # Pass the .mo-cflags and .mo-libs along to member objects
+            $(foreach p,$($o-objs),
+                $(if $($o-cflags), $(eval $p-cflags += $($o-cflags)))
+                $(if $($o-libs), $(eval $p-libs += $($o-libs)))))
+        $(shell mkdir -p ./ $(sort $(dir $($v))))
+        # Include all the .d files
+        $(eval -include $(addsuffix *.d, $(sort $(dir $($v)))))
+        $(eval $v := $(filter-out %/,$($v))))
 endef
diff --git a/trace/simple.c b/trace/simple.c
index a8f923c..11ad030 100644
--- a/trace/simple.c
+++ b/trace/simple.c
@@ -40,28 +40,9 @@
  * Trace records are written out by a dedicated thread.  The thread waits for
  * records to become available, writes them out, and then waits again.
  */
-#if GLIB_CHECK_VERSION(2, 32, 0)
-static GMutex trace_lock;
-#define lock_trace_lock() g_mutex_lock(&trace_lock)
-#define unlock_trace_lock() g_mutex_unlock(&trace_lock)
-#define get_trace_lock_mutex() (&trace_lock)
-#else
-static GStaticMutex trace_lock = G_STATIC_MUTEX_INIT;
-#define lock_trace_lock() g_static_mutex_lock(&trace_lock)
-#define unlock_trace_lock() g_static_mutex_unlock(&trace_lock)
-#define get_trace_lock_mutex() g_static_mutex_get_mutex(&trace_lock)
-#endif
-
-/* g_cond_new() was deprecated in glib 2.31 but we still need to support it */
-#if GLIB_CHECK_VERSION(2, 31, 0)
-static GCond the_trace_available_cond;
-static GCond the_trace_empty_cond;
-static GCond *trace_available_cond = &the_trace_available_cond;
-static GCond *trace_empty_cond = &the_trace_empty_cond;
-#else
-static GCond *trace_available_cond;
-static GCond *trace_empty_cond;
-#endif
+static CompatGMutex trace_lock;
+static CompatGCond trace_available_cond;
+static CompatGCond trace_empty_cond;
 
 static bool trace_available;
 static bool trace_writeout_enabled;
@@ -151,26 +132,26 @@
  */
 static void flush_trace_file(bool wait)
 {
-    lock_trace_lock();
+    g_mutex_lock(&trace_lock);
     trace_available = true;
-    g_cond_signal(trace_available_cond);
+    g_cond_signal(&trace_available_cond);
 
     if (wait) {
-        g_cond_wait(trace_empty_cond, get_trace_lock_mutex());
+        g_cond_wait(&trace_empty_cond, &trace_lock);
     }
 
-    unlock_trace_lock();
+    g_mutex_unlock(&trace_lock);
 }
 
 static void wait_for_trace_records_available(void)
 {
-    lock_trace_lock();
+    g_mutex_lock(&trace_lock);
     while (!(trace_available && trace_writeout_enabled)) {
-        g_cond_signal(trace_empty_cond);
-        g_cond_wait(trace_available_cond, get_trace_lock_mutex());
+        g_cond_signal(&trace_empty_cond);
+        g_cond_wait(&trace_available_cond, &trace_lock);
     }
     trace_available = false;
-    unlock_trace_lock();
+    g_mutex_unlock(&trace_lock);
 }
 
 static gpointer writeout_thread(gpointer opaque)
@@ -383,11 +364,7 @@
     pthread_sigmask(SIG_SETMASK, &set, &oldset);
 #endif
 
-#if GLIB_CHECK_VERSION(2, 31, 0)
     thread = g_thread_new("trace-thread", fn, NULL);
-#else
-    thread = g_thread_create(fn, NULL, FALSE, NULL);
-#endif
 
 #ifndef _WIN32
     pthread_sigmask(SIG_SETMASK, &oldset, NULL);
@@ -402,11 +379,6 @@
 
     trace_pid = getpid();
 
-#if !GLIB_CHECK_VERSION(2, 31, 0)
-    trace_available_cond = g_cond_new();
-    trace_empty_cond = g_cond_new();
-#endif
-
     thread = trace_thread_create(writeout_thread);
     if (!thread) {
         fprintf(stderr, "warning: unable to initialize simple trace backend\n");
diff --git a/util/hbitmap.c b/util/hbitmap.c
index d936831..b3060e6 100644
--- a/util/hbitmap.c
+++ b/util/hbitmap.c
@@ -92,11 +92,6 @@
     unsigned long *levels[HBITMAP_LEVELS];
 };
 
-static inline int popcountl(unsigned long l)
-{
-    return BITS_PER_LONG == 32 ? ctpop32(l) : ctpop64(l);
-}
-
 /* Advance hbi to the next nonzero word and return it.  hbi->pos
  * is updated.  Returns zero if we reach the end of the bitmap.
  */
@@ -200,14 +195,14 @@
         if (pos >= (end >> BITS_PER_LEVEL)) {
             break;
         }
-        count += popcountl(cur);
+        count += ctpopl(cur);
     }
 
     if (pos == (end >> BITS_PER_LEVEL)) {
         /* Drop bits representing the END-th and subsequent items.  */
         int bit = end & (BITS_PER_LONG - 1);
         cur &= (1UL << bit) - 1;
-        count += popcountl(cur);
+        count += ctpopl(cur);
     }
 
     return count;
diff --git a/util/qemu-openpty.c b/util/qemu-openpty.c
index 4febfe9..4c53211 100644
--- a/util/qemu-openpty.c
+++ b/util/qemu-openpty.c
@@ -47,6 +47,8 @@
 #elif defined CONFIG_SOLARIS
 # include <termios.h>
 # include <stropts.h>
+#else
+# include <termios.h>
 #endif
 
 #ifdef __sun__
diff --git a/util/readline.c b/util/readline.c
index 8baec55..cc1302a 100644
--- a/util/readline.c
+++ b/util/readline.c
@@ -263,6 +263,12 @@
 void readline_add_completion(ReadLineState *rs, const char *str)
 {
     if (rs->nb_completions < READLINE_MAX_COMPLETIONS) {
+        int i;
+        for (i = 0; i < rs->nb_completions; i++) {
+            if (!strcmp(rs->completions[i], str)) {
+                return;
+            }
+        }
         rs->completions[rs->nb_completions++] = g_strdup(str);
     }
 }
@@ -345,6 +351,12 @@
     }
 }
 
+static void readline_clear_screen(ReadLineState *rs)
+{
+    rs->printf_func(rs->opaque, "\033[2J\033[1;1H");
+    readline_show_prompt(rs);
+}
+
 /* return true if command handled */
 void readline_handle_byte(ReadLineState *rs, int ch)
 {
@@ -363,6 +375,9 @@
         case 9:
             readline_completion(rs);
             break;
+        case 12:
+            readline_clear_screen(rs);
+            break;
         case 10:
         case 13:
             rs->cmd_buf[rs->cmd_buf_size] = '\0';
diff --git a/xen-hvm.c b/xen-hvm.c
index a64486c..aac38ef 100644
--- a/xen-hvm.c
+++ b/xen-hvm.c
@@ -511,7 +511,7 @@
     for (i = 0; i < ARRAY_SIZE(bitmap); i++) {
         unsigned long map = bitmap[i];
         while (map != 0) {
-            j = ffsl(map) - 1;
+            j = ctzl(map);
             map &= ~(1ul << j);
             memory_region_set_dirty(framebuffer,
                                     (i * width + j) * TARGET_PAGE_SIZE,